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

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

// Speaker type constants
const INDIVIDUAL_SPEAKER_TYPE_OF_ID = 1;
const REPRESENTATIVE_SPEAKER_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 AdminSpeakerAddStep2Page() {
  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) {
      if (import.meta.env.DEV) {
        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 speaker creation state or create new one
      let speakerState = {};
      try {
        const existing = sessionStorage.getItem(
          "FLASHPOINTTRAINING_SPEAKER_CREATION_STATE",
        );
        if (existing) {
          speakerState = JSON.parse(existing);
        }
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Error parsing speaker state:", error);
        }
      }

      // Set the type
      speakerState.type = typeId;

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

      // Save to session storage
      try {
        sessionStorage.setItem(
          "FLASHPOINTTRAINING_SPEAKER_CREATION_STATE",
          JSON.stringify(speakerState),
        );
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Error saving speaker state:", error);
        }
      }

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

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

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

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={2}
        title="Add New Speaker"
        subtitle="Select the type of speaker you want to create"
        icon={ChatBubbleBottomCenterIcon}
      >
        <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 AdminSpeakerAddStep2Page;
