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

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router";
import {
  useAuthManager,
  useDivisionWizardStorage,
} from "../../../../services/Services";
import {
  BuildingOffice2Icon,
  UserIcon,
  ExclamationCircleIcon,
  EnvelopeIcon,
  PhoneIcon,
  PlusIcon,
} from "@heroicons/react/24/outline";
import {
  StaffWizardFormStep,
  Input,
  Select,
  Checkbox,
  UIXThemeProvider,
  useUIXTheme,
  Button,
} from "../../../../components/UIX";

// Phone type options
const PHONE_TYPE_OPTIONS = [
  { value: 1, label: "Mobile" },
  { value: 2, label: "Work" },
  { value: 3, label: "Home" },
];

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

// SECURITY: Sanitize contact object fields
const sanitizeContact = (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: contact.phoneType,
  phoneExtension: sanitizeInput(contact.phoneExtension || ''),
  otherPhone: sanitizeInput(contact.otherPhone || ''),
  otherPhoneType: contact.otherPhoneType || 0,
  otherPhoneExtension: sanitizeInput(contact.otherPhoneExtension || ''),
});

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

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

  // Component states
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [divisionName, setDivisionName] = useState("");
  const [divisionShortName, setDivisionShortName] = useState("");
  const [contacts, setContacts] = useState([
    {
      firstName: "",
      lastName: "",
      title: "",
      email: "",
      isOkToEmail: true,
      phone: "",
      phoneType: 0,
      phoneExtension: "",
      otherPhone: "",
      otherPhoneType: 0,
      otherPhoneExtension: "",
    },
  ]);

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

    const step3Data = wizardStorage.getStepData("step3Data");
    if (step3Data) {
      if (step3Data.divisionName) setDivisionName(step3Data.divisionName);
      if (step3Data.divisionShortName)
        setDivisionShortName(step3Data.divisionShortName);
      if (step3Data.contacts) setContacts(step3Data.contacts);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Handle contact field changes
  const handleContactChange = useCallback((contactIndex, field, value) => {
    setContacts((prev) =>
      prev.map((contact, index) =>
        index === contactIndex ? { ...contact, [field]: value } : contact,
      ),
    );
  }, []);

  // Add new contact
  const addContact = useCallback(() => {
    if (contacts.length < 10) {
      setContacts((prev) => [
        ...prev,
        {
          firstName: "",
          lastName: "",
          title: "",
          email: "",
          isOkToEmail: true,
          phone: "",
          phoneType: 0,
          phoneExtension: "",
          otherPhone: "",
          otherPhoneType: 0,
          otherPhoneExtension: "",
        },
      ]);
    }
  }, [contacts.length]);

  // Remove contact
  const removeContact = useCallback(
    (contactIndex) => {
      if (contacts.length > 1) {
        setContacts((prev) =>
          prev.filter((_, index) => index !== contactIndex),
        );
      }
    },
    [contacts.length],
  );

  // Validation function - matching Organization validation
  const validateForm = useCallback(() => {
    const newErrors = {};

    // Division name validation
    if (!divisionName.trim()) {
      newErrors.divisionName = "Division name is required";
    }

    // Division short name validation - required like Organization
    if (!divisionShortName.trim()) {
      newErrors.divisionShortName = "Division short name is required";
    }

    // Contact validation - matching Organization patterns
    contacts.forEach((contact, index) => {
      if (!contact.firstName.trim()) {
        newErrors[`contact_${index}_firstName`] = "First name is required";
      }
      if (!contact.lastName.trim()) {
        newErrors[`contact_${index}_lastName`] = "Last name is required";
      }
      if (!contact.title.trim()) {
        newErrors[`contact_${index}_title`] = "Title is required";
      }
      if (!contact.email.trim()) {
        newErrors[`contact_${index}_email`] = "Email is required";
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(contact.email)) {
        newErrors[`contact_${index}_email`] = "Please enter a valid email address";
      }
      if (!contact.phone.trim()) {
        newErrors[`contact_${index}_phone`] = "Phone number is required";
      }
      if (contact.phoneType === 0) {
        newErrors[`contact_${index}_phoneType`] = "Phone type is required";
      }
    });

    return newErrors;
  }, [divisionName, divisionShortName, contacts]);

  // Handle form submission
  const handleSubmit = useCallback(() => {
    const validationErrors = validateForm();
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }

    setIsLoading(true);
    setErrors({});

    try {
      // SECURITY: Save division and contact data with sanitization
      const contactData = {
        divisionName: sanitizeInput(divisionName),
        divisionShortName: sanitizeInput(divisionShortName),
        contacts: contacts.map(sanitizeContact),
        timestamp: new Date().toISOString(),
      };

      wizardStorage.saveStepData("step3Data", contactData);

      // Navigate to next step
      navigate("/admin/divisions/add/step-4");
    } catch (error) {
      setErrors({
        submit: error.message || "Failed to save contact information",
      });
    } finally {
      setIsLoading(false);
    }
  }, [
    divisionName,
    divisionShortName,
    contacts,
    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-2");
  }, [navigate]);

  return (
    <UIXThemeProvider>
      <StaffWizardFormStep
        wizardSteps={WIZARD_STEPS}
        currentStep={3}
        wizardTitle="Add New Division"
        wizardIcon={BuildingOffice2Icon}
        stepTitle="Division & Contact Information"
        errors={errors}
        isLoading={isLoading}
        showFormCard={true}
        actionLayout="between"
        contentMaxWidth="6xl"
        onBack={handlePrevious}
        onCancel={handleCancel}
        backLabel="Back to Type"
        cancelLabel="Cancel"
        actions={[
          {
            label: "Continue to Address",
            onClick: handleSubmit,
            variant: "primary",
            disabled: isLoading,
            loading: isLoading,
          },
        ]}
      >
        <div className="space-y-8">
          {/* Division Name Section */}
          <div className={`${getThemeClasses('bg-card')} rounded-lg shadow-sm border ${getThemeClasses('border-secondary')} p-6`}>
            <h3 className={`text-lg font-semibold ${getThemeClasses('text-primary')} mb-4 flex items-center`}>
              <BuildingOffice2Icon className="w-5 h-5 mr-2" />
              Division Information
            </h3>
            <div className="space-y-4">
              <Input
                label="Division Name"
                value={divisionName}
                onChange={(value) => setDivisionName(value)}
                error={errors.divisionName}
                required={true}
                placeholder="Enter division name"
              />
              <Input
                label="Division Short Name"
                value={divisionShortName}
                onChange={(value) => setDivisionShortName(value)}
                error={errors.divisionShortName}
                required={true}
                placeholder="Enter division short name"
              />
            </div>
          </div>

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

              {/* Personal Information */}
              <div className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <Input
                    label="First Name"
                    value={contact.firstName}
                    onChange={(value) =>
                      handleContactChange(contactIndex, "firstName", value)
                    }
                    error={errors[`contact_${contactIndex}_firstName`]}
                    required={true}
                    placeholder="Enter first name"
                  />
                  <Input
                    label="Last Name"
                    value={contact.lastName}
                    onChange={(value) =>
                      handleContactChange(contactIndex, "lastName", value)
                    }
                    error={errors[`contact_${contactIndex}_lastName`]}
                    required={true}
                    placeholder="Enter last name"
                  />
                </div>

                <Input
                  label="Title"
                  value={contact.title}
                  onChange={(value) =>
                    handleContactChange(contactIndex, "title", value)
                  }
                  error={errors[`contact_${contactIndex}_title`]}
                  required={true}
                  placeholder="Enter title"
                />

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

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

                {/* Primary Phone */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <Input
                    label="Phone Number"
                    type="tel"
                    value={contact.phone}
                    onChange={(value) =>
                      handleContactChange(contactIndex, "phone", value)
                    }
                    error={errors[`contact_${contactIndex}_phone`]}
                    required={true}
                    placeholder="Enter phone number"
                    icon={PhoneIcon}
                  />
                  <Select
                    label="Phone Type"
                    value={contact.phoneType}
                    onChange={(value) =>
                      handleContactChange(contactIndex, "phoneType", parseInt(value))
                    }
                    error={errors[`contact_${contactIndex}_phoneType`]}
                    required={true}
                    options={PHONE_TYPE_OPTIONS}
                  />
                </div>

                {/* Phone Extension - only show when Work phone selected */}
                {contact.phoneType === 2 && (
                  <Input
                    label="Phone Extension"
                    value={contact.phoneExtension}
                    onChange={(value) =>
                      handleContactChange(contactIndex, "phoneExtension", value)
                    }
                    placeholder="Extension"
                  />
                )}

                {/* Secondary Phone */}
                <div>
                  <h4 className={`text-sm font-medium mb-3 ${getThemeClasses('text-secondary')}`}>
                    Alternative Phone (Optional)
                  </h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <Input
                      label="Other Phone Number"
                      type="tel"
                      value={contact.otherPhone}
                      onChange={(value) =>
                        handleContactChange(contactIndex, "otherPhone", value)
                      }
                      placeholder="Enter alternative phone"
                    />
                    <Select
                      label="Other Phone Type"
                      value={contact.otherPhoneType}
                      onChange={(value) =>
                        handleContactChange(
                          contactIndex,
                          "otherPhoneType",
                          parseInt(value),
                        )
                      }
                      options={PHONE_TYPE_OPTIONS}
                    />
                  </div>

                  {/* Other Phone Extension - only show when Other Work phone selected */}
                  {contact.otherPhoneType === 2 && (
                    <div className="mt-4">
                      <Input
                        label="Other Phone Extension"
                        value={contact.otherPhoneExtension}
                        onChange={(value) =>
                          handleContactChange(
                            contactIndex,
                            "otherPhoneExtension",
                            value,
                          )
                        }
                        placeholder="Extension"
                      />
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}

          {/* Add Additional Contact Button */}
          {contacts.length < 10 && (
            <div className="flex flex-col items-center">
              <Button
                variant="outline"
                onClick={addContact}
                icon={PlusIcon}
              >
                Add Additional Contact
              </Button>
              <p className={`mt-2 text-xs ${getThemeClasses('text-muted')}`}>
                You can add up to {10 - contacts.length} more contact
                {10 - contacts.length !== 1 ? "s" : ""}
              </p>
            </div>
          )}

          {/* Form Error */}
          {errors.submit && (
            <div
              className={`p-4 rounded-lg flex items-start border ${getThemeClasses("error-bg")} ${getThemeClasses("error-border")}`}
            >
              <ExclamationCircleIcon
                className={`w-5 h-5 mt-0.5 mr-3 flex-shrink-0 ${getThemeClasses("error-text")}`}
              />
              <span className={`text-sm ${getThemeClasses("error-text")}`}>
                {errors.submit}
              </span>
            </div>
          )}
        </div>
      </StaffWizardFormStep>
    </UIXThemeProvider>
  );
}

export default AdminDivisionAddStep3Page;
