// File Path: monorepo/web/frontend/src/pages/Admin/Facilitator/Add/Step2Page.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router";
import {
  useAuthManager,
  useAccountManager,
} from "../../../../services/Services";
import {
  WrenchScrewdriverIcon,
  BuildingOffice2Icon,
  UserIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import {
  UIXThemeProvider,
  StepWizard,
  CardSelectionGrid,
  Button,
} from "../../../../components/UIX";

// Facilitator type constants
const INDIVIDUAL_FACILITATOR_TYPE_OF_ID = 1;
const REPRESENTATIVE_FACILITATOR_TYPE_OF_ID = 2;

// Wizard steps configuration - moved outside component
const WIZARD_STEPS = [
  { title: "Search" },
  { title: "Type", isCompleted: false },
  { title: "Contact" },
  { title: "Address" },
  { title: "Account" },
  { title: "Metrics" },
  { title: "Review" },
];

// Mark step 1 as completed
WIZARD_STEPS[0].isCompleted = true;

function AdminFacilitatorAddStep2Page() {
  const authManager = useAuthManager();
  const accountManager = useAccountManager();
  const navigate = useNavigate();

  // Component states
  const [currentUser, setCurrentUser] = useState(null);
  const [selectedType, setSelectedType] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  // Check authentication
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    // Fetch current user for country info
    fetchCurrentUser();
  }, [authManager, navigate]);

  const fetchCurrentUser = useCallback(async () => {
    try {
      const user = await accountManager.getAccountDetail(() =>
        navigate("/login?unauthorized=true"),
      );
      setCurrentUser(user);
    } catch (error) {
      console.error("Failed to fetch current user:", error);
    }
  }, [accountManager, navigate]);

  const onSelectType = useCallback((typeId) => {
    // Set visual selection state
    setSelectedType(typeId);
    setIsLoading(true);

    // Animate the selection before navigating
    setTimeout(() => {
      // Get existing facilitator creation state or create new one
      let facilitatorState = {};
      try {
        const existing = sessionStorage.getItem(
          "FLASHPOINTTRAINING_FACILITATOR_CREATION_STATE",
        );
        if (existing) {
          facilitatorState = JSON.parse(existing);
        }
      } catch (error) {
        console.error("Error parsing facilitator state:", error);
      }

      // Set the type
      facilitatorState.type = typeId;

      // Set default country based on current user's country
      if (currentUser?.country) {
        facilitatorState.country = currentUser.country;
      } else {
        facilitatorState.country = "Canada"; // Default fallback
      }

      // Save to session storage
      try {
        sessionStorage.setItem(
          "FLASHPOINTTRAINING_FACILITATOR_CREATION_STATE",
          JSON.stringify(facilitatorState),
        );
      } catch (error) {
        console.error("Error saving facilitator state:", error);
      }

      // Navigate to next step
      navigate("/admin/facilitators/add/step-3");
    }, 300);
  }, [currentUser, navigate]);

  const handleCancel = useCallback(() => {
    navigate("/admin/facilitators");
  }, [navigate]);

  // Card selection options
  const selectionOptions = useMemo(() => [
    {
      title: "Individual",
      icon: UserIcon,
      buttonLabel: "Select Individual",
      onClick: () => onSelectType(INDIVIDUAL_FACILITATOR_TYPE_OF_ID),
      variant: "success",
    },
    {
      title: "Business",
      icon: BuildingOffice2Icon,
      buttonLabel: "Select Business",
      onClick: () => onSelectType(REPRESENTATIVE_FACILITATOR_TYPE_OF_ID),
      variant: "primary",
    },
  ], [onSelectType]);

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={2}
        title="Add New Facilitator"
        subtitle="Select the type of facilitator you want to create"
        icon={WrenchScrewdriverIcon}
      >
        <div className="max-w-4xl mx-auto space-y-6">
          <CardSelectionGrid
            options={selectionOptions}
            layout="2-card"
            selectedValue={selectedType}
            isLoading={isLoading}
            showSelectionStatus={false}
          />

          {/* Cancel Button */}
          <div className="flex justify-start">
            <Button
              variant="outline"
              onClick={handleCancel}
              icon={XMarkIcon}
            >
              Cancel
            </Button>
          </div>
        </div>
      </StepWizard>
    </UIXThemeProvider>
  );
}

export default AdminFacilitatorAddStep2Page;
