// File path: monorepo/web/frontend/src/pages/Admin/Division/Add/Step2Page.jsx
import React, {
  useState,
  useEffect,
  useRef,
  useCallback,
  useMemo,
} from "react";
import { useNavigate } from "react-router";
import { OrganizationSelect } from "../../../../components/business/selects";
import {
  useAuthManager,
  useDivisionWizardStorage,
} from "../../../../services/Services";
import {
  BuildingOffice2Icon,
  AcademicCapIcon,
  BriefcaseIcon,
  UserGroupIcon,
  BuildingLibraryIcon,
} from "@heroicons/react/24/outline";
import {
  StaffWizardFormStep,
  UIXThemeProvider,
  CardSelectionGrid,
  useUIXTheme,
  Button,
} from "../../../../components/UIX";

// Import organization type constants from the OrganizationSelect component
import {
  ORGANIZATION_TYPE_EDUCATIONAL,
  ORGANIZATION_TYPE_CORPORATE,
  ORGANIZATION_TYPE_NONPROFIT,
  ORGANIZATION_TYPE_GOVERNMENT,
} from "../../../../components/business/selects/OrganizationSelect";

// Division Type Constants (matching backend: cloud/backend/app/division/datastore/datastore.go)
const DIVISION_TYPE_EDUCATIONAL = 1;
const DIVISION_TYPE_CORPORATE = 2;
const DIVISION_TYPE_NONPROFIT = 3;
const DIVISION_TYPE_GOVERNMENT = 4;

// Map division types to organization types
const DIVISION_TYPE_TO_ORG_TYPE = {
  [DIVISION_TYPE_EDUCATIONAL]: ORGANIZATION_TYPE_EDUCATIONAL,
  [DIVISION_TYPE_CORPORATE]: ORGANIZATION_TYPE_CORPORATE,
  [DIVISION_TYPE_NONPROFIT]: ORGANIZATION_TYPE_NONPROFIT,
  [DIVISION_TYPE_GOVERNMENT]: ORGANIZATION_TYPE_GOVERNMENT,
};

// SECURITY: Input sanitization to prevent XSS
const sanitizeInput = (input) => {
  if (typeof input !== 'string') return input;
  return input.trim().replace(/[<>]/g, '');
};

// PERFORMANCE: Move wizard steps outside component
const WIZARD_STEPS = [
  { title: "Search" },
  { title: "Type" },
  { title: "Contact" },
  { title: "Address" },
  { title: "Additional" },
  { title: "Review" },
];

function AdminDivisionAddStep2Page() {
  const navigate = useNavigate();
  const authManager = useAuthManager();
  const wizardStorage = useDivisionWizardStorage();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [selectedType, setSelectedType] = useState(null);
  const [selectedOrganization, setSelectedOrganization] = useState("");
  const [selectedOrganizationName, setSelectedOrganizationName] = useState("");
  const organizationSelectRef = useRef(null);

  // SECURITY & PERFORMANCE: Authentication check and load existing data (run once on mount)
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    const step2Data = wizardStorage.getStepData("step2Data");
    if (step2Data) {
      setSelectedType(step2Data.divisionType || null);
      setSelectedOrganization(step2Data.organizationId || "");
      setSelectedOrganizationName(step2Data.organizationName || "");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Division type options for CardSelectionGrid (using integer values)
  const divisionTypes = useMemo(
    () => [
      {
        title: "Educational",
        description: "",
        icon: AcademicCapIcon,
        buttonLabel: "Select Educational",
        onClick: () => handleTypeSelection(DIVISION_TYPE_EDUCATIONAL),
        variant: "primary",
        value: DIVISION_TYPE_EDUCATIONAL, // 1
      },
      {
        title: "Corporate",
        description: "",
        icon: BriefcaseIcon,
        buttonLabel: "Select Corporate",
        onClick: () => handleTypeSelection(DIVISION_TYPE_CORPORATE),
        variant: "primary",
        value: DIVISION_TYPE_CORPORATE, // 2
      },
      {
        title: "Non-Profit",
        description: "",
        icon: UserGroupIcon,
        buttonLabel: "Select Non-Profit",
        onClick: () => handleTypeSelection(DIVISION_TYPE_NONPROFIT),
        variant: "primary",
        value: DIVISION_TYPE_NONPROFIT, // 3
      },
      {
        title: "Government",
        description: "",
        icon: BuildingLibraryIcon,
        buttonLabel: "Select Government",
        onClick: () => handleTypeSelection(DIVISION_TYPE_GOVERNMENT),
        variant: "primary",
        value: DIVISION_TYPE_GOVERNMENT, // 4
      },
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  // Handle type selection
  const handleTypeSelection = useCallback(
    (type) => {
      setSelectedType(type);
      setSelectedOrganization("");
      setSelectedOrganizationName("");
      // Clear errors
      if (errors.divisionType || errors.organizationId) {
        setErrors((prev) => ({
          ...prev,
          divisionType: "",
          organizationId: "",
        }));
      }
    },
    [errors.divisionType, errors.organizationId],
  );

  // Handle organization selection
  const handleOrganizationChange = useCallback((value) => {
    setSelectedOrganization(value);
  }, []);

  // PERFORMANCE: Extract organization name from select element with proper cleanup
  useEffect(() => {
    if (!selectedOrganization) return;

    const timeoutId = setTimeout(() => {
      if (organizationSelectRef.current) {
        const selectElement =
          organizationSelectRef.current.querySelector("select");
        if (selectElement && selectElement.selectedOptions.length > 0) {
          const selectedOption = selectElement.selectedOptions[0];
          setSelectedOrganizationName(selectedOption.text);
        }
      }
    }, 100);

    // Cleanup function to prevent memory leaks
    return () => clearTimeout(timeoutId);
  }, [selectedOrganization]);

  // Validation function
  const validateForm = useCallback(() => {
    const newErrors = {};

    if (!selectedType) {
      newErrors.divisionType = "Division type is required";
    }
    if (selectedType && !selectedOrganization) {
      newErrors.organizationId = "Organization is required";
    }

    return newErrors;
  }, [selectedType, selectedOrganization]);

  // Handle form submission
  const handleSubmit = useCallback(
    (e) => {
      e.preventDefault();

      const validationErrors = validateForm();
      if (Object.keys(validationErrors).length > 0) {
        setErrors(validationErrors);
        return;
      }

      setIsLoading(true);
      setErrors({});

      try {
        // Get organization name if not available
        let orgName = selectedOrganizationName;
        if (!orgName && organizationSelectRef.current) {
          const selectElement =
            organizationSelectRef.current.querySelector("select");
          if (selectElement && selectElement.selectedOptions.length > 0) {
            orgName = selectElement.selectedOptions[0].text;
          }
        }

        // SECURITY: Save division type and organization data with sanitization
        const step2Data = {
          divisionType: selectedType,
          organizationId: sanitizeInput(selectedOrganization),
          organizationName: sanitizeInput(orgName || selectedOrganizationName),
          timestamp: new Date().toISOString(),
        };

        wizardStorage.saveStepData("step2Data", step2Data);

        // Navigate to next step
        navigate("/admin/divisions/add/step-3");
      } catch (error) {
        setErrors({
          submit:
            error.message || "Failed to save division type and organization",
        });
      } finally {
        setIsLoading(false);
      }
    },
    [
      selectedType,
      selectedOrganization,
      selectedOrganizationName,
      validateForm,
      wizardStorage,
      navigate,
    ],
  );

  // Handle cancel
  const handleCancel = useCallback(() => {
    wizardStorage.clearWizardData();
    navigate("/admin/divisions");
  }, [wizardStorage, navigate]);

  // Handle previous step
  const handlePrevious = useCallback(() => {
    navigate("/admin/divisions/add/step-1-search");
  }, [navigate]);

  // Handle changing division type (go back to selection)
  const handleChangeDivisionType = useCallback(() => {
    setSelectedType(null);
    setSelectedOrganization("");
    setSelectedOrganizationName("");
    setErrors({});
  }, []);

  // Get division type display name
  const getDivisionTypeName = useCallback((type) => {
    const typeObj = divisionTypes.find(t => t.value === type);
    return typeObj ? typeObj.title : "";
  }, [divisionTypes]);

  // Handle unauthorized access
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  return (
    <UIXThemeProvider>
      <StaffWizardFormStep
        wizardSteps={WIZARD_STEPS}
        currentStep={2}
        wizardTitle="Add New Division"
        wizardIcon={BuildingOffice2Icon}
        stepTitle="Division Type and Organization"
        errors={errors}
        isLoading={isLoading}
        showFormCard={true}
        actionLayout="between"
        contentMaxWidth="6xl"
        onBack={handlePrevious}
        onCancel={handleCancel}
        backLabel="Back to Search"
        cancelLabel="Cancel"
        showActions={!!selectedType}
        actions={selectedType ? [
          {
            label: "Continue to Contact",
            onClick: handleSubmit,
            variant: "primary",
            disabled: isLoading,
            loading: isLoading,
          },
        ] : []}
      >
        {/* STATE 1: Division Type Selection - Show when no type is selected */}
        {!selectedType && (
          <div>
            <CardSelectionGrid
              options={divisionTypes}
              layout="4-card"
              selectedValue={selectedType}
              onFormatSelectedLabel={(value) => {
                const type = divisionTypes.find(t => t.value === value);
                return type ? type.title : String(value);
              }}
              isLoading={isLoading}
              variant="primary"
              showSelectionStatus={false}
            />
            {errors.divisionType && (
              <p className={`mt-2 text-sm ${getThemeClasses('text-danger')} text-center`}>{errors.divisionType}</p>
            )}
          </div>
        )}

        {/* STATE 2: Organization Selection - Show when type is selected */}
        {selectedType && (
          <div className="space-y-6">
            {/* Selected Division Type Badge with Change Button */}
            <div className={`flex items-center justify-between p-4 ${getThemeClasses('bg-muted')} rounded-lg shadow-sm border ${getThemeClasses('border-secondary')}`}>
              <div className="flex items-center gap-3">
                <BuildingOffice2Icon className={`w-6 h-6 ${getThemeClasses('text-primary')}`} />
                <div>
                  <p className={`text-sm ${getThemeClasses('text-muted')}`}>Division Type</p>
                  <p className={`text-lg font-semibold ${getThemeClasses('text-primary')}`}>
                    {getDivisionTypeName(selectedType)}
                  </p>
                </div>
              </div>
              <Button
                variant="outline"
                size="md"
                onClick={handleChangeDivisionType}
                disabled={isLoading}
              >
                Change Type
              </Button>
            </div>

            {/* Parent Organization Section */}
            <div>
              <h3 className={`text-lg font-semibold ${getThemeClasses('text-primary')} mb-4 flex items-center`}>
                <BuildingOffice2Icon className="w-5 h-5 mr-2" />
                Parent Organization
              </h3>
              <div
                className={`max-w-2xl mx-auto ${getThemeClasses('bg-muted')} rounded-lg shadow-sm border ${getThemeClasses('border-secondary')} p-4`}
                ref={organizationSelectRef}
              >
                <OrganizationSelect
                  key={`org-select-${selectedType}`}
                  value={selectedOrganization}
                  onChange={handleOrganizationChange}
                  error={errors.organizationId}
                  required={true}
                  label=""
                  onUnauthorized={onUnauthorized}
                  type={DIVISION_TYPE_TO_ORG_TYPE[selectedType]}
                  forceRefresh={true}
                  placeholder={`Select ${
                    selectedType === DIVISION_TYPE_EDUCATIONAL
                      ? "Educational"
                      : selectedType === DIVISION_TYPE_CORPORATE
                        ? "Corporate"
                        : selectedType === DIVISION_TYPE_NONPROFIT
                          ? "Non-Profit"
                          : selectedType === DIVISION_TYPE_GOVERNMENT
                            ? "Government"
                            : ""
                  } Organization`}
                />
              </div>
              {errors.organizationId && (
                <p className={`mt-2 text-sm ${getThemeClasses('text-danger')} text-center`}>
                  {errors.organizationId}
                </p>
              )}
            </div>
          </div>
        )}
      </StaffWizardFormStep>
    </UIXThemeProvider>
  );
}

export default AdminDivisionAddStep2Page;
