// File Path: monorepo/web/frontend/src/pages/Admin/Division/Add/Step6Page.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router";
import {
  useAuthManager,
  useDivisionManager,
  useDivisionWizardStorage,
} from "../../../../services/Services";
import {
  BuildingOffice2Icon,
  MapPinIcon,
  TruckIcon,
  TagIcon,
  QuestionMarkCircleIcon,
  UserGroupIcon,
  ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { TagsDisplay } from "../../../../components/business/displays";
import {
  StaffWizardFormStep,
  Modal,
  Button,
  Alert,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";

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

// SECURITY: Sanitize output for display to prevent XSS
const sanitizeOutput = (value) => {
  if (typeof value !== 'string') return value;
  // For display purposes, we just need to escape HTML entities
  const div = document.createElement('div');
  div.textContent = value;
  return div.innerHTML;
};

// PERFORMANCE: Division type mapping outside component
const DIVISION_TYPE_MAP = {
  1: "Educational",
  2: "Corporate",
  3: "Non-Profit",
  4: "Government",
};

// PERFORMANCE: Phone type mapping outside component
const PHONE_TYPE_MAP = {
  0: "Unknown",
  1: "Mobile",
  2: "Work",
  3: "Home",
};

// PERFORMANCE: Country mapping outside component
const COUNTRY_MAP = {
  CA: "Canada",
  US: "United States",
  MX: "Mexico",
};

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

  // Component states
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [showCancelWarning, setShowCancelWarning] = useState(false);
  const [divisionData, setDivisionData] = useState({});

  // PERFORMANCE: Memoize theme classes
  const themeClasses = useMemo(() => ({
    textPrimary: getThemeClasses('text-primary'),
    textSecondary: getThemeClasses('text-secondary'),
    textMuted: getThemeClasses('text-muted'),
    bgCard: getThemeClasses('bg-card'),
    borderSecondary: getThemeClasses('border-secondary'),
  }), [getThemeClasses]);

  // PERFORMANCE: Memoize helper functions
  const getDivisionTypeLabel = useMemo(() => (type) => {
    return DIVISION_TYPE_MAP[type] || "Unknown";
  }, []);

  const getPhoneTypeLabel = useMemo(() => (phoneType) => {
    return PHONE_TYPE_MAP[phoneType] || "Unknown";
  }, []);

  const getCountryLabel = useMemo(() => (country) => {
    return COUNTRY_MAP[country] || country || "Unknown";
  }, []);

  // Load wizard data
  const loadDivisionState = useCallback(() => {
    try {
      // Collect all step data from wizard storage
      const step1Data = wizardStorage.getStepData("step1Data") || {};
      const step2Data = wizardStorage.getStepData("step2Data") || {};
      const step3Data = wizardStorage.getStepData("step3Data") || {};
      const step4Data = wizardStorage.getStepData("step4Data") || {};
      const step5Data = wizardStorage.getStepData("step5Data") || {};

      // Combine all step data
      const combinedData = {
        ...step1Data,
        ...step2Data,
        ...step3Data,
        ...step4Data,
        ...step5Data,
      };

      if (Object.keys(combinedData).length === 0) {
        // If no data exists, redirect to step 1
        navigate("/admin/divisions/add/step-1-search");
        return;
      }

      setDivisionData(combinedData);
    } catch (error) {
      if (process.env.NODE_ENV === 'development') {
        console.error("Step6Page: Error loading division state:", error);
      }
      navigate("/admin/divisions/add/step-1-search");
    }
  }, [wizardStorage, navigate]);

  // Load existing state from wizard storage
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    loadDivisionState();
  }, [authManager, navigate, loadDivisionState]);

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

  // Handle form submission
  const onSubmitClick = useCallback(
    async () => {
      setErrors({});
      setIsLoading(true);

      try {
        // Transform data for API using the wizard storage method
        const apiData = wizardStorage.transformForAPI();

        // Create the division using the DivisionManager
        const createdDivision = await divisionManager.createDivision(
          apiData,
          onUnauthorized,
        );

        // Clear wizard storage after successful submission
        wizardStorage.clearWizardData();

        // Navigate to the new division detail page
        navigate(`/admin/division/${createdDivision.id}`);
      } catch (error) {
        // Handle error response
        // If error is a validation errors object (from DivisionManager), use it directly
        if (error && typeof error === 'object' && !error.message) {
          setErrors(error);
        } else {
          // Otherwise, treat as a general error
          const errorMessage =
            error.message ||
            "An unexpected error occurred while creating the division.";
          setErrors({ message: errorMessage });
        }

        window.scrollTo({ top: 0, behavior: 'smooth' });
      } finally {
        setIsLoading(false);
      }
    },
    [divisionManager, onUnauthorized, wizardStorage, navigate],
  );

  // Handle cancel
  const handleCancel = useCallback(() => {
    setShowCancelWarning(true);
  }, []);

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

  const handleCancelModal = useCallback(() => {
    setShowCancelWarning(false);
  }, []);

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

  // PERFORMANCE: Memoize actions
  const actions = useMemo(() => [
    {
      label: "Create Division",
      onClick: onSubmitClick,
      variant: "success",
      disabled: isLoading,
      loading: isLoading,
    }
  ], [onSubmitClick, isLoading]);

  // DetailField Component for displaying review data
  const DetailField = useCallback(({ label, value, fullWidth = false }) => (
    <div className={fullWidth ? "lg:col-span-2" : ""}>
      <dt className={`text-xs sm:text-sm font-medium ${themeClasses.textMuted} mb-1`}>
        {label}
      </dt>
      <dd className={`text-sm sm:text-base font-medium ${themeClasses.textPrimary} break-words`}>
        {value || "-"}
      </dd>
    </div>
  ), [themeClasses]);

  // If loading, show loading state
  if (!divisionData || Object.keys(divisionData).length === 0) {
    return (
      <UIXThemeProvider>
        <div className="flex items-center justify-center min-h-screen">
          <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${getThemeClasses('border-primary')}`}></div>
          <span className={`ml-3 ${themeClasses.textSecondary}`}>Loading...</span>
        </div>
      </UIXThemeProvider>
    );
  }

  return (
    <UIXThemeProvider>
      <StaffWizardFormStep
        wizardSteps={WIZARD_STEPS}
        currentStep={6}
        wizardTitle="Add New Division"
        wizardIcon={BuildingOffice2Icon}
        stepTitle="Review and Submit"
        stepSubtitle="Please carefully review the division details before submitting"
        errors={errors}
        isLoading={isLoading}
        showFormCard={false}
        contentMaxWidth="7xl"
        actionLayout="between"
        onBack={handlePrevious}
        onCancel={handleCancel}
        backLabel="Back to Additional Info"
        cancelLabel="Cancel"
        actions={actions}
      >
        {/* Error Alert */}
        {(errors.message || Object.keys(errors).length > 0) && (
          <Alert
            type="error"
            message="Error Creating Division"
            className="mb-6"
          >
            {errors.message && <p className="mb-2">{errors.message}</p>}
            {Object.keys(errors)
              .filter(key => key !== 'message')
              .map(key => (
                <p key={key} className={`text-sm ${getThemeClasses('text-danger')} mb-1`}>
                  <strong>{key}:</strong> {errors[key]}
                </p>
              ))}
          </Alert>
        )}

        {/* Loading State */}
        {isLoading ? (
          <div className="flex items-center justify-center py-8">
            <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${getThemeClasses('border-primary')}`}></div>
            <span className={`ml-3 ${themeClasses.textSecondary}`}>Creating division...</span>
          </div>
        ) : (
          <div className="space-y-6">
            {/* Division Information Section */}
            <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} p-6`}>
              <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} mb-4 flex items-center`}>
                <BuildingOffice2Icon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                Division Information
              </h3>
              <dl className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
                <DetailField
                  label="Division Name"
                  value={sanitizeOutput(divisionData.divisionName)}
                />
                <DetailField
                  label="Short Name"
                  value={sanitizeOutput(divisionData.divisionShortName)}
                />
                <DetailField
                  label="Division Type"
                  value={getDivisionTypeLabel(divisionData.divisionType)}
                />
                <DetailField
                  label="Parent Organization"
                  value={sanitizeOutput(divisionData.organizationName)}
                />
              </dl>
            </div>

            {/* Contact Information Section */}
            <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} p-6`}>
              <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} mb-4 flex items-center`}>
                <UserGroupIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                Contact Information
              </h3>
              {divisionData.contacts &&
                divisionData.contacts.map((contact, index) => (
                  <div
                    key={index}
                    className={
                      index > 0 ? `mt-6 pt-6 border-t ${themeClasses.borderSecondary}` : ""
                    }
                  >
                    {divisionData.contacts.length > 1 && (
                      <p className={`text-sm font-semibold ${themeClasses.textSecondary} mb-4`}>
                        Contact Person #{index + 1}
                      </p>
                    )}
                    <dl className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
                      <DetailField
                        label="Name"
                        value={sanitizeOutput(`${contact.firstName || ""} ${contact.lastName || ""}`)}
                      />
                      <DetailField label="Title" value={sanitizeOutput(contact.title)} />
                      <DetailField
                        label="Email"
                        value={sanitizeOutput(contact.email) || "Not provided"}
                      />
                      <DetailField
                        label="OK to Email"
                        value={contact.isOkToEmail ? "Yes" : "No"}
                      />
                      <DetailField
                        label="Phone"
                        value={
                          contact.phone
                            ? `${sanitizeOutput(contact.phone)} (${getPhoneTypeLabel(contact.phoneType)})`
                            : "-"
                        }
                      />
                      {contact.phoneType === 2 &&
                        contact.phoneExtension && (
                          <DetailField
                            label="Extension"
                            value={sanitizeOutput(contact.phoneExtension)}
                          />
                        )}
                      {contact.otherPhone && (
                        <>
                          <DetailField
                            label="Other Phone"
                            value={`${sanitizeOutput(contact.otherPhone)} (${getPhoneTypeLabel(contact.otherPhoneType)})`}
                          />
                          {contact.otherPhoneType === 2 &&
                            contact.otherPhoneExtension && (
                              <DetailField
                                label="Other Extension"
                                value={sanitizeOutput(contact.otherPhoneExtension)}
                              />
                            )}
                        </>
                      )}
                    </dl>
                  </div>
                ))}
            </div>

            {/* Mailing Address Section */}
            <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} p-6`}>
              <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} mb-4 flex items-center`}>
                <MapPinIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                Mailing Address
              </h3>
              <dl className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
                <DetailField
                  label="Address"
                  value={sanitizeOutput(divisionData.addressLine1)}
                />
                {divisionData.addressLine2 && (
                  <DetailField
                    label="Address Line 2"
                    value={sanitizeOutput(divisionData.addressLine2)}
                  />
                )}
                <DetailField label="City" value={sanitizeOutput(divisionData.city)} />
                <DetailField
                  label="Province/Territory/State"
                  value={sanitizeOutput(divisionData.region)}
                />
                <DetailField
                  label="Postal/ZIP Code"
                  value={sanitizeOutput(divisionData.postalCode)}
                />
                <DetailField
                  label="Country"
                  value={getCountryLabel(divisionData.country)}
                />
              </dl>
            </div>

            {/* Billing Address Section (if different) */}
            {divisionData.hasShippingAddress && (
              <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} p-6`}>
                <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} mb-4 flex items-center`}>
                  <TruckIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                  Billing Address
                </h3>
                <dl className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
                  <DetailField
                    label="Name"
                    value={sanitizeOutput(divisionData.shippingName)}
                  />
                  <DetailField
                    label="Phone"
                    value={sanitizeOutput(divisionData.shippingPhone)}
                  />
                  <DetailField
                    label="Address"
                    value={sanitizeOutput(divisionData.shippingAddressLine1)}
                  />
                  {divisionData.shippingAddressLine2 && (
                    <DetailField
                      label="Address Line 2"
                      value={sanitizeOutput(divisionData.shippingAddressLine2)}
                    />
                  )}
                  <DetailField
                    label="City"
                    value={sanitizeOutput(divisionData.shippingCity)}
                  />
                  <DetailField
                    label="Province/Territory/State"
                    value={sanitizeOutput(divisionData.shippingRegion)}
                  />
                  <DetailField
                    label="Postal/ZIP Code"
                    value={sanitizeOutput(divisionData.shippingPostalCode)}
                  />
                  <DetailField
                    label="Country"
                    value={getCountryLabel(divisionData.shippingCountry)}
                  />
                </dl>
              </div>
            )}

            {/* Additional Information Section */}
            <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} p-6`}>
              <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} mb-4 flex items-center`}>
                <QuestionMarkCircleIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                Additional Information
              </h3>

              {/* Tags Display */}
              {divisionData.tags && divisionData.tags.length > 0 && (
                <div className="mb-6">
                  <TagsDisplay
                    values={divisionData.tags}
                    label="Tags"
                    onUnauthorized={onUnauthorized}
                    variant="primary"
                  />
                </div>
              )}

              <dl className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
                <DetailField
                  label="Join Date"
                  value={divisionData.joinDate}
                />
              </dl>

              {divisionData.additionalComment && (
                <div className={`mt-6 pt-6 border-t ${themeClasses.borderSecondary}`}>
                  <DetailField
                    label="Additional Comments"
                    value={sanitizeOutput(divisionData.additionalComment)}
                    fullWidth
                  />
                </div>
              )}
            </div>

            {/* Final Instructions */}
            <Alert
              type="info"
              message="Ready to Submit"
              className="mb-6"
            >
              Review all the information above. If everything looks correct, click the "Create Division" button to complete the process.
            </Alert>
          </div>
        )}
      </StaffWizardFormStep>

      {/* Cancel Confirmation Modal */}
      <Modal
        isOpen={showCancelWarning}
        onClose={handleCancelModal}
        title="Cancel Division Creation?"
        icon={ExclamationTriangleIcon}
        iconColor="warning"
      >
        <p className={`text-sm sm:text-base ${themeClasses.textSecondary}`}>
          Your division record will be cancelled and your work will be lost. This cannot be undone. Do you want to continue?
        </p>
        <div className="mt-6 flex flex-col-reverse sm:flex-row sm:justify-end gap-3">
          <Button
            onClick={handleCancelModal}
            variant="secondary"
          >
            No, Keep Working
          </Button>
          <Button
            onClick={handleConfirmCancel}
            variant="danger"
          >
            Yes, Cancel
          </Button>
        </div>
      </Modal>
    </UIXThemeProvider>
  );
}

export default AdminDivisionAddStep6Page;
