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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router";
import { useAuthManager } from "../../../../services/Services";
import {
  UserPlusIcon,
  ArrowLeftIcon,
  ArrowRightIcon,
  UserIcon,
  EnvelopeIcon,
  PhoneIcon,
  BuildingOfficeIcon,
  AcademicCapIcon,
} from "@heroicons/react/24/outline";
import {
  StepWizard,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  Checkbox,
  Button,
  Alert,
  RadioGroup,
  UIXThemeProvider,
} from "../../../../components/UIX";
import {
  CUSTOMER_PHONE_TYPES,
  CUSTOMER_PHONE_TYPE_OPTIONS,
  RESIDENTIAL_CUSTOMER_TYPE_OF_ID,
  COMMERCIAL_CUSTOMER_TYPE_OF_ID,
  CUSTOMER_ORGANIZATION_TYPE_OPTIONS,
} from "../../../../constants/Customer";

// Wizard steps configuration
const WIZARD_STEPS = [
  { id: 1, title: "Search", isCompleted: true },
  { id: 2, title: "Type", isCompleted: true },
  { 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 AdminCustomerAddStep3Page() {
  const authManager = useAuthManager();
  const navigate = useNavigate();

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

  // Form data
  const [customerType, setCustomerType] = useState(null);
  const [organizationName, setOrganizationName] = useState("");
  const [organizationType, setOrganizationType] = useState(0);
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [phoneType, setPhoneType] = useState(CUSTOMER_PHONE_TYPES.MOBILE);
  const [phoneExtension, setPhoneExtension] = useState("");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [otherPhone, setOtherPhone] = useState("");
  const [otherPhoneType, setOtherPhoneType] = useState(0);
  const [otherPhoneExtension, setOtherPhoneExtension] = useState("");
  const [isOkToText, setIsOkToText] = useState(true);
  const [isOkToEmail, setIsOkToEmail] = useState(true);

  // SHSM Information state (stored as string for RadioGroup, converted to boolean when saving)
  const [isSHSMClient, setIsSHSMClient] = useState("no");

  // Memoize loadCustomerState callback
  const loadCustomerState = useCallback(() => {
    try {
      const existing = sessionStorage.getItem(
        "FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE",
      );
      if (existing) {
        const customerState = JSON.parse(existing);

        setCustomerType(customerState.type || null);
        setOrganizationName(customerState.organizationName || "");
        setOrganizationType(customerState.organizationType || 0);
        setEmail(customerState.email || "");
        setPhone(customerState.phone || "");
        setPhoneType(customerState.phoneType || CUSTOMER_PHONE_TYPES.MOBILE);
        setPhoneExtension(customerState.phoneExtension || "");
        setFirstName(customerState.firstName || "");
        setLastName(customerState.lastName || "");
        setOtherPhone(customerState.otherPhone || "");
        setOtherPhoneType(customerState.otherPhoneType || 0);
        setOtherPhoneExtension(customerState.otherPhoneExtension || "");
        setIsOkToText(
          customerState.isOkToText !== undefined
            ? customerState.isOkToText
            : true,
        );
        setIsOkToEmail(
          customerState.isOkToEmail !== undefined
            ? customerState.isOkToEmail
            : true,
        );

        // Load SHSM Information (convert boolean to string for RadioGroup)
        setIsSHSMClient(customerState.isSHSMClient ? "yes" : "no");
      } else {
        // No state found, redirect back to step 2
        navigate("/admin/customers/add/step-2");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error loading customer state:", error);
      }
      navigate("/admin/customers/add/step-2");
    }
  }, []);  // navigate is stable from useNavigate, doesn't need to be in dependencies

  // Check authentication and load existing state
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    // Load existing customer creation state
    loadCustomerState();
  }, [authManager, loadCustomerState]);  // navigate is stable, doesn't need to be in dependencies

  const getExistingState = useCallback(() => {
    try {
      const existing = sessionStorage.getItem(
        "FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE",
      );
      return existing ? JSON.parse(existing) : {};
    } catch (error) {
      return {};
    }
  }, []);

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

  const onSubmitClick = useCallback((e) => {
    e.preventDefault();
    setErrors({});

    let newErrors = {};
    let hasErrors = false;

    // Validation for commercial customers
    if (customerType === COMMERCIAL_CUSTOMER_TYPE_OF_ID) {
      if (!organizationName.trim()) {
        newErrors.organizationName = "Organization name is required";
        hasErrors = true;
      }
      if (organizationType === 0) {
        newErrors.organizationType = "Organization type is required";
        hasErrors = true;
      }
    }

    // General validation
    if (!firstName.trim()) {
      newErrors.firstName = "First name is required";
      hasErrors = true;
    }
    if (!lastName.trim()) {
      newErrors.lastName = "Last name is required";
      hasErrors = true;
    }
    if (!email.trim()) {
      newErrors.email = "Email is required";
      hasErrors = true;
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      newErrors.email = "Please enter a valid email address";
      hasErrors = true;
    }
    if (!phone.trim()) {
      newErrors.phone = "Phone number is required";
      hasErrors = true;
    }
    if (phoneType === 0) {
      newErrors.phoneType = "Phone type is required";
      hasErrors = true;
    }

    // Validate SHSM Client selection
    if (!isSHSMClient || isSHSMClient === "") {
      newErrors.isSHSMClient = "Please indicate if this is an SHSM client";
      hasErrors = true;
    }

    if (hasErrors) {
      setErrors(newErrors);
      return;
    }

    // Save to session storage
    // FIXED: Spread existing state FIRST, then override with new values
    const customerState = {
      // Keep any existing data from previous steps
      ...getExistingState(),
      // Then override with current form values
      organizationName,
      organizationType,
      firstName,
      lastName,
      email,
      phone,
      phoneType,
      phoneExtension,
      otherPhone,
      otherPhoneType,
      otherPhoneExtension,
      isOkToText,
      isOkToEmail,
      // Convert "yes"/"no" string to boolean for storage
      isSHSMClient: isSHSMClient === "yes",
    };

    try {
      sessionStorage.setItem(
        "FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE",
        JSON.stringify(customerState),
      );
      navigate("/admin/customers/add/step-4");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error saving customer state:", error);
      }
      setErrors({ general: "Failed to save data. Please try again." });
    }
  }, [
    customerType,
    organizationName,
    organizationType,
    firstName,
    lastName,
    email,
    phone,
    phoneType,
    phoneExtension,
    otherPhone,
    otherPhoneType,
    otherPhoneExtension,
    isOkToText,
    isOkToEmail,
    isSHSMClient,
    getExistingState,
    navigate,
  ]);

  const handleBack = useCallback(() => {
    navigate("/admin/customers/add/step-2");
  }, [navigate]);

  if (customerType === null) {
    return (
      <UIXThemeProvider>
        <StepWizard
          steps={WIZARD_STEPS}
          currentStep={3}
          title="Add New Customer"
          icon={UserPlusIcon}
        >
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-current opacity-25"></div>
        </div>
      </StepWizard>
      </UIXThemeProvider>
    );
  }

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={3}
        title="Add New Customer"
        icon={UserPlusIcon}
      >
      <form onSubmit={onSubmitClick}>
        {/* Error Alert */}
        {errors.general && (
          <Alert
            type="error"
            message={errors.general}
            onClose={() => setErrors({})}
            className="mb-6"
          />
        )}

        {/* Commercial Customer Section */}
        {customerType === COMMERCIAL_CUSTOMER_TYPE_OF_ID && (
          <FormCard
            title="Commercial Customer Details"
            icon={BuildingOfficeIcon}
            description="Commercial organization information"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={1}>
                <Input
                  label="Organization Name"
                  name="organizationName"
                  value={organizationName}
                  onChange={(value) => setOrganizationName(value)}
                  placeholder="Enter organization name"
                  icon={BuildingOfficeIcon}
                  required
                  error={errors.organizationName}
                />
              </FormRow>

              <FormRow columns={1}>
                <Select
                  label="Organization Type"
                  name="organizationType"
                  value={String(organizationType)}
                  onChange={(value) => setOrganizationType(parseInt(value))}
                  options={CUSTOMER_ORGANIZATION_TYPE_OPTIONS}
                  icon={BuildingOfficeIcon}
                  placeholder=""
                  required
                  error={errors.organizationType}
                />
              </FormRow>
            </FormSection>
          </FormCard>
        )}

        {/* Contact Information Section */}
        <FormCard
          title="Contact Information"
          icon={UserIcon}
          description="Customer contact and phone details"
          maxWidth="full"
          className="mb-6"
        >
          <FormSection>
            <FormRow columns={2}>
              <Input
                label="First Name"
                name="firstName"
                value={firstName}
                onChange={(value) => setFirstName(value)}
                placeholder="Enter first name"
                icon={UserIcon}
                autoComplete="off"
                required
                error={errors.firstName}
              />
              <Input
                label="Last Name"
                name="lastName"
                value={lastName}
                onChange={(value) => setLastName(value)}
                placeholder="Enter last name"
                icon={UserIcon}
                autoComplete="off"
                required
                error={errors.lastName}
              />
            </FormRow>

            <FormRow columns={1}>
              <Input
                label="Email Address"
                name="email"
                type="email"
                value={email}
                onChange={(value) => setEmail(value)}
                placeholder="Enter email address"
                icon={EnvelopeIcon}
                autoComplete="off"
                required
                error={errors.email}
              />
            </FormRow>

            <FormRow columns={1}>
              <Checkbox
                id="isOkToEmail"
                label="I agree to receive electronic email"
                checked={isOkToEmail}
                onChange={(checked) => setIsOkToEmail(checked)}
              />
            </FormRow>

            <FormRow columns={2}>
              <Input
                label="Phone Number"
                name="phone"
                type="tel"
                value={phone}
                onChange={(value) => setPhone(value)}
                placeholder="Enter phone number"
                icon={PhoneIcon}
                autoComplete="off"
                required
                error={errors.phone}
              />
              <Select
                label="Phone Type"
                name="phoneType"
                value={String(phoneType)}
                onChange={(value) => setPhoneType(parseInt(value))}
                options={CUSTOMER_PHONE_TYPE_OPTIONS}
                icon={PhoneIcon}
                required
                error={errors.phoneType}
              />
            </FormRow>

            {phoneType === CUSTOMER_PHONE_TYPES.WORK && (
              <FormRow columns={1}>
                <Input
                  label="Phone Extension (Optional)"
                  name="phoneExtension"
                  value={phoneExtension}
                  onChange={(value) => setPhoneExtension(value)}
                  placeholder="Enter extension"
                />
              </FormRow>
            )}

            <FormRow columns={1}>
              <Checkbox
                id="isOkToText"
                label="I agree to receive texts to my phone"
                checked={isOkToText}
                onChange={(checked) => setIsOkToText(checked)}
              />
            </FormRow>

            <FormRow columns={2}>
              <Input
                label="Other Phone Number"
                name="otherPhone"
                type="tel"
                value={otherPhone}
                onChange={(value) => setOtherPhone(value)}
                placeholder="Enter other phone number"
                icon={PhoneIcon}
              />
              {otherPhone && (
                <Select
                  label="Other Phone Type"
                  name="otherPhoneType"
                  value={String(otherPhoneType)}
                  onChange={(value) => setOtherPhoneType(parseInt(value))}
                  options={CUSTOMER_PHONE_TYPE_OPTIONS}
                  icon={PhoneIcon}
                />
              )}
            </FormRow>

            {otherPhoneType === CUSTOMER_PHONE_TYPES.WORK && otherPhone && (
              <FormRow columns={1}>
                <Input
                  label="Other Phone Extension (Optional)"
                  name="otherPhoneExtension"
                  value={otherPhoneExtension}
                  onChange={(value) => setOtherPhoneExtension(value)}
                  placeholder="Enter extension"
                />
              </FormRow>
            )}
          </FormSection>
        </FormCard>

        {/* SHSM Information Section */}
        <FormCard
          title="SHSM Information"
          icon={AcademicCapIcon}
          description="Specialist High Skills Major program details"
          maxWidth="full"
          className="mb-6"
        >
          <FormSection>
            <FormRow columns={1}>
              <RadioGroup
                id="isSHSMClient"
                name="isSHSMClient"
                label="Is this an SHSM client?"
                value={isSHSMClient}
                onChange={(value) => setIsSHSMClient(value)}
                options={[
                  { value: "yes", label: "Yes" },
                  { value: "no", label: "No" },
                ]}
                layout="horizontal"
                required={true}
                error={errors.isSHSMClient}
              />
            </FormRow>
          </FormSection>
        </FormCard>

        {/* Form Actions */}
        <div className="flex flex-col sm:flex-row gap-3 mt-6">
          <Button
            type="button"
            variant="outline"
            onClick={handleBack}
            icon={ArrowLeftIcon}
            className="flex-1"
          >
            Back
          </Button>
          <Button
            type="submit"
            variant="primary"
            icon={ArrowRightIcon}
            disabled={isLoading}
            loading={isLoading}
            className="flex-1"
          >
            Next
          </Button>
        </div>
      </form>
    </StepWizard>
    </UIXThemeProvider>
  );
}

export default AdminCustomerAddStep3Page;
