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

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router";
import { useAuthManager, useInsuranceRequirementManager, useServiceFeeManager } from "../../../../services/Services";
import {
  ChatBubbleBottomCenterIcon,
  ArrowLeftIcon,
  ArrowRightIcon,
  ChartBarIcon,
  AcademicCapIcon,
  ShieldCheckIcon,
  CurrencyDollarIcon,
  CalendarDaysIcon,
  ComputerDesktopIcon,
  LockClosedIcon,
  LanguageIcon,
  ClockIcon,
} from "@heroicons/react/24/outline";
import {
  UIXThemeProvider,
  StepWizard,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  Button,
  Alert,
} from "../../../../components/UIX";
import {
  SkillSetsMultiSelect,
} from "../../../../components/business/selects";

// Constants - moved outside component
const WIZARD_STEPS = [
  { title: "Search", isCompleted: true },
  { title: "Type", isCompleted: true },
  { title: "Contact", isCompleted: true },
  { title: "Address", isCompleted: true },
  { title: "Account", isCompleted: false },
  { title: "Metrics" },
  { title: "Review" },
];

const LEVEL_OPTIONS = [
  { value: "", label: "Select a level" },
  { value: "level1", label: "Level 1 (unpaid)" },
  { value: "level2", label: "Level 2 (paid)" },
];

const LANGUAGE_OPTIONS = [
  { value: "English", label: "English" },
  { value: "French", label: "French" },
];

const DAYS_OF_WEEK = [
  { key: "monday", label: "Monday" },
  { key: "tuesday", label: "Tuesday" },
  { key: "wednesday", label: "Wednesday" },
  { key: "thursday", label: "Thursday" },
  { key: "friday", label: "Friday" },
  { key: "saturday", label: "Saturday" },
  { key: "sunday", label: "Sunday" },
];

function AdminSpeakerAddStep5Page() {
  const authManager = useAuthManager();
  const navigate = useNavigate();
  const insuranceRequirementManager = useInsuranceRequirementManager();
  const serviceFeeManager = useServiceFeeManager();

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

  // Level state
  const [level, setLevel] = useState("");

  // Availability state
  const [availability, setAvailability] = useState({
    monday: { am: false, pm: false },
    tuesday: { am: false, pm: false },
    wednesday: { am: false, pm: false },
    thursday: { am: false, pm: false },
    friday: { am: false, pm: false },
    saturday: { am: false, pm: false },
    sunday: { am: false, pm: false },
  });

  // Account form data
  const [skillSets, setSkillSets] = useState([]);
  const [insuranceRequirements, setInsuranceRequirements] = useState([]);
  const [insuranceRequirementOptions, setInsuranceRequirementOptions] = useState([]);
  const [hourlySalaryDesired, setHourlySalaryDesired] = useState("");
  const [commercialInsuranceExpiryDate, setCommercialInsuranceExpiryDate] = useState("");
  const [policeCheck, setPoliceCheck] = useState("");
  const [taxId, setTaxId] = useState("");
  const [serviceFeeId, setServiceFeeId] = useState("");
  const [isServiceFeeOther, setIsServiceFeeOther] = useState(false);
  const [serviceFeeOther, setServiceFeeOther] = useState("");
  const [serviceFeeOptions, setServiceFeeOptions] = useState([]);
  const [preferredLanguage, setPreferredLanguage] = useState("English");
  const [password, setPassword] = useState("");
  const [passwordRepeated, setPasswordRepeated] = useState("");

  // Define onUnauthorized callback before using it in useEffects
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

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

    loadSpeakerState();
  }, [authManager, navigate]);

  // Fetch insurance requirement options
  useEffect(() => {
    const fetchInsuranceRequirementOptions = async () => {
      try {
        const options = await insuranceRequirementManager.getInsuranceRequirementSelectOptions(
          onUnauthorized,
          false
        );

        if (options && options.length > 0) {
          const formattedOptions = options.map(opt => ({
            value: opt.value !== undefined ? String(opt.value) : String(opt.id),
            label: opt.label || opt.text || opt.name || `Insurance Requirement ${opt.id}`,
          }));

          setInsuranceRequirementOptions(formattedOptions);
          // Insurance requirement is now optional - no auto-selection
        }
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Error fetching insurance requirement options:", error);
        }
      }
    };

    if (insuranceRequirementOptions.length === 0) {
      fetchInsuranceRequirementOptions();
    }
  }, [insuranceRequirementOptions.length]);

  // Fetch service fee options
  useEffect(() => {
    const fetchServiceFeeOptions = async () => {
      try {
        const options = await serviceFeeManager.getServiceFeeSelectOptions(
          onUnauthorized
        );

        if (options && options.length > 0) {
          const formattedOptions = options.map(opt => ({
            value: opt.value !== undefined ? String(opt.value) : String(opt.id),
            label: opt.label || opt.title || opt.name || `Service Fee ${opt.id}`,
          }));

          setServiceFeeOptions(formattedOptions);

          // Auto-select first valid option if none selected (skip placeholder options with value "0" or "")
          if (!serviceFeeId || serviceFeeId === "" || serviceFeeId === "0" || serviceFeeId === 0) {
            const firstValidOption = formattedOptions.find(opt => opt.value && opt.value !== "0" && opt.value !== "");
            if (firstValidOption) {
              setServiceFeeId(firstValidOption.value);

              if (firstValidOption.label && firstValidOption.label.toLowerCase() === "other") {
                setIsServiceFeeOther(true);
              }
            }
          }
        }
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Error fetching service fee options:", error);
        }
      }
    };

    if (serviceFeeOptions.length === 0) {
      fetchServiceFeeOptions();
    }
  }, [serviceFeeId, serviceFeeOptions.length]);

  const loadSpeakerState = useCallback(() => {
    try {
      const existing = sessionStorage.getItem(
        "FLASHPOINTTRAINING_SPEAKER_CREATION_STATE",
      );
      if (existing) {
        const speakerState = JSON.parse(existing);

        if (speakerState.level) setLevel(speakerState.level);
        if (speakerState.availability) setAvailability(speakerState.availability);

        setSkillSets(speakerState.skillSets || []);
        setInsuranceRequirements(speakerState.insuranceRequirements || []);
        setHourlySalaryDesired(speakerState.hourlySalaryDesired || "");
        setCommercialInsuranceExpiryDate(speakerState.commercialInsuranceExpiryDate || "");
        setPoliceCheck(speakerState.policeCheck || "");
        setTaxId(speakerState.taxId || "");
        setServiceFeeId(speakerState.serviceFeeId || "");
        setIsServiceFeeOther(speakerState.isServiceFeeOther || false);
        setServiceFeeOther(speakerState.serviceFeeOther || "");
        setPreferredLanguage(speakerState.preferredLanguage || "English");
        setPassword(speakerState.password || "");
        setPasswordRepeated(speakerState.passwordRepeated || "");
      } else {
        navigate("/admin/speakers/add/step-1-search");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error loading speaker state:", error);
      }
      navigate("/admin/speakers/add/step-1-search");
    }
  }, [navigate]);

  const handleAvailabilityChange = useCallback((day, period) => {
    setAvailability((prev) => ({
      ...prev,
      [day]: {
        ...prev[day],
        [period]: !prev[day][period],
      },
    }));

    setErrors((prevErrors) => {
      if (prevErrors.availability) {
        const { availability, ...newErrors } = prevErrors;
        return newErrors;
      }
      return prevErrors;
    });
  }, []);

  const hasAvailabilitySelected = useCallback(() => {
    return Object.values(availability).some((day) => day.am || day.pm);
  }, [availability]);

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

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

    let newErrors = {};
    let hasErrors = false;

    if (!level) {
      newErrors.level = "Speaker level is required";
      hasErrors = true;
    }

    if (!hasAvailabilitySelected()) {
      newErrors.availability = "At least one availability time slot must be selected";
      hasErrors = true;
    }

    if (!skillSets || skillSets.length === 0) {
      newErrors.skillSets = "At least one skill set is required";
      hasErrors = true;
    }

    // Insurance requirement is now optional - no validation needed
    if (!hourlySalaryDesired || String(hourlySalaryDesired).trim() === "") {
      newErrors.hourlySalaryDesired = "Hourly rate is required";
      hasErrors = true;
    } else if (parseFloat(hourlySalaryDesired) < 0) {
      newErrors.hourlySalaryDesired = "Hourly rate cannot be negative";
      hasErrors = true;
    }
    if (!policeCheck.trim()) {
      newErrors.policeCheck = "Police check date is required";
      hasErrors = true;
    }
    // Commercial insurance expiry date is now optional
    // Check if serviceFeeId is a valid value (not empty, not "0", not 0)
    if (!serviceFeeId || serviceFeeId === "" || serviceFeeId === "0" || serviceFeeId === 0) {
      newErrors.serviceFeeId = "Service fee is required";
      hasErrors = true;
    }
    if (isServiceFeeOther && !serviceFeeOther.trim()) {
      newErrors.serviceFeeOther = "Please specify the custom service fee";
      hasErrors = true;
    }
    if (!preferredLanguage.trim()) {
      newErrors.preferredLanguage = "Preferred language is required";
      hasErrors = true;
    }

    if (password || passwordRepeated) {
      if (password !== passwordRepeated) {
        newErrors.password = "Passwords do not match";
        newErrors.passwordRepeated = "Passwords do not match";
        hasErrors = true;
      }
      if (password && password.length < 8) {
        newErrors.password = "Password must be at least 8 characters";
        hasErrors = true;
      }
    }

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

    const existingState = getExistingState();
    // Remove fields that are no longer used
    delete existingState.duesDate;
    delete existingState.autoInsuranceExpiryDate;
    delete existingState.wsibNumber;
    delete existingState.wsibInsuranceDate;
    delete existingState.driversLicenseClass;
    delete existingState.vehicleTypes;
    delete existingState.emergencyContactName;
    delete existingState.emergencyContactRelationship;
    delete existingState.emergencyContactTelephone;
    delete existingState.emergencyContactAlternativeTelephone;
    delete existingState.description;
    delete existingState.limitSpecial;
    delete existingState.selectedSkillSets; // Old format

    const speakerState = {
      ...existingState,
      level,
      availability,
      skillSets,
      insuranceRequirements,
      hourlySalaryDesired: hourlySalaryDesired ? parseInt(hourlySalaryDesired) : 0,
      commercialInsuranceExpiryDate,
      policeCheck,
      taxId,
      serviceFeeId,
      isServiceFeeOther,
      serviceFeeOther,
      preferredLanguage,
      password,
      passwordRepeated,
    };

    try {
      sessionStorage.setItem(
        "FLASHPOINTTRAINING_SPEAKER_CREATION_STATE",
        JSON.stringify(speakerState),
      );
      navigate("/admin/speakers/add/step-6");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error saving speaker state:", error);
      }
      setErrors({ general: "Failed to save data. Please try again." });
    }
  };

  const handleServiceFeeChange = useCallback((value) => {
    setServiceFeeId(value);

    // Clear error when a valid value is selected
    if (value && value !== "" && value !== "0" && value !== 0) {
      setErrors((prevErrors) => {
        if (prevErrors.serviceFeeId) {
          const { serviceFeeId: _, ...newErrors } = prevErrors;
          return newErrors;
        }
        return prevErrors;
      });
    }

    // Check if "Other" was selected
    const selectedOption = serviceFeeOptions.find(opt => String(opt.value) === String(value));
    const isOther = selectedOption && selectedOption.label && selectedOption.label.toLowerCase() === "other";
    setIsServiceFeeOther(isOther);

    if (!isOther) {
      setServiceFeeOther("");
    }
  }, [serviceFeeOptions]);

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

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={5}
        title="Add New Speaker"
        subtitle="Configure account settings and preferences for the new speaker"
        icon={ChatBubbleBottomCenterIcon}
      >
        <form onSubmit={onSubmitClick}>
          {errors.general && (
            <Alert
              type="error"
              message={errors.general}
              onClose={() => setErrors({})}
              className="mb-6"
            />
          )}

          {/* Level Section */}
          <FormCard
            title="Level"
            icon={ChartBarIcon}
            description="Select the speaker's level classification"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={1}>
                <Select
                  label="Speaker Level"
                  name="level"
                  value={level}
                  onChange={(value) => {
                    setLevel(value);
                    if (errors.level) {
                      setErrors({ ...errors, level: null });
                    }
                  }}
                  options={LEVEL_OPTIONS}
                  placeholder=""
                  required
                  error={errors.level}
                  helperText="Level 1 speakers are unpaid volunteers, while Level 2 speakers receive compensation for their services."
                />
              </FormRow>
            </FormSection>
          </FormCard>

          {/* Availability Section */}
          <FormCard
            title="Availability"
            icon={ClockIcon}
            description="Select the time slots when the speaker is available"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-border">
                  <thead className="bg-muted">
                    <tr>
                      <th className="px-6 py-4 text-left text-base font-medium text-secondary uppercase">Day</th>
                      <th className="px-6 py-4 text-center text-base font-medium text-secondary uppercase">AM</th>
                      <th className="px-6 py-4 text-center text-base font-medium text-secondary uppercase">PM</th>
                    </tr>
                  </thead>
                  <tbody className="bg-card divide-y divide-border">
                    {DAYS_OF_WEEK.map((day) => (
                      <tr key={day.key} className="hover:bg-muted/50 transition-colors">
                        <td className="px-6 py-4 whitespace-nowrap text-base font-medium text-primary">
                          {day.label}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-center">
                          <input
                            id={`availability-${day.key}-am`}
                            name={`availability-${day.key}-am`}
                            type="checkbox"
                            checked={availability[day.key].am}
                            onChange={() => handleAvailabilityChange(day.key, "am")}
                            className="h-5 w-5 text-accent focus:ring-accent border-border rounded cursor-pointer"
                          />
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-center">
                          <input
                            id={`availability-${day.key}-pm`}
                            name={`availability-${day.key}-pm`}
                            type="checkbox"
                            checked={availability[day.key].pm}
                            onChange={() => handleAvailabilityChange(day.key, "pm")}
                            className="h-5 w-5 text-accent focus:ring-accent border-border rounded cursor-pointer"
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {errors.availability && (
                <p className="mt-2 text-sm text-red-600">{errors.availability}</p>
              )}
              <p className="mt-3 text-base opacity-60">
                <span className="font-medium">Note:</span> At least one time slot must be selected.
              </p>
            </FormSection>
          </FormCard>

          {/* Skill Sets Section */}
          <FormCard
            title="Skill Sets"
            icon={AcademicCapIcon}
            description="Select all skill sets that apply to this speaker"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              {/* Honeypot for Chrome autofill - prevents autofill in skill sets field */}
              <input
                id="organization_honeypot"
                name="organization_honeypot"
                type="text"
                autoComplete="organization"
                tabIndex={-1}
                aria-label="Organization honeypot - do not fill"
                style={{
                  position: 'absolute',
                  left: '-9999px',
                  width: '1px',
                  height: '1px',
                  opacity: 0,
                  pointerEvents: 'none'
                }}
              />
              <SkillSetsMultiSelect
                value={skillSets}
                onChange={(value) => {
                  setSkillSets(value);
                  if (errors.skillSets && value && value.length > 0) {
                    const { skillSets: _, ...newErrors } = errors;
                    setErrors(newErrors);
                  }
                }}
                error={errors.skillSets}
                required={true}
                helperText="Choose the skills and expertise areas"
                onUnauthorized={onUnauthorized}
              />
            </FormSection>
          </FormCard>

          {/* Insurance Requirements Section */}
          <FormCard
            title="Insurance Requirements"
            icon={ShieldCheckIcon}
            description="Select insurance requirement for this speaker"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={1}>
                <Select
                  label="Insurance Requirement (Optional)"
                  name="insuranceRequirement"
                  value={insuranceRequirements[0] || ""}
                  onChange={(value) => setInsuranceRequirements([value])}
                  options={insuranceRequirementOptions}
                  placeholder="Select insurance requirement"
                  required={false}
                  error={errors.insuranceRequirements}
                  helperText="Choose applicable insurance coverage type if required"
                />
              </FormRow>
            </FormSection>
          </FormCard>

          {/* Financial Information */}
          <FormCard
            title="Financial Information"
            icon={CurrencyDollarIcon}
            description="Configure rates, fees, and financial details"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={2}>
                <Input
                  label="Hourly Rate"
                  name="hourlySalaryDesired"
                  type="number"
                  value={hourlySalaryDesired}
                  onChange={(value) => setHourlySalaryDesired(value)}
                  placeholder="$ / hr"
                  icon={CurrencyDollarIcon}
                  required
                  error={errors.hourlySalaryDesired}
                />
                <Select
                  label="Service Fee"
                  name="serviceFeeId"
                  value={serviceFeeId}
                  onChange={(value) => handleServiceFeeChange(value)}
                  options={serviceFeeOptions}
                  placeholder=""
                  required
                  error={errors.serviceFeeId}
                  helperText="Select the applicable service fee"
                />
              </FormRow>

              {isServiceFeeOther && (
                <FormRow columns={1}>
                  <Input
                    label="Specify Other Service Fee"
                    name="serviceFeeOther"
                    value={serviceFeeOther}
                    onChange={(value) => setServiceFeeOther(value)}
                    placeholder="Enter custom service fee details"
                    required
                    error={errors.serviceFeeOther}
                  />
                </FormRow>
              )}

              {/* Honeypot for Chrome autofill - prevents email autofill in HST field */}
              <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}>
                <Input
                  label="HST # (Optional)"
                  name="taxId"
                  value={taxId}
                  onChange={(value) => setTaxId(value)}
                  placeholder="Enter HST number"
                />
              </FormRow>
            </FormSection>
          </FormCard>

          {/* Important Dates */}
          <FormCard
            title="Important Dates"
            icon={CalendarDaysIcon}
            description="Track expiry dates and renewal schedules"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={2}>
                <Input
                  label="Police Check Expiry"
                  name="policeCheck"
                  type="date"
                  value={policeCheck}
                  onChange={(value) => setPoliceCheck(value)}
                  required
                  error={errors.policeCheck}
                />
                <Input
                  label="Commercial Insurance Expiry (Optional)"
                  name="commercialInsuranceExpiryDate"
                  type="date"
                  value={commercialInsuranceExpiryDate}
                  onChange={(value) => setCommercialInsuranceExpiryDate(value)}
                  required={false}
                  error={errors.commercialInsuranceExpiryDate}
                />
              </FormRow>
            </FormSection>
          </FormCard>

          {/* Login Credentials */}
          <FormCard
            title="Login Credentials"
            icon={LockClosedIcon}
            description="Set up authentication for the speaker's account"
            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="Enter password (min 8 characters)"
                  icon={LockClosedIcon}
                  autoComplete="new-password"
                  error={errors.password}
                  helperText="Leave blank to auto-generate a password"
                />
                <Input
                  label="Confirm Password (Optional)"
                  name="passwordRepeated"
                  type="password"
                  value={passwordRepeated}
                  onChange={(value) => setPasswordRepeated(value)}
                  placeholder="Repeat password"
                  icon={LockClosedIcon}
                  autoComplete="new-password"
                  error={errors.passwordRepeated}
                  helperText="Must match the password above if entered"
                />
              </FormRow>
            </FormSection>
          </FormCard>

          {/* System Settings */}
          <FormCard
            title="System Settings"
            icon={ComputerDesktopIcon}
            description="Language preferences and system configuration"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={1}>
                <Select
                  label="Preferred Language"
                  name="preferredLanguage"
                  value={preferredLanguage}
                  onChange={(value) => setPreferredLanguage(value)}
                  options={LANGUAGE_OPTIONS}
                  icon={LanguageIcon}
                  placeholder=""
                  required
                  error={errors.preferredLanguage}
                />
              </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 AdminSpeakerAddStep5Page;
