// monorepo/web/frontend/src/pages/Admin/Organization/Add/Step2Page.jsx

import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router";
import { useOrganizationWizardStorage } from "../../../../services/Services";
import {
  BuildingOffice2Icon,
  UserGroupIcon,
  AcademicCapIcon,
  BriefcaseIcon,
  BuildingLibraryIcon,
  BuildingOfficeIcon,
  HeartIcon,
} from "@heroicons/react/24/outline";
import {
  StaffWizardFormStep,
  CardSelectionGrid,
  UIXThemeProvider,
} from "../../../../components/UIX";

function AdminOrganizationAddStep2Page() {
  const navigate = useNavigate();
  const wizardStorage = useOrganizationWizardStorage();

  // Component states
  const [errors, setErrors] = useState({});
  const [selectedType, setSelectedType] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  // Wizard configuration
  const wizardSteps = [
    { title: "Search" },
    { title: "Type" },
    { title: "Contact" },
    { title: "Address" },
    { title: "Additional" },
    { title: "Review" },
  ];

  // Organization type options
  const organizationTypeOptions = [
    {
      title: "Educational",
      description: "",
      icon: AcademicCapIcon,
      buttonLabel: "Select Educational",
      onClick: () => handleSelectType("educational"),
      variant: "primary",
    },
    {
      title: "Corporate",
      description: "",
      icon: BriefcaseIcon,
      buttonLabel: "Select Corporate",
      onClick: () => handleSelectType("corporate"),
      variant: "primary",
    },
    {
      title: "Non-Profit",
      description: "",
      icon: HeartIcon,
      buttonLabel: "Select Non-Profit",
      onClick: () => handleSelectType("non-profit"),
      variant: "primary",
    },
    {
      title: "Government",
      description: "",
      icon: BuildingLibraryIcon,
      buttonLabel: "Select Government",
      onClick: () => handleSelectType("government"),
      variant: "primary",
    },
  ];

  // Load existing data on component mount
  useEffect(() => {
    // Load existing step 2 data
    const step2Data = wizardStorage.getStepData("step2Data");
    if (step2Data && step2Data.organizationType) {
      setSelectedType(step2Data.organizationType);
    }
  }, [wizardStorage]);

  // Handle type selection
  const handleSelectType = async (typeId) => {
    if (isLoading) return;

    setIsLoading(true);
    setSelectedType(typeId);
    setErrors({});

    try {
      // Get existing step1 data or create default
      let step1Data = wizardStorage.getStepData("step1Data");
      if (!step1Data) {
        step1Data = {
          searchCompleted: true,
          fromStep2: true,
          timestamp: new Date().toISOString(),
        };
        wizardStorage.saveStepData("step1Data", step1Data);
      }

      // Create Step 2 data
      const step2Data = {
        organizationType: typeId,
        timestamp: new Date().toISOString(),
      };

      // Save step 2 data
      wizardStorage.saveStepData("step2Data", step2Data);

      // Small delay for user feedback
      await new Promise((resolve) => setTimeout(resolve, 500));

      // Navigate to next step
      navigate("/admin/organizations/add/step-3");
    } catch (error) {
      // Error saving organization type
      setErrors({ message: "Failed to save selection. Please try again." });
      setSelectedType(null);
    } finally {
      setIsLoading(false);
    }
  };

  // Handle back navigation
  const handleBack = () => {
    navigate("/admin/organizations/add/step-1-search");
  };

  // Handle cancel
  const handleCancel = () => {
    wizardStorage.clearWizardData();
    navigate("/admin/organizations");
  };

  return (
    <UIXThemeProvider>
      <StaffWizardFormStep
        wizardSteps={wizardSteps}
        currentStep={2}
        wizardTitle="Add New Organization"
        wizardIcon={BuildingOffice2Icon}
        stepTitle="Select Organization Type"
        stepSubtitle="Please select the type of organization"
        stepIcon={UserGroupIcon}
        errors={errors}
        isLoading={isLoading}
        showFormCard={true}
        actionLayout="center"
        contentMaxWidth="6xl"
        showActions={false}
        onBack={handleBack}
        backLabel="Back to Search"
      >
        {/* Organization Type Selection */}
        <CardSelectionGrid
          options={organizationTypeOptions}
          layout="4-card"
          selectedValue={selectedType}
          onFormatSelectedLabel={(value) =>
            value.charAt(0).toUpperCase() + value.slice(1).replace("-", " ")
          }
          isLoading={isLoading}
          variant="primary"
          showSelectionStatus={true}
        />

      </StaffWizardFormStep>
    </UIXThemeProvider>
  );
}

export default AdminOrganizationAddStep2Page;