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

import React, { useState, useEffect, useMemo, useCallback } from "react";
import { useNavigate } from "react-router";
import { useAuthManager } from "../../../../services/Services";
import { StepWizard, FormCard, Button, CardSelectionGrid, Alert, UIXThemeProvider, useUIXTheme } from "../../../../components/UIX";
import {
  OrganizationSelect,
  DivisionSelect,
} from "../../../../components/business/selects";
import {
  CUSTOMER_TYPE_MAPPING,
  CUSTOMER_TYPE_VALUES,
  CUSTOMER_TYPE_OPTIONS,
  CUSTOMER_STATUS,
} from "../../../../constants/Customer";
import {
  UserPlusIcon,
  ChevronRightIcon,
  ArrowLeftIcon,
  UserGroupIcon,
  BuildingOfficeIcon,
  ExclamationCircleIcon,
  AcademicCapIcon,
  BriefcaseIcon,
  BuildingLibraryIcon,
} from "@heroicons/react/24/outline";

const STORAGE_KEY = "FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE";

// Wizard steps configuration for StepWizard component
const WIZARD_STEPS = [
  { id: 1, title: "Search", isCompleted: true },
  { id: 2, title: "Type", isCompleted: false },
  { id: 3, title: "Contact", isCompleted: false },
  { id: 4, title: "Address", isCompleted: false },
  { id: 5, title: "Account", isCompleted: false },
  { id: 6, title: "Comments", isCompleted: false },
];

function AdminCustomerAddStep2Page() {
  const authManager = useAuthManager();
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

  // Form states
  const [customerType, setCustomerType] = useState("");
  const [organizationId, setOrganizationId] = useState("");
  const [divisionId, setDivisionId] = useState("");
  const [error, setError] = useState("");

  // Check auth and load saved data
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    // Load saved data only once on mount
    try {
      const saved = sessionStorage.getItem(STORAGE_KEY);
      if (saved) {
        const data = JSON.parse(saved);

        // Load the string customer type (for the select dropdown)
        if (data.customerTypeString) {
          setCustomerType(data.customerTypeString);
        }
        if (data.organization_id) setOrganizationId(data.organization_id);
        if (data.division_id) setDivisionId(data.division_id);
      }
    } catch (err) {
      if (import.meta.env.DEV) {
        console.error("Error loading saved data:", err);
      }
    }
  }, [authManager, navigate]);

  // Event handlers - memoized
  const handleTypeSelection = useCallback((type) => {
    setCustomerType(type);
    // IMPORTANT: Clear both organization and division when type changes
    setOrganizationId("");
    setDivisionId("");
    setError("");
  }, []);

  // Card selection options for CardSelectionGrid - memoized
  const selectionOptions = useMemo(() => [
    {
      title: "Educational",
      icon: AcademicCapIcon,
      buttonLabel: "Select Educational",
      onClick: () => handleTypeSelection(CUSTOMER_TYPE_VALUES.EDUCATIONAL),
      variant: "error", // Red theme
      value: CUSTOMER_TYPE_VALUES.EDUCATIONAL,
    },
    {
      title: "Corporate",
      icon: BriefcaseIcon,
      buttonLabel: "Select Corporate",
      onClick: () => handleTypeSelection(CUSTOMER_TYPE_VALUES.CORPORATE),
      variant: "info", // Blue theme
      value: CUSTOMER_TYPE_VALUES.CORPORATE,
    },
    {
      title: "Non-Profit",
      icon: UserGroupIcon,
      buttonLabel: "Select Non-Profit",
      onClick: () => handleTypeSelection(CUSTOMER_TYPE_VALUES.NON_PROFIT),
      variant: "success", // Green theme
      value: CUSTOMER_TYPE_VALUES.NON_PROFIT,
    },
    {
      title: "Government",
      icon: BuildingLibraryIcon,
      buttonLabel: "Select Government",
      onClick: () => handleTypeSelection(CUSTOMER_TYPE_VALUES.GOVERNMENT),
      variant: "warning", // Orange/Yellow theme
      value: CUSTOMER_TYPE_VALUES.GOVERNMENT,
    },
  ], [handleTypeSelection]);

  const handleOrganizationChange = useCallback((value) => {
    setOrganizationId(value);
    // Clear division when organization changes
    setDivisionId("");
  }, []);

  const handleDivisionChange = useCallback((value) => {
    setDivisionId(value);
  }, []);

  const handleNext = useCallback(() => {
    if (!customerType) {
      setError("Please select a customer type");
      return;
    }

    if (!organizationId) {
      setError("Please select an organization");
      return;
    }

    if (!divisionId) {
      setError("Please select a division");
      return;
    }

    // Get the numeric type based on the string customer type
    const numericType = CUSTOMER_TYPE_MAPPING[customerType];
    if (!numericType) {
      setError("Invalid customer type selected");
      return;
    }

    const data = {
      // Store the numeric type for the backend
      type: numericType,
      // Store the organization and division IDs
      organization_id: organizationId,
      division_id: divisionId,
      // Also store the original string for display purposes
      customerTypeString: customerType,
      country: "Canada",
    };

    sessionStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    navigate("/admin/customers/add/step-3");
  }, [customerType, organizationId, divisionId, navigate]);

  // Memoize form actions
  const formActions = useMemo(() => (
    <div className="flex flex-col sm:flex-row gap-3">
      <Button
        variant="outline"
        onClick={() => navigate("/admin/customers/add/step-1-search")}
        icon={ArrowLeftIcon}
      >
        Back
      </Button>
      <Button
        variant="primary"
        onClick={handleNext}
        disabled={!customerType || !organizationId || !divisionId}
      >
        Next
      </Button>
    </div>
  ), [customerType, organizationId, divisionId, handleNext, navigate]);

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={2}
        title="Add New Customer"
        icon={UserPlusIcon}
      >
      <FormCard
        title="Select Customer Type"
        icon={BuildingOfficeIcon}
        actions={formActions}
        maxWidth="7xl"
      >
            <div className="space-y-6">
              {/* Error Alert */}
              {error && !customerType && (
                <Alert
                  type="error"
                  message={error}
                  className="mb-4"
                />
              )}

              {/* Customer Type Selection */}
              <div>
                <CardSelectionGrid
                  options={selectionOptions}
                  layout="4-card"
                  selectedValue={customerType}
                  isLoading={false}
                  showSelectionStatus={false}
                />
              </div>

              {/* Organization Selection - Only show when type is selected */}
              {customerType && (
                <div className="transition-all duration-300 ease-in-out">
                  <h3 className={`text-lg font-medium ${getThemeClasses('text-primary')} mb-3`}>
                    Select Organization{" "}
                    <span className="text-red-600">*</span>
                  </h3>
                  <div className={`max-w-2xl mx-auto ${getThemeClasses('bg-muted')} border ${getThemeClasses('border-border')} rounded-lg p-4`}>
                    <OrganizationSelect
                      key={`org-${customerType}`} // Force re-mount when type changes
                      value={organizationId}
                      onChange={handleOrganizationChange}
                      required={true}
                      label=""
                      placeholder="Select organization..."
                      onUnauthorized={() => navigate("/login?unauthorized=true")}
                      forceRefresh={true} // Force fresh data
                      error={
                        error && !organizationId
                          ? "Please select an organization"
                          : ""
                      }
                    />
                  </div>
                </div>
              )}

              {/* Division Selection - Only show when both type and organization are selected */}
              {customerType && organizationId && (
                <div className="transition-all duration-300 ease-in-out">
                  <h3 className={`text-lg font-medium ${getThemeClasses('text-primary')} mb-3`}>
                    Select Division{" "}
                    <span className="text-red-600">*</span>
                  </h3>
                  <div className={`max-w-2xl mx-auto ${getThemeClasses('bg-muted')} border ${getThemeClasses('border-border')} rounded-lg p-4`}>
                    <DivisionSelect
                      key={`div-${organizationId}`} // Force re-mount when organization changes
                      value={divisionId}
                      onChange={handleDivisionChange}
                      required={true}
                      label=""
                      placeholder="Select division..."
                      onUnauthorized={() => navigate("/login?unauthorized=true")}
                      organizationId={organizationId}
                      forceRefresh={true} // Force fresh data
                      error={
                        error && !divisionId ? "Please select a division" : ""
                      }
                    />
                  </div>
                </div>
              )}
            </div>
      </FormCard>
    </StepWizard>
    </UIXThemeProvider>
  );
}

export default AdminCustomerAddStep2Page;
