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

import React, { useState, useEffect, useCallback, useMemo, memo } from "react";
import { useNavigate } from "react-router";
import { useStaffAddWizardStorage } from "../../../../services/Services";
import {
  UserPlusIcon,
  ArrowRightIcon,
  ShieldCheckIcon,
  LanguageIcon,
  PhoneIcon,
  UserGroupIcon,
  LockClosedIcon,
  ComputerDesktopIcon,
  CheckIcon,
} from "@heroicons/react/24/outline";
import {
  StaffWizardFormStep,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  Textarea,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";

// Language constants
const LANGUAGE_ENGLISH = "English";
const LANGUAGE_FRENCH = "French";

// Password validation constants
const PASSWORD_MIN_LENGTH = 8;
const PASSWORD_MAX_LENGTH = 255;
const PASSWORD_REGEX = {
  hasUpperCase: /[A-Z]/,
  hasLowerCase: /[a-z]/,
  hasNumbers: /\d/,
  hasSpecialChar: /[!@#$%^&*(),.?":{}|<>]/,
};

// Language options (static, moved outside component)
const LANGUAGE_OPTIONS = [
  { value: LANGUAGE_ENGLISH, label: "English" },
  { value: LANGUAGE_FRENCH, label: "French" },
];

// Wizard configuration (static, moved outside component)
const WIZARD_STEPS = [
  { id: 1, title: "Search", subtitle: "Find Staff", isActive: false, isCompleted: true },
  { id: 2, title: "Type", subtitle: "Select Type", isActive: false, isCompleted: true },
  { id: 3, title: "Contact", subtitle: "Information", isActive: false, isCompleted: true },
  { id: 4, title: "Address", subtitle: "Location", isActive: false, isCompleted: true },
  { id: 5, title: "Account", subtitle: "Settings", isActive: true, isCompleted: false },
  { id: 6, title: "Metrics", subtitle: "Performance", isActive: false, isCompleted: false },
  { id: 7, title: "Comments", subtitle: "Notes", isActive: false, isCompleted: false },
];

// Memoized content component
const Step5Content = memo(function Step5Content() {
  const navigate = useNavigate();
  const wizardStorage = useStaffAddWizardStorage();
  const { getThemeClasses } = useUIXTheme();

  // PERFORMANCE: Memoize wizardState to prevent unnecessary re-computation
  const wizardState = useMemo(() => wizardStorage.getWizardState(), [wizardStorage]);

  // Component states
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [passwordStrength, setPasswordStrength] = useState(0);
  const [passwordRequirements, setPasswordRequirements] = useState({
    minLength: false,
    hasUpperCase: false,
    hasLowerCase: false,
    hasNumbers: false,
    hasSpecialChar: false,
  });

  // Account form data
  const [limitSpecial, setLimitSpecial] = useState(
    wizardState.limitSpecial || "",
  );
  const [policeCheck, setPoliceCheck] = useState(wizardState.policeCheck || "");
  const [emergencyContactName, setEmergencyContactName] = useState(
    wizardState.emergencyContactName || "",
  );
  const [emergencyContactRelationship, setEmergencyContactRelationship] =
    useState(wizardState.emergencyContactRelationship || "");
  const [emergencyContactTelephone, setEmergencyContactTelephone] = useState(
    wizardState.emergencyContactTelephone || "",
  );
  const [
    emergencyContactAlternativeTelephone,
    setEmergencyContactAlternativeTelephone,
  ] = useState(wizardState.emergencyContactAlternativeTelephone || "");
  const [description, setDescription] = useState(wizardState.description || "");
  const [preferredLanguage, setPreferredLanguage] = useState(
    wizardState.preferredLanguage || LANGUAGE_ENGLISH,
  );
  // Initialize passwords as empty for new staff creation
  const [password, setPassword] = useState("");
  const [passwordRepeated, setPasswordRepeated] = useState("");

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

  // Scroll to top on mount only
  useEffect(() => {
    window.scrollTo(0, 0);
  }, []);

  // Check for existing state and redirect if needed
  useEffect(() => {
    // If no wizard state exists, redirect back to step 1
    if (!wizardState || Object.keys(wizardState).length === 0) {
      navigate("/admin/staff/add/step-1-search");
    }
  }, [wizardState, navigate]);

  // Password strength calculator
  const calculatePasswordStrength = (pwd) => {
    if (!pwd) return 0;

    let strength = 0;
    const requirements = {
      minLength: pwd.length >= PASSWORD_MIN_LENGTH,
      hasUpperCase: PASSWORD_REGEX.hasUpperCase.test(pwd),
      hasLowerCase: PASSWORD_REGEX.hasLowerCase.test(pwd),
      hasNumbers: PASSWORD_REGEX.hasNumbers.test(pwd),
      hasSpecialChar: PASSWORD_REGEX.hasSpecialChar.test(pwd),
    };

    // Calculate strength based on requirements met
    Object.values(requirements).forEach((met) => {
      if (met) strength += 20;
    });

    setPasswordRequirements(requirements);
    setPasswordStrength(strength);
    return requirements;
  };

  // Handle password change with validation
  const handlePasswordChange = useCallback((value) => {
    setPassword(value);
    calculatePasswordStrength(value);

    // Clear password errors when user starts typing
    if (errors.password) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors.password;
        return newErrors;
      });
    }
  }, [errors.password]);

  // Validate password according to business rules
  const validatePassword = (pwd, pwdRepeated) => {
    const errors = {};

    if (!pwd || pwd.trim() === "") {
      errors.password = "Password is required";
      return errors;
    }

    if (pwd.length < PASSWORD_MIN_LENGTH) {
      errors.password = `Password must be at least ${PASSWORD_MIN_LENGTH} characters long`;
      return errors;
    }

    if (pwd.length > PASSWORD_MAX_LENGTH) {
      errors.password = `Password must not exceed ${PASSWORD_MAX_LENGTH} characters`;
      return errors;
    }

    // Check password complexity requirements
    const requirements = calculatePasswordStrength(pwd);
    const missingRequirements = [];

    if (!requirements.hasUpperCase)
      missingRequirements.push("one uppercase letter");
    if (!requirements.hasLowerCase)
      missingRequirements.push("one lowercase letter");
    if (!requirements.hasNumbers) missingRequirements.push("one number");
    if (!requirements.hasSpecialChar)
      missingRequirements.push("one special character");

    if (missingRequirements.length > 0) {
      errors.password = `Password must contain at least ${missingRequirements.join(", ")}`;
      return errors;
    }

    if (pwd !== pwdRepeated) {
      errors.password = "Passwords do not match";
      errors.passwordRepeated = "Passwords do not match";
      return errors;
    }

    return errors;
  };

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

    let newErrors = {};
    let hasErrors = false;

    // Emergency contact validation - now optional, no validation needed
    // Preferred language is still required
    if (!preferredLanguage.trim()) {
      newErrors.preferredLanguage = "Preferred language is required";
      hasErrors = true;
    }

    // Password validation - now required
    const passwordErrors = validatePassword(password, passwordRepeated);
    if (Object.keys(passwordErrors).length > 0) {
      newErrors = { ...newErrors, ...passwordErrors };
      hasErrors = true;
    }

    // Check if password confirmation is empty when password is provided
    if (password && !passwordRepeated) {
      newErrors.passwordRepeated = "Please confirm your password";
      hasErrors = true;
    }

    if (hasErrors) {
      setErrors(newErrors);
      // Scroll to top to show errors
      window.scrollTo(0, 0);
      return;
    }

    setIsLoading(true);

    try {
      // Save to storage
      const dataToSave = {
        limitSpecial,
        policeCheck,
        emergencyContactName,
        emergencyContactRelationship,
        emergencyContactTelephone,
        emergencyContactAlternativeTelephone,
        description,
        preferredLanguage,
        password,
        passwordRepeated,
      };

      // Update wizard storage
      wizardStorage.updateWizardState(dataToSave);

      // Navigate to next step
      navigate("/admin/staff/add/step-6");
    } catch (error) {
      if (import.meta.env.DEV) {
      console.error("Error saving account information:", error);
      setErrors({
        general: "Failed to save account information. Please try again.",
      });
      }
      setIsLoading(false);
    }
  }, [emergencyContactName, emergencyContactRelationship, emergencyContactTelephone, preferredLanguage, password, passwordRepeated, limitSpecial, policeCheck, emergencyContactAlternativeTelephone, description, wizardStorage, navigate]);

  // Get password strength color - theme-aware progression
  const getPasswordStrengthColor = () => {
    const primaryThemeClass = getThemeClasses('button-primary');
    // Extract the base theme color from the primary button class (bg-blue-900 or bg-red-900)
    const isRedTheme = primaryThemeClass.includes('bg-red-');
    const baseColor = isRedTheme ? 'red' : 'blue';

    if (passwordStrength <= 20) return `bg-${baseColor}-200`;
    if (passwordStrength <= 40) return `bg-${baseColor}-300`;
    if (passwordStrength <= 60) return `bg-${baseColor}-500`;
    if (passwordStrength <= 80) return `bg-${baseColor}-700`;
    return `bg-${baseColor}-900`;
  };

  // Get password strength text
  const getPasswordStrengthText = () => {
    if (passwordStrength <= 20) return "Weak";
    if (passwordStrength <= 40) return "Fair";
    if (passwordStrength <= 60) return "Good";
    if (passwordStrength <= 80) return "Strong";
    return "Very Strong";
  };

  // Memoized input handlers to prevent re-rendering and focus issues
  const handleLimitSpecialChange = useCallback((e) => {
    setLimitSpecial(e.target.value);
  }, []);

  const handlePoliceCheckChange = useCallback((value) => {
    setPoliceCheck(value);
  }, []);

  const handleEmergencyContactNameChange = useCallback((value) => {
    setEmergencyContactName(value);
  }, []);

  const handleEmergencyContactRelationshipChange = useCallback((value) => {
    setEmergencyContactRelationship(value);
  }, []);

  const handleEmergencyContactTelephoneChange = useCallback((value) => {
    setEmergencyContactTelephone(value);
  }, []);

  const handleEmergencyContactAlternativeTelephoneChange = useCallback((value) => {
    setEmergencyContactAlternativeTelephone(value);
  }, []);

  const handleDescriptionChange = useCallback((value) => {
    setDescription(value);
  }, []);

  const handlePreferredLanguageChange = useCallback((value) => {
    setPreferredLanguage(value);
  }, []);

  const handlePasswordRepeatedChange = useCallback((value) => {
    setPasswordRepeated(value);
    // Clear error when user starts typing
    if (errors.passwordRepeated) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors.passwordRepeated;
        return newErrors;
      });
    }
  }, [errors.passwordRepeated]);

  // Memoized theme classes
  const themeClasses = useMemo(() => ({
    borderPrimary: getThemeClasses('border-primary'),
    linkPrimary: getThemeClasses('link-primary'),
    errorText: getThemeClasses('error-text'),
    alertInfoBg: getThemeClasses('alert-info-bg'),
    alertInfoBorder: getThemeClasses('alert-info-border'),
    alertInfoText: getThemeClasses('alert-info-text'),
  }), [getThemeClasses]);

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

  const handleCancel = useCallback(() => {
    navigate("/admin/staff");
  }, [navigate]);

  // Action configuration
  const actions = useMemo(() => [
    {
      label: "Continue to Metrics",
      variant: "primary",
      icon: ArrowRightIcon,
      onClick: onSubmitClick,
      disabled: isLoading,
    }
  ], [onSubmitClick, isLoading]);

  return (
    <StaffWizardFormStep
      wizardSteps={WIZARD_STEPS}
      currentStep={5}
      wizardTitle="Add New Staff Member"
      wizardIcon={UserPlusIcon}
      stepTitle="Account Settings"
      stepIcon={ComputerDesktopIcon}
      showFormCard={false}
      contentMaxWidth="7xl"
      errors={errors}
      isLoading={isLoading}
      actions={actions}
      onCancel={handleCancel}
      onBack={handleBack}
      actionLayout="end"
    >
      {/* Hidden honeypot fields to catch browser autofill */}
      <div style={{ position: 'absolute', left: '-9999px', width: '1px', height: '1px' }} aria-hidden="true">
        <input type="email" name="email" tabIndex="-1" autoComplete="email" />
        <input type="password" name="password" tabIndex="-1" autoComplete="current-password" />
      </div>

      {/* Compliance Information Section */}
      <FormCard
        title="Compliance Information"
        icon={ShieldCheckIcon}
        maxWidth="7xl"
        className="mb-8"
      >
        <FormSection>
          <FormRow columns={1}>
            <Input
              label="Police Check Expiry"
              type="date"
              value={policeCheck}
              onChange={handlePoliceCheckChange}
            />
          </FormRow>
        </FormSection>
      </FormCard>

      {/* Emergency Contact Section */}
      <FormCard
        title="Emergency Contact"
        icon={UserGroupIcon}
        maxWidth="7xl"
        className="mb-8"
      >
        <FormSection>
          <FormRow columns={2}>
            <Input
              label="Contact Name"
              type="text"
              value={emergencyContactName}
              onChange={handleEmergencyContactNameChange}
              placeholder="Enter emergency contact name"
              error={errors.emergencyContactName}
            />
            <Input
              label="Relationship"
              type="text"
              value={emergencyContactRelationship}
              onChange={handleEmergencyContactRelationshipChange}
              placeholder="Enter relationship"
              error={errors.emergencyContactRelationship}
            />
          </FormRow>

          <FormRow columns={1}>
            <Input
              label="Phone Number"
              type="tel"
              value={emergencyContactTelephone}
              onChange={handleEmergencyContactTelephoneChange}
              placeholder="Enter phone number"
              icon={PhoneIcon}
              error={errors.emergencyContactTelephone}
            />
          </FormRow>
        </FormSection>
      </FormCard>

      {/* System Settings Section */}
      <FormCard
        title="System Settings"
        icon={ComputerDesktopIcon}
        maxWidth="7xl"
        className="mb-8"
      >
        <FormSection>
          <Select
            label="Preferred Language"
            value={preferredLanguage}
            onChange={handlePreferredLanguageChange}
            options={LANGUAGE_OPTIONS}
            icon={LanguageIcon}
            error={errors.preferredLanguage}
            required
          />
        </FormSection>

        <FormSection>
          <Textarea
            label="Description"
            value={description}
            onChange={handleDescriptionChange}
            placeholder="Enter any additional notes or description about this staff member"
            rows={4}
            maxLength={638}
          />
        </FormSection>
      </FormCard>

      {/* Login Credentials Section */}
      <FormCard
        title="Login Credentials"
        icon={LockClosedIcon}
        maxWidth="7xl"
      >
        <FormSection>
          <Input
            label="Password"
            type="password"
            value={password}
            onChange={handlePasswordChange}
            placeholder="Enter a secure password"
            error={errors.password}
            autoComplete="new-password"
            required
          />

          {/* Password strength indicator */}
          {password && (
            <div className="mt-4">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm text-gray-600">
                  Password strength:
                </span>
                <span
                  className={`text-sm font-medium ${
                    passwordStrength >= 80
                      ? themeClasses.linkPrimary
                      : passwordStrength >= 60
                        ? themeClasses.linkPrimary
                        : passwordStrength >= 40
                          ? themeClasses.linkPrimary
                          : themeClasses.errorText
                  }`}
                >
                  {getPasswordStrengthText()}
                </span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div
                  className={`h-2 rounded-full transition-all duration-300 ${getPasswordStrengthColor()}`}
                  style={{ width: `${passwordStrength}%` }}
                ></div>
              </div>

              {/* Password requirements checklist */}
              <div className="mt-3 space-y-2">
                <div
                  className={`text-sm flex items-center ${
                    passwordRequirements.minLength
                      ? themeClasses.linkPrimary
                      : "text-gray-500"
                  }`}
                >
                  <CheckIcon
                    className={`w-4 h-4 mr-2 ${
                      passwordRequirements.minLength
                        ? "visible"
                        : "invisible"
                    }`}
                  />
                  At least 8 characters
                </div>
                <div
                  className={`text-sm flex items-center ${
                    passwordRequirements.hasUpperCase
                      ? themeClasses.linkPrimary
                      : "text-gray-500"
                  }`}
                >
                  <CheckIcon
                    className={`w-4 h-4 mr-2 ${
                      passwordRequirements.hasUpperCase
                        ? "visible"
                        : "invisible"
                    }`}
                  />
                  One uppercase letter
                </div>
                <div
                  className={`text-sm flex items-center ${
                    passwordRequirements.hasLowerCase
                      ? themeClasses.linkPrimary
                      : "text-gray-500"
                  }`}
                >
                  <CheckIcon
                    className={`w-4 h-4 mr-2 ${
                      passwordRequirements.hasLowerCase
                        ? "visible"
                        : "invisible"
                    }`}
                  />
                  One lowercase letter
                </div>
                <div
                  className={`text-sm flex items-center ${
                    passwordRequirements.hasNumbers
                      ? themeClasses.linkPrimary
                      : "text-gray-500"
                  }`}
                >
                  <CheckIcon
                    className={`w-4 h-4 mr-2 ${
                      passwordRequirements.hasNumbers
                        ? "visible"
                        : "invisible"
                    }`}
                  />
                  One number
                </div>
                <div
                  className={`text-sm flex items-center ${
                    passwordRequirements.hasSpecialChar
                      ? themeClasses.linkPrimary
                      : "text-gray-500"
                  }`}
                >
                  <CheckIcon
                    className={`w-4 h-4 mr-2 ${
                      passwordRequirements.hasSpecialChar
                        ? "visible"
                        : "invisible"
                    }`}
                  />
                  One special character (!@#$%^&*...)
                </div>
              </div>
            </div>
          )}

          <Input
            label="Confirm Password"
            type="password"
            value={passwordRepeated}
            onChange={handlePasswordRepeatedChange}
            placeholder="Re-enter your password"
            error={errors.passwordRepeated}
            autoComplete="new-password"
            required
          />

          {passwordRepeated && password === passwordRepeated && (
            <div className={`mt-2 text-sm flex items-center ${themeClasses.linkPrimary}`}>
              <CheckIcon className="w-4 h-4 mr-2" />
              Passwords match
            </div>
          )}
        </FormSection>

        <div className={`mt-6 p-4 rounded-lg ${themeClasses.alertInfoBg} border ${themeClasses.alertInfoBorder}`}>
          <p className={`text-sm ${themeClasses.alertInfoText}`}>
            <strong>Security Note:</strong> The staff member will need
            this password to log into their account. Make sure to
            securely share this password with them after account
            creation.
          </p>
        </div>
      </FormCard>
    </StaffWizardFormStep>
  );
});

Step5Content.displayName = 'Step5Content';

function AdminStaffAddStep5Page() {
  return (
    <UIXThemeProvider>
      <Step5Content />
    </UIXThemeProvider>
  );
}

export default AdminStaffAddStep5Page;
