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

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router";
import { useAuthManager } from "../../../../services/Services";
import {
  UserPlusIcon,
  ArrowLeftIcon,
  ArrowRightIcon,
  ExclamationTriangleIcon,
  TagIcon,
  CalendarIcon,
  ChatBubbleBottomCenterTextIcon,
  UserIcon,
  QuestionMarkCircleIcon,
  LanguageIcon,
  LockClosedIcon,
} from "@heroicons/react/24/outline";
import {
  StepWizard,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  Button,
  Alert,
  RadioGroup,
  Textarea,
  Modal,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";
import HowHearAboutUsSelect from "../../../../components/business/selects/HowHearAboutUsSelect";
import TagsMultiSelect from "../../../../components/business/selects/TagsMultiSelect";
import {
  CUSTOMER_GENDER_OPTIONS,
  CUSTOMER_GENDER_TYPES,
  CUSTOMER_LANGUAGES,
  CUSTOMER_VALIDATION,
} 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: true },
  { id: 4, title: "Address", isCompleted: true },
  { id: 5, title: "Account", isCompleted: false },
  { id: 6, title: "Review", isCompleted: false },
];

function AdminCustomerAddStep5Page() {
  const authManager = useAuthManager();
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

  // Get existing customer data from sessionStorage
  const [customerData, setCustomerData] = useState(() => {
    const saved = sessionStorage.getItem(
      "FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE",
    );
    return saved ? JSON.parse(saved) : {};
  });

  // Component state
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [showCancelWarning, setShowCancelWarning] = useState(false);
  const [tags, setTags] = useState(customerData.tags || []);
  const [howDidYouHearAboutUsID, setHowDidYouHearAboutUsID] = useState(
    customerData.howDidYouHearAboutUsID || "",
  );
  const [isHowDidYouHearAboutUsOther, setIsHowDidYouHearAboutUsOther] =
    useState(customerData.isHowDidYouHearAboutUsOther || false);
  const [howDidYouHearAboutUsOther, setHowDidYouHearAboutUsOther] = useState(
    customerData.howDidYouHearAboutUsOther || "",
  );
  const [joinDate, setJoinDate] = useState(
    customerData.joinDate || new Date().toISOString().split("T")[0],
  );
  const [gender, setGender] = useState(customerData.gender || 0);
  const [genderOther, setGenderOther] = useState(
    customerData.genderOther || "",
  );
  const [additionalComment, setAdditionalComment] = useState(
    customerData.additionalComment || "",
  );
  // Default to "English" if no saved preference
  const [preferredLanguage, setPreferredLanguage] = useState(
    customerData.preferredLanguage || CUSTOMER_LANGUAGES.ENGLISH,
  );
  const [password, setPassword] = useState(customerData.password || "");
  const [passwordRepeated, setPasswordRepeated] = useState(
    customerData.passwordRepeated || "",
  );

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

    window.scrollTo(0, 0);
    // Check if we have customer data, if not redirect to step 1
    const saved = sessionStorage.getItem(
      "FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE",
    );
    if (!saved) {
      navigate("/admin/customers/add/step-1");
    }
  }, [authManager, navigate]);

  const validateForm = useCallback(() => {
    const newErrors = {};

    if (!howDidYouHearAboutUsID) {
      newErrors.howDidYouHearAboutUsID =
        "Please specify how you heard about us";
    } else if (
      isHowDidYouHearAboutUsOther &&
      !howDidYouHearAboutUsOther.trim()
    ) {
      newErrors.howDidYouHearAboutUsOther = "Please specify other option";
    }

    // Gender validation removed - now optional
    // Only validate "Other" field if gender is set to "Other" (1)
    if (gender === CUSTOMER_GENDER_TYPES.OTHER && !genderOther.trim()) {
      newErrors.genderOther = "Please specify the gender";
    }

    if (!joinDate) {
      newErrors.joinDate = "Join date is required";
    }

    if (!preferredLanguage) {
      newErrors.preferredLanguage = "Preferred language is required";
    }

    if (password || passwordRepeated) {
      if (password !== passwordRepeated) {
        newErrors.password = "Passwords do not match";
        newErrors.passwordRepeated = "Passwords do not match";
      }
    }

    return newErrors;
  }, [
    howDidYouHearAboutUsID,
    isHowDidYouHearAboutUsOther,
    howDidYouHearAboutUsOther,
    gender,
    genderOther,
    joinDate,
    preferredLanguage,
    password,
    passwordRepeated,
  ]);

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

  const handleConfirmCancel = useCallback(() => {
    sessionStorage.removeItem("FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE");
    navigate("/admin/customers");
  }, [navigate]);

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

    if (import.meta.env.DEV) {
      console.log("onSubmitClick: Beginning...");
    }

    const formErrors = validateForm();
    if (Object.keys(formErrors).length > 0) {
      setErrors(formErrors);
      window.scrollTo(0, 0);

      if (import.meta.env.DEV) {
        console.log("onSubmitClick: Validation failed");  // Don't log actual error details
      }
      return;
    }

    setErrors({});

    // Save data to sessionStorage (keeping birthDate for backward compatibility)
    const updatedCustomerData = {
      ...customerData,
      tags,
      howDidYouHearAboutUsID,
      howDidYouHearAboutUsOther,
      isHowDidYouHearAboutUsOther,
      gender,
      genderOther,
      birthDate: customerData.birthDate || "", // Keep for backward compatibility
      joinDate,
      additionalComment,
      preferredLanguage,
      // SECURITY: DO NOT store passwords in sessionStorage - they are stored in component state only
      // and will be submitted directly to the API in Step 6
      // password,         // REMOVED for security
      // passwordRepeated, // REMOVED for security
    };

    sessionStorage.setItem(
      "FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE",
      JSON.stringify(updatedCustomerData),
    );

    // Store passwords in customerData state but NOT in sessionStorage
    setCustomerData({
      ...updatedCustomerData,
      password,
      passwordRepeated,
    });

    if (import.meta.env.DEV) {
      console.log("onSubmitClick: Ending with success.");
    }
    navigate("/admin/customers/add/step-6");
  }, [
    validateForm,
    customerData,
    tags,
    howDidYouHearAboutUsID,
    howDidYouHearAboutUsOther,
    isHowDidYouHearAboutUsOther,
    gender,
    genderOther,
    joinDate,
    additionalComment,
    preferredLanguage,
    password,
    passwordRepeated,
    navigate,
  ]);

  const handleHowHearChange = useCallback(
    (value) => {
      setHowDidYouHearAboutUsID(value);
      // Clear error when user selects a value
      if (errors.howDidYouHearAboutUsID) {
        setErrors({ ...errors, howDidYouHearAboutUsID: null });
      }
    },
    [errors],
  );

  const handleHowHearOtherDetected = useCallback(
    (isOther) => {
      setIsHowDidYouHearAboutUsOther(isOther);
      if (!isOther) {
        setHowDidYouHearAboutUsOther(""); // Clear other field if not "Other"
      }
    },
    [],
  );

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

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

        {/* Discovery & Tags Section */}
        <FormCard
          title="Discovery & Classification"
          icon={QuestionMarkCircleIcon}
          description="How did they find us and how we categorize them"
          maxWidth="full"
          className="mb-6"
        >
          <FormSection>
            {/* Honeypot for Chrome autofill - positioned outside FormRow */}
            <input
              id="email_honeypot"
              name="email_honeypot"
              type="email"
              autoComplete="email"
              tabIndex={-1}
              aria-label="Email honeypot - do not fill"
              style={{
                position: 'absolute',
                left: '-9999px',
                width: '1px',
                height: '1px',
                opacity: 0,
                pointerEvents: 'none'
              }}
            />
            <FormRow columns={1}>
              <TagsMultiSelect
                value={tags}
                onChange={setTags}
                error={errors.tags}
                required={false}
                label="Tags (Optional)"
                onUnauthorized={() => navigate("/login?unauthorized=true")}
              />
            </FormRow>

            <FormRow columns={1}>
              <HowHearAboutUsSelect
                value={howDidYouHearAboutUsID}
                onChange={handleHowHearChange}
                onOtherDetected={handleHowHearOtherDetected}
                error={errors.howDidYouHearAboutUsID}
                required={true}
                label="How did you hear about us?"
                onUnauthorized={() => navigate("/login?unauthorized=true")}
              />
            </FormRow>

            {isHowDidYouHearAboutUsOther && (
              <FormRow columns={1}>
                <Input
                  label="How did you hear about us? (Other)"
                  name="howDidYouHearAboutUsOther"
                  value={howDidYouHearAboutUsOther}
                  onChange={(value) => setHowDidYouHearAboutUsOther(value)}
                  placeholder="Please specify"
                  required
                  error={errors.howDidYouHearAboutUsOther}
                />
              </FormRow>
            )}
          </FormSection>
        </FormCard>

        {/* Personal Information Section */}
        <FormCard
          title="Personal Information"
          icon={UserIcon}
          description="Demographic and preference details"
          maxWidth="full"
          className="mb-6"
        >
          <FormSection>
            <FormRow columns={2}>
              <Select
                label="Gender (Optional)"
                name="gender"
                value={String(gender)}
                onChange={(value) => setGender(parseInt(value))}
                options={CUSTOMER_GENDER_OPTIONS.map((opt) => ({
                  value: String(opt.value),
                  label: opt.label,
                }))}
                icon={UserIcon}
                placeholder=""
                error={errors.gender}
              />

              {gender === CUSTOMER_GENDER_TYPES.OTHER && (
                <Input
                  label="Gender (Other)"
                  name="genderOther"
                  value={genderOther}
                  onChange={(value) => setGenderOther(value)}
                  placeholder="Please specify"
                  icon={UserIcon}
                  required
                  error={errors.genderOther}
                />
              )}

              {gender !== CUSTOMER_GENDER_TYPES.OTHER && (
                <Input
                  label="Join Date"
                  name="joinDate"
                  type="date"
                  value={joinDate}
                  onChange={(value) => setJoinDate(value)}
                  icon={CalendarIcon}
                  required
                  error={errors.joinDate}
                  helperText="When the user joined the workery (automatically set to today)"
                  disabled
                />
              )}
            </FormRow>

            {gender === CUSTOMER_GENDER_TYPES.OTHER && (
              <FormRow columns={1}>
                <Input
                  label="Join Date"
                  name="joinDate"
                  type="date"
                  value={joinDate}
                  onChange={(value) => setJoinDate(value)}
                  icon={CalendarIcon}
                  required
                  error={errors.joinDate}
                  helperText="When the user joined the workery (automatically set to today)"
                  disabled
                />
              </FormRow>
            )}

            <FormRow columns={1}>
              <RadioGroup
                id="preferredLanguage"
                name="preferredLanguage"
                label="Preferred Language"
                icon={LanguageIcon}
                value={preferredLanguage}
                onChange={(value) => setPreferredLanguage(value)}
                options={[
                  { value: CUSTOMER_LANGUAGES.ENGLISH, label: CUSTOMER_LANGUAGES.ENGLISH },
                  { value: CUSTOMER_LANGUAGES.FRENCH, label: CUSTOMER_LANGUAGES.FRENCH },
                ]}
                layout="horizontal"
                required
                error={errors.preferredLanguage}
              />
            </FormRow>

            <FormRow columns={1}>
              <Textarea
                label="Additional Comment (Optional)"
                name="additionalComment"
                value={additionalComment}
                onChange={(value) => setAdditionalComment(value)}
                placeholder={`Max ${CUSTOMER_VALIDATION.COMMENT_MAX_LENGTH} characters`}
                rows={4}
                maxLength={CUSTOMER_VALIDATION.COMMENT_MAX_LENGTH}
                icon={ChatBubbleBottomCenterTextIcon}
                helperText={`${additionalComment.length}/${CUSTOMER_VALIDATION.COMMENT_MAX_LENGTH} characters`}
              />
            </FormRow>
          </FormSection>
        </FormCard>

        {/* Login Credentials Section */}
        <FormCard
          title="Login Credentials"
          icon={LockClosedIcon}
          description="Set up account access (optional)"
          maxWidth="full"
          className="mb-6"
        >
          <FormSection>
            {/* Honeypot for Chrome autofill - positioned outside FormRow */}
            <input
              id="password_honeypot"
              name="password_honeypot"
              type="password"
              autoComplete="current-password"
              tabIndex={-1}
              aria-label="Password honeypot - do not fill"
              style={{
                position: 'absolute',
                left: '-9999px',
                width: '1px',
                height: '1px',
                opacity: 0,
                pointerEvents: 'none'
              }}
            />
            <FormRow columns={2}>
              <Input
                label="Password (Optional)"
                name="password"
                type="password"
                value={password}
                onChange={(value) => setPassword(value)}
                placeholder="Leave blank if not setting a password"
                icon={LockClosedIcon}
                autoComplete="new-password"
                error={errors.password}
              />
              <Input
                label="Password Repeated (Optional)"
                name="passwordRepeated"
                type="password"
                value={passwordRepeated}
                onChange={(value) => setPasswordRepeated(value)}
                placeholder="Repeat password here"
                icon={LockClosedIcon}
                autoComplete="new-password"
                error={errors.passwordRepeated}
              />
            </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="button"
            variant="secondary"
            onClick={handleCancel}
            className="flex-1"
          >
            Cancel
          </Button>
          <Button
            type="submit"
            variant="primary"
            icon={ArrowRightIcon}
            disabled={isLoading}
            loading={isLoading}
            className="flex-1"
          >
            Next
          </Button>
        </div>
      </form>

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

export default AdminCustomerAddStep5Page;
