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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router";
import {
  UIXThemeProvider,
  useUIXTheme,
  StaffWizardFormStep,
  FormSection,
  FormRow,
  Input,
  Select,
  Checkbox,
  Alert,
  Modal,
  Button,
} from "../../../../components/UIX";
import {
  BuildingOfficeIcon,
  UserIcon,
  UserGroupIcon,
  EnvelopeIcon,
  PhoneIcon,
  XMarkIcon,
  PlusIcon,
  ArrowRightIcon,
  CheckIcon,
} from "@heroicons/react/24/outline";

// Phone type options - Static to prevent recreation
const PHONE_TYPE_OPTIONS = [
  { value: "0", label: "Please select" },
  { value: "1", label: "Mobile" },
  { value: "2", label: "Work" },
  { value: "3", label: "Home" },
];

// Wizard steps configuration - Static to prevent recreation
const WIZARD_STEPS = [
  { id: 1, title: "Search", subtitle: "Find Org", isActive: false, isCompleted: true },
  { id: 2, title: "Type", subtitle: "Select", isActive: false, isCompleted: true },
  { id: 3, title: "Contact", subtitle: "Information", isActive: true, isCompleted: false },
  { id: 4, title: "Address", subtitle: "Location", isActive: false, isCompleted: false },
  { id: 5, title: "Additional", subtitle: "Extra Info", isActive: false, isCompleted: false },
  { id: 6, title: "Review", subtitle: "Confirm", isActive: false, isCompleted: false },
];

// SECURITY: Initial contact template - moved outside component to prevent recreation
const INITIAL_CONTACT_TEMPLATE = {
  firstName: "",
  lastName: "",
  title: "",
  email: "",
  isOkToEmail: true,
  phone: "",
  phoneType: 0,
  phoneExtension: "",
  otherPhone: "",
  otherPhoneType: 0,
  otherPhoneExtension: "",
};

// SECURITY: Input sanitization helper
const sanitizeInput = (input) => {
  if (typeof input !== 'string') return input;
  // Trim whitespace and remove potential XSS characters
  return input.trim().replace(/[<>]/g, '');
};

// SECURITY: Email validation helper
const isValidEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// SECURITY: Phone validation helper
const isValidPhone = (phone) => {
  // Basic phone validation - digits, spaces, hyphens, parentheses
  const phoneRegex = /^[\d\s\-\(\)\+]+$/;
  return phoneRegex.test(phone) && phone.replace(/\D/g, '').length >= 10;
};

function AdminOrganizationAddStep3Page() {
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();
  const [showCancelWarning, setShowCancelWarning] = useState(false);
  const [errors, setErrors] = useState({});
  const [isInitialized, setIsInitialized] = useState(false);

  // PERFORMANCE FIX: Initialize state with static template
  const [organizationName, setOrganizationName] = useState("");
  const [organizationShortName, setOrganizationShortName] = useState("");
  const [organizationType, setOrganizationType] = useState("");
  const [contacts, setContacts] = useState([{ ...INITIAL_CONTACT_TEMPLATE }]);

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

  // SECURITY: Load existing data on component mount with validation
  useEffect(() => {
    const initializeData = async () => {
      try {
        // Check if we have data from Step 1
        const step1Data = sessionStorage.getItem("step1Data");

        if (!step1Data) {
          navigate("/admin/organizations/add/step-1");
          return;
        }

        // SECURITY: Validate step1Data structure
        let parsedStep1Data;
        try {
          parsedStep1Data = JSON.parse(step1Data);
          if (typeof parsedStep1Data !== "object" || parsedStep1Data === null) {
            throw new Error("Invalid step1Data structure");
          }
        } catch (error) {
          // SECURITY: Don't expose error details in production
          if (import.meta.env.DEV) {
            console.error("Step 3: Error parsing Step 1 data:", error);
          }
          navigate("/admin/organizations/add/step-1");
          return;
        }

        // Check if we have data from Step 2
        const step2Data = sessionStorage.getItem("step2Data");

        if (!step2Data) {
          navigate("/admin/organizations/add/step-2");
          return;
        }

        // SECURITY: Parse and validate Step 2 data
        let step2ParsedData;
        try {
          step2ParsedData = JSON.parse(step2Data);
          const orgType = step2ParsedData.organizationType;

          if (!orgType || typeof orgType !== 'string') {
            throw new Error("Invalid organization type");
          }

          // SECURITY: Validate organization type against whitelist
          const validTypes = ['educational', 'corporate', 'non-profit', 'government'];
          if (!validTypes.includes(orgType)) {
            throw new Error("Invalid organization type value");
          }

          setOrganizationType(orgType);
        } catch (error) {
          if (import.meta.env.DEV) {
            console.error("Step 3: Error parsing Step 2 data:", error);
          }
          navigate("/admin/organizations/add/step-2");
          return;
        }

        // Load any existing Step 3 data
        const step3Data = sessionStorage.getItem("step3Data");
        const combinedData = sessionStorage.getItem("WORKERY_ORGANIZATION_CREATION_STATE");

        let dataToLoad = null;

        if (step3Data) {
          try {
            dataToLoad = JSON.parse(step3Data);
          } catch (error) {
            if (import.meta.env.DEV) {
              console.error("Step 3: Error parsing existing Step 3 data:", error);
            }
          }
        }

        // If no step3Data but there's combined data, extract relevant fields
        if (!dataToLoad && combinedData) {
          try {
            const combined = JSON.parse(combinedData);
            if (combined.organizationName || combined.contacts) {
              dataToLoad = combined;
            }
          } catch (error) {
            if (import.meta.env.DEV) {
              console.error("Step 3: Error parsing combined data:", error);
            }
          }
        }

        // SECURITY: Apply loaded data with sanitization
        if (dataToLoad) {
          if (dataToLoad.organizationName) {
            setOrganizationName(sanitizeInput(dataToLoad.organizationName));
          }
          if (dataToLoad.organizationShortName) {
            setOrganizationShortName(sanitizeInput(dataToLoad.organizationShortName));
          }

          // SECURITY: Validate contacts array structure
          if (
            dataToLoad.contacts &&
            Array.isArray(dataToLoad.contacts) &&
            dataToLoad.contacts.length > 0 &&
            dataToLoad.contacts.length <= 10 // Prevent DoS through large arrays
          ) {
            // Sanitize each contact field
            const sanitizedContacts = dataToLoad.contacts.map(contact => ({
              firstName: sanitizeInput(contact.firstName || ""),
              lastName: sanitizeInput(contact.lastName || ""),
              title: sanitizeInput(contact.title || ""),
              email: sanitizeInput(contact.email || ""),
              isOkToEmail: Boolean(contact.isOkToEmail),
              phone: sanitizeInput(contact.phone || ""),
              phoneType: Number(contact.phoneType) || 0,
              phoneExtension: sanitizeInput(contact.phoneExtension || ""),
              otherPhone: sanitizeInput(contact.otherPhone || ""),
              otherPhoneType: Number(contact.otherPhoneType) || 0,
              otherPhoneExtension: sanitizeInput(contact.otherPhoneExtension || ""),
            }));
            setContacts(sanitizedContacts);
          }
        }

        setIsInitialized(true);
      } catch (error) {
        // SECURITY: Generic error handling without exposing details
        if (import.meta.env.DEV) {
          console.error("Step 3: Initialization error:", error);
        }
        navigate("/admin/organizations/add/step-1");
      }
    };

    initializeData();
  }, [navigate]);

  // PERFORMANCE FIX: Use functional state updates to avoid dependency on contacts
  const addContact = useCallback(() => {
    setContacts(prevContacts => {
      if (prevContacts.length < 10) {
        return [...prevContacts, { ...INITIAL_CONTACT_TEMPLATE }];
      }
      return prevContacts;
    });
  }, []);

  // PERFORMANCE FIX: Use functional state updates
  const removeContact = useCallback((index) => {
    setContacts(prevContacts => {
      if (prevContacts.length > 1) {
        return prevContacts.filter((_, i) => i !== index);
      }
      return prevContacts;
    });
  }, []);

  // PERFORMANCE: Update contact field with sanitization
  const updateContact = useCallback((index, field, value) => {
    setContacts(prevContacts => {
      const newContacts = [...prevContacts];
      // SECURITY: Sanitize string inputs
      if (typeof value === 'string') {
        newContacts[index][field] = sanitizeInput(value);
      } else {
        newContacts[index][field] = value;
      }
      return newContacts;
    });
  }, []);

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

  const handleConfirmCancel = useCallback(() => {
    setShowCancelWarning(false);
    // SECURITY: Clear all session data when cancelling
    try {
      sessionStorage.removeItem("step1Data");
      sessionStorage.removeItem("step2Data");
      sessionStorage.removeItem("step3Data");
      sessionStorage.removeItem("step4Data");
      sessionStorage.removeItem("step5Data");
      sessionStorage.removeItem("step6Data");
      sessionStorage.removeItem("WORKERY_ORGANIZATION_CREATION_STATE");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error clearing session storage:", error);
      }
    }
    navigate("/admin/organizations");
  }, [navigate]);

  // Handle Back button
  const handleBack = useCallback(() => {
    // Save current state before going back
    const step3Data = {
      organizationName: sanitizeInput(organizationName),
      organizationShortName: sanitizeInput(organizationShortName),
      organizationType,
      contacts,
      timestamp: new Date().toISOString(),
    };

    try {
      sessionStorage.setItem("step3Data", JSON.stringify(step3Data));
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error saving step3Data:", error);
      }
    }

    navigate("/admin/organizations/add/step-2");
  }, [organizationName, organizationShortName, organizationType, contacts, navigate]);

  // SECURITY: Enhanced form validation with proper email and phone validation
  const validateForm = useCallback(() => {
    const newErrors = {};

    // Check organization fields
    const trimmedOrgName = organizationName.trim();
    const trimmedShortName = organizationShortName.trim();

    if (!trimmedOrgName) {
      newErrors.organizationName = "Organization name is required";
    } else if (trimmedOrgName.length > 255) {
      newErrors.organizationName = "Organization name is too long (max 255 characters)";
    }

    if (!trimmedShortName) {
      newErrors.organizationShortName = "Organization short name is required";
    } else if (trimmedShortName.length > 100) {
      newErrors.organizationShortName = "Short name is too long (max 100 characters)";
    }

    // SECURITY: Validate each contact with proper validation
    contacts.forEach((contact, index) => {
      const trimmedFirstName = contact.firstName.trim();
      const trimmedLastName = contact.lastName.trim();
      const trimmedTitle = contact.title.trim();
      const trimmedEmail = contact.email.trim();
      const trimmedPhone = contact.phone.trim();

      if (!trimmedFirstName) {
        newErrors[`contact_${index}_firstName`] = "First name is required";
      } else if (trimmedFirstName.length > 100) {
        newErrors[`contact_${index}_firstName`] = "First name is too long";
      }

      if (!trimmedLastName) {
        newErrors[`contact_${index}_lastName`] = "Last name is required";
      } else if (trimmedLastName.length > 100) {
        newErrors[`contact_${index}_lastName`] = "Last name is too long";
      }

      if (!trimmedTitle) {
        newErrors[`contact_${index}_title`] = "Title is required";
      } else if (trimmedTitle.length > 100) {
        newErrors[`contact_${index}_title`] = "Title is too long";
      }

      if (!trimmedEmail) {
        newErrors[`contact_${index}_email`] = "Email is required";
      } else if (!isValidEmail(trimmedEmail)) {
        newErrors[`contact_${index}_email`] = "Please enter a valid email address";
      } else if (trimmedEmail.length > 255) {
        newErrors[`contact_${index}_email`] = "Email is too long";
      }

      if (!trimmedPhone) {
        newErrors[`contact_${index}_phone`] = "Phone number is required";
      } else if (!isValidPhone(trimmedPhone)) {
        newErrors[`contact_${index}_phone`] = "Please enter a valid phone number (at least 10 digits)";
      }

      if (contact.phoneType === 0) {
        newErrors[`contact_${index}_phoneType`] = "Phone type is required";
      }
    });

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [organizationName, organizationShortName, contacts]);

  // Handle Next button with rate limiting
  const handleNext = useCallback((e) => {
    e.preventDefault();

    // Validate form
    if (!validateForm()) {
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }

    // SECURITY: Create Step 3 data with sanitized inputs
    const step3Data = {
      organizationName: sanitizeInput(organizationName),
      organizationShortName: sanitizeInput(organizationShortName),
      organizationType,
      contacts: contacts.map(contact => ({
        firstName: sanitizeInput(contact.firstName),
        lastName: sanitizeInput(contact.lastName),
        title: sanitizeInput(contact.title),
        email: sanitizeInput(contact.email),
        isOkToEmail: Boolean(contact.isOkToEmail),
        phone: sanitizeInput(contact.phone),
        phoneType: Number(contact.phoneType),
        phoneExtension: sanitizeInput(contact.phoneExtension),
        otherPhone: sanitizeInput(contact.otherPhone),
        otherPhoneType: Number(contact.otherPhoneType),
        otherPhoneExtension: sanitizeInput(contact.otherPhoneExtension),
      })),
      timestamp: new Date().toISOString(),
    };

    try {
      sessionStorage.setItem("step3Data", JSON.stringify(step3Data));
      navigate("/admin/organizations/add/step-4");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Step 3: Error saving data:", error);
      }
      setErrors({ message: "Failed to save data. Please try again." });
    }
  }, [validateForm, organizationName, organizationShortName, organizationType, contacts, navigate]);

  // PERFORMANCE: Memoize action buttons configuration
  const actions = useMemo(() => [
    {
      label: "Continue to Address",
      variant: "primary",
      icon: ArrowRightIcon,
      onClick: handleNext,
      disabled: false,
    }
  ], [handleNext]);

  // Show loading state while initializing
  if (!isInitialized) {
    return (
      <div className={`min-h-screen ${getThemeClasses('bg-gradient-primary')} flex items-center justify-center`}>
        <div className="text-center">
          <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${themeClasses.borderPrimary} mx-auto`}></div>
          <p className={`mt-4 ${themeClasses.textSecondary}`}>Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className={`min-h-screen ${getThemeClasses('bg-gradient-primary')} px-4 sm:px-6 lg:px-8`}>
      <div className="max-w-7xl mx-auto py-6 sm:py-8">
        <StaffWizardFormStep
          wizardSteps={WIZARD_STEPS}
          currentStep={3}
          wizardTitle="Add New Organization"
          wizardIcon={BuildingOfficeIcon}
          stepTitle="Contact Information"
          stepSubtitle="Enter organization and contact details"
          stepIcon={UserGroupIcon}
          errors={errors}
          showFormCard={false}
          contentMaxWidth="7xl"
          actions={actions}
          onCancel={handleCancel}
          onBack={handleBack}
          actionLayout="end"
        >
          {/* Error Alert */}
          {Object.keys(errors).length > 0 && (
            <Alert
              type="error"
              message={errors.message || "Please correct the errors below before proceeding"}
              className="mb-6"
              dismissible
              onDismiss={() => setErrors({})}
            />
          )}

          {/* Organization Information Section */}
          <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${getThemeClasses('border-secondary')} p-6 mb-6`}>
            <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} mb-4 flex items-center`}>
              <BuildingOfficeIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
              Organization Details
            </h3>
            <FormSection>
              <FormRow>
                <Input
                  label="Organization Name"
                  value={organizationName}
                  onChange={setOrganizationName}
                  placeholder="Enter organization name"
                  error={errors.organizationName}
                  required={true}
                  icon={BuildingOfficeIcon}
                  maxLength={255}
                />
              </FormRow>

              <FormRow>
                <Input
                  label="Organization Short Name"
                  value={organizationShortName}
                  onChange={setOrganizationShortName}
                  placeholder="Enter organization short name"
                  error={errors.organizationShortName}
                  required={true}
                  icon={BuildingOfficeIcon}
                  maxLength={100}
                />
              </FormRow>

              <FormRow>
                <div>
                  <label className={`block text-base sm:text-lg font-semibold ${themeClasses.textPrimary} mb-3`}>
                    Organization Type (Selected in Step 2)
                  </label>
                  <div className={`${getThemeClasses('bg-disabled')} p-4 rounded-lg border ${getThemeClasses('border-secondary')}`}>
                    <div className="flex items-center">
                      <BuildingOfficeIcon className={`h-5 w-5 ${themeClasses.textMuted} mr-2`} />
                      <span className={`text-base font-medium ${themeClasses.textPrimary}`}>
                        {organizationType
                          ? organizationType.charAt(0).toUpperCase() +
                            organizationType.slice(1).replace("-", " ")
                          : "Not selected"}
                      </span>
                    </div>
                  </div>
                </div>
              </FormRow>
            </FormSection>
          </div>

          {/* Contact Persons Section */}
          {contacts.map((contact, index) => (
            <div
              key={index}
              className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${getThemeClasses('border-secondary')} p-6 mb-6`}
            >
              <div className="flex items-center justify-between mb-4">
                <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} flex items-center`}>
                  <UserIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                  Contact Person{contacts.length > 1 ? ` #${index + 1}` : ""}
                </h3>
                {/* Remove button for additional contacts */}
                {index > 0 && (
                  <Button
                    variant="danger"
                    size="sm"
                    onClick={() => removeContact(index)}
                    icon={XMarkIcon}
                  >
                    Remove
                  </Button>
                )}
              </div>

              <FormSection>
                <FormRow cols={2}>
                  <Input
                    label="First Name"
                    value={contact.firstName}
                    onChange={(value) => updateContact(index, "firstName", value)}
                    placeholder="Enter first name"
                    error={errors[`contact_${index}_firstName`]}
                    required={true}
                    icon={UserIcon}
                    maxLength={100}
                  />
                  <Input
                    label="Last Name"
                    value={contact.lastName}
                    onChange={(value) => updateContact(index, "lastName", value)}
                    placeholder="Enter last name"
                    error={errors[`contact_${index}_lastName`]}
                    required={true}
                    icon={UserIcon}
                    maxLength={100}
                  />
                </FormRow>

                <FormRow>
                  <Input
                    label="Title"
                    value={contact.title}
                    onChange={(value) => updateContact(index, "title", value)}
                    placeholder="Enter title"
                    error={errors[`contact_${index}_title`]}
                    required={true}
                    icon={UserIcon}
                    maxLength={100}
                  />
                </FormRow>

                <FormRow>
                  <Input
                    label="Email Address"
                    type="email"
                    value={contact.email}
                    onChange={(value) => updateContact(index, "email", value)}
                    placeholder="Enter email address"
                    error={errors[`contact_${index}_email`]}
                    required={true}
                    icon={EnvelopeIcon}
                    maxLength={255}
                  />
                </FormRow>

                <FormRow>
                  <Checkbox
                    label="I agree to receive electronic email"
                    checked={contact.isOkToEmail}
                    onChange={(checked) => updateContact(index, "isOkToEmail", checked)}
                  />
                </FormRow>

                <FormRow cols={2}>
                  <Input
                    label="Phone Number"
                    type="tel"
                    value={contact.phone}
                    onChange={(value) => updateContact(index, "phone", value)}
                    placeholder="Enter phone number"
                    error={errors[`contact_${index}_phone`]}
                    required={true}
                    icon={PhoneIcon}
                    maxLength={20}
                  />
                  <Select
                    label="Phone Type"
                    value={String(contact.phoneType)}
                    onChange={(value) => updateContact(index, "phoneType", parseInt(value))}
                    options={PHONE_TYPE_OPTIONS}
                    error={errors[`contact_${index}_phoneType`]}
                    required={true}
                  />
                </FormRow>

                {/* Extension field for Work phone */}
                {contact.phoneType === 2 && (
                  <FormRow>
                    <Input
                      label="Extension"
                      value={contact.phoneExtension}
                      onChange={(value) => updateContact(index, "phoneExtension", value)}
                      placeholder="Extension"
                      maxLength={10}
                    />
                  </FormRow>
                )}

                {/* Alternative Phone Section */}
                <div className="mt-6">
                  <h5 className={`text-sm font-semibold ${themeClasses.textSecondary} mb-4`}>
                    Alternative Phone (Optional)
                  </h5>
                  <FormRow cols={2}>
                    <Input
                      label="Other Phone Number"
                      type="tel"
                      value={contact.otherPhone}
                      onChange={(value) => updateContact(index, "otherPhone", value)}
                      placeholder="Enter alternative phone"
                      icon={PhoneIcon}
                      maxLength={20}
                    />
                    <Select
                      label="Other Phone Type"
                      value={String(contact.otherPhoneType)}
                      onChange={(value) => updateContact(index, "otherPhoneType", parseInt(value))}
                      options={PHONE_TYPE_OPTIONS}
                    />
                  </FormRow>

                  {/* Extension field for Other Work phone */}
                  {contact.otherPhoneType === 2 && (
                    <FormRow>
                      <Input
                        label="Extension"
                        value={contact.otherPhoneExtension}
                        onChange={(value) => updateContact(index, "otherPhoneExtension", value)}
                        placeholder="Extension"
                        maxLength={10}
                      />
                    </FormRow>
                  )}
                </div>
              </FormSection>
            </div>
          ))}

          {/* Add Additional Contact Button */}
          {contacts.length < 10 && (
            <div className="mb-6">
              <Button
                variant="outline"
                onClick={addContact}
                icon={PlusIcon}
              >
                Add Additional Contact
              </Button>
              <p className={`mt-2 text-sm ${themeClasses.textMuted}`}>
                You can add up to {10 - contacts.length} more contact
                {10 - contacts.length !== 1 ? "s" : ""}
              </p>
            </div>
          )}
        </StaffWizardFormStep>

        {/* Cancel Confirmation Modal */}
        <Modal
          isOpen={showCancelWarning}
          onClose={() => setShowCancelWarning(false)}
          title="Are you sure?"
          footer={
            <div className="flex justify-end space-x-3">
              <Button
                variant="secondary"
                onClick={() => setShowCancelWarning(false)}
              >
                No, Keep Working
              </Button>
              <Button
                variant="danger"
                onClick={handleConfirmCancel}
              >
                Yes, Cancel
              </Button>
            </div>
          }
        >
          <p className={themeClasses.textSecondary}>
            Your Organization record will be cancelled and your work will be
            lost. This cannot be undone. Do you want to continue?
          </p>
        </Modal>
      </div>
    </div>
  );
}

function AdminOrganizationAddStep3PageWrapper() {
  return (
    <UIXThemeProvider>
      <AdminOrganizationAddStep3Page />
    </UIXThemeProvider>
  );
}

export default AdminOrganizationAddStep3PageWrapper;
