import React, { useEffect, useRef, useState } from "react";
import { ClipLoader } from "react-spinners";
import { toast } from "react-toastify";
import {
  getAllEducationLevels,
  getAllStates,
  getJurorById,
  updateJuror,
} from "@/services/jurorsService";
import CustomSelect from "@/components/common/CustomSelect";
import { getMaritalStatus } from "@/services/caseService";
import { useParams, useRouter } from "next/navigation";
import Layout from "@/Layout";
import Link from "next/link";

// const STEPS = [
//   "Identification",
//   "Contact",
//   "Demographics",
//   "Family Background",
//   "Employment",
//   "Prior Jury Experience",
//   "Prior Trial Experience",
//   "Internal Use Fields",
// ];

const STEPS = [
  "Identification",
  "Contact",
  "Demographics",
  "Family",
  "Employment",
  "Prior Jury",
  "Prior Trial",
  "Internal Use ",
];


const draftKey = (id) => `juror_JR_${id}`;

const saveDraft = (id, data) => {
  try {
    const { photo, ...rest } = data;
    localStorage.setItem(draftKey(id), JSON.stringify(rest));
  } catch (e) { }
};

const loadDraft = (id) => {
  try {
    const raw = localStorage.getItem(draftKey(id));
    return raw ? JSON.parse(raw) : null;
  } catch (e) {
    return null;
  }
};

const clearDraft = (id) => {
  try {
    localStorage.removeItem(draftKey(id));
  } catch (e) { }
};

export default function EditJurorNew() {
  const [loading, setLoading] = useState(false);
  const [currentStep, setCurrentStep] = useState(1);
  const [formData, setFormData] = useState({
    addresses: [{}],
  });
  const skipSaveRef = useRef(true);
  const hasLoadedRef = useRef(false);
  const [stateOptions, setStateOptions] = useState([]);
  const [educationLevelOptions, setEducationLevelOptions] = useState([]);
  const [maritalStatusOptions, setMaritalStatusOptions] = useState([]);
  const params = useParams();
  const router = useRouter();
  const [refetchTick, setRefetchTick] = useState(0);
  

  const jurorId = params.id;
  const caseId = params.caseId;

  useEffect(() => {
    if (jurorId) {
      setLoading(true);

      getJurorById(jurorId)
        .then((res) => {
          const data = res.data;
          const notes = data.notes || [];

          const getNote = (tab) => {
            const item = notes.find((n) => n.tab === tab);
            return item ? item.note : "";
          };

          const apiFormData = {
            juryNumber: data.juror_number || "",
            caseNumber: data.case || "",
            firstName: data.first_name || "",
            middleName: data.middle_name || "",
            lastName: data.last_name || "",
            photo: data.photo || null,

            addresses: [
              {
                primaryEmail: data.email || "",
                primaryPhone: formatUSPhone(data.primary_phone || ""),
                mobilePhone: formatUSPhone(data.cell_phone || ""),
                streetAddress: data.street_address || "",
                city: data.city || "",
                state: data.state || "",
                county: data.county || "",
                zipCode: data.zipcode || "",
                houseOwnership: data.house_ownership || "",
              },
            ],

            dob: data.date_of_birth || "",
            age: data.age || "",
            gender: data.gender || "",
            race: data.race || "",
            birthCountry: data.birth_country || "",

            usCitizen: data.us_citizen ?? false,

            educationLevel: data.education_levels || "",
            maritalStatus: data.marital_status || "",

            spouseFullName: data.spouse_full_name || "",
            spouseEmploymentStatus: data.spouse_employment_status || "",
            spouseOccupation: data.spouse_occupation || "",
            spouseEmployerName: data.spouse_employer_name || "",

            employerBusinessName: data.employer || "",
            employmentStatus: data.employment_status || "",
            occupation: data.occupation || "",
            jobTitle: data.job_title || "",

            civilJury: data.civil_jury || false,
            criminalJury: data.criminal_jury || false,
            grandJury: data.grand_jury || false,
            verdictReached: data.verdict_reached || false,

            partyToCivilSuit: data.party_to_civil_suit || false,
            accusedCriminalTrial: data.accused_in_criminal_trial || false,
            complainantCriminalTrial:
              data.complainant_in_criminal_trial || false,
            witnessCriminalTrial: data.witness_in_criminal_trial || false,
            felonyProbationHistory: data.felony_probation_history || false,
            misdemeanorTheftConviction:
              data.misdemeanor_theft_conviction || false,

            religion: data.religion || "",
            politicalAffiliation: data.political_party || "",
            votingRecord: data.voting_record || "",
            relativeLawEnforcement: data.relative_in_law_enforcement || "",
            analystNotes: data.analyst_notes || "",
            notes: data.notes || "",
            idiJson: data.id_json_file_name || "",
            status: data.status || "unassigned",

            identificationAdditionalNote: getNote("identification_additional_note"),
            contactInformationAdditionalNote: getNote("contact_information_additional_note"),
            demographicsAdditionalNote: getNote("demographics_additional_note"),
            familyBackgroundAdditionalNote: getNote("family_background_additional_note"),
            employmentDetailsAdditionalNote: getNote("employment_details_additional_note"),
            priorJuryExperienceAdditionalNote: getNote("prior_jury_experience_additional_note"),
            priorTrialExperienceAdditionalNote: getNote("prior_trial_experience_additional_note"),
            internalUseFieldsAdditionalNote: getNote("internal_use_fields_additional_note"),
          }
          // setFormData({
          //   juryNumber: data.juror_number || "",
          //   caseNumber: data.case || "",
          //   firstName: data.first_name || "",
          //   middleName: data.middle_name || "",
          //   lastName: data.last_name || "",
          //   photo: data.photo || null,

          //   addresses: [
          //     {
          //       primaryEmail: data.email || "",
          //       primaryPhone: formatUSPhone(data.primary_phone || ""),
          //       mobilePhone: formatUSPhone(data.cell_phone || ""),
          //       streetAddress: data.street_address || "",
          //       city: data.city || "",
          //       state: data.state || "",
          //       county: data.county || "",
          //       zipCode: data.zipcode || "",
          //       houseOwnership: data.house_ownership || "",
          //     },
          //   ],

          //   dob: data.date_of_birth || "",
          //   age: data.age || "",
          //   gender: data.gender || "",
          //   race: data.race || "",
          //   birthCountry: data.birth_country || "",

          //   usCitizen: data.us_citizen ?? false,

          //   educationLevel: data.education_levels || "",
          //   maritalStatus: data.marital_status || "",

          //   spouseFullName: data.spouse_full_name || "",
          //   spouseEmploymentStatus: data.spouse_employment_status || "",
          //   spouseOccupation: data.spouse_occupation || "",
          //   spouseEmployerName: data.spouse_employer_name || "",

          //   employerBusinessName: data.employer || "",
          //   employmentStatus: data.employment_status || "",
          //   occupation: data.occupation || "",
          //   jobTitle: data.job_title || "",

          //   civilJury: data.civil_jury || false,
          //   criminalJury: data.criminal_jury || false,
          //   grandJury: data.grand_jury || false,
          //   verdictReached: data.verdict_reached || false,

          //   partyToCivilSuit: data.party_to_civil_suit || false,
          //   accusedCriminalTrial: data.accused_in_criminal_trial || false,
          //   complainantCriminalTrial:
          //     data.complainant_in_criminal_trial || false,
          //   witnessCriminalTrial: data.witness_in_criminal_trial || false,
          //   felonyProbationHistory: data.felony_probation_history || false,
          //   misdemeanorTheftConviction:
          //     data.misdemeanor_theft_conviction || false,

          //   religion: data.religion || "",
          //   politicalAffiliation: data.political_party || "",
          //   votingRecord: data.voting_record || "",
          //   relativeLawEnforcement: data.relative_in_law_enforcement || "",
          //   analystNotes: data.analyst_notes || "",
          //   notes: data.notes || "",
          //   idiJson: data.id_json_file_name || "",
          //   status: data.status || "unassigned",

          //   identificationAdditionalNote: getNote("identification_additional_note"),
          //   contactInformationAdditionalNote: getNote("contact_information_additional_note"),
          //   demographicsAdditionalNote: getNote("demographics_additional_note"),
          //   familyBackgroundAdditionalNote: getNote("family_background_additional_note"),
          //   employmentDetailsAdditionalNote: getNote("employment_details_additional_note"),
          //   priorJuryExperienceAdditionalNote: getNote("prior_jury_experience_additional_note"),
          //   priorTrialExperienceAdditionalNote: getNote("prior_trial_experience_additional_note"),
          //   internalUseFieldsAdditionalNote: getNote("internal_use_fields_additional_note"),
          // });
          // If the user left this juror mid-edit before, restore that draft instead of the clean API data
          const draft = loadDraft(jurorId);
          hasLoadedRef.current = false; // block saving until this juror's real data is in
          skipSaveRef.current = true; // this setFormData is a "load", not a user edit
          hasLoadedRef.current = true;
          setFormData(
            draft
              ? { ...draft, photo: apiFormData.photo } // photo always from API, never from draft
              : apiFormData
          );

        })
        .catch(() => toast.error("Failed to load juror information"))
        .finally(() => setLoading(false));
    }
  }, [jurorId, refetchTick]);
  useEffect(() => {
    if (!jurorId) return;
    if (!hasLoadedRef.current) {
      return;
    }
    if (skipSaveRef.current) {
      skipSaveRef.current = false;
      return;
    }
    saveDraft(jurorId, formData);
  }, [formData, jurorId]);

  useEffect(() => {
    fetchStates();
    fetchEducationLevels();
    fetchMaritalStatus();
  }, []);

  useEffect(() => {
    setCurrentStep(1);
  }, []);

  const formatUSPhone = (value) => {
    const digits = value.replace(/\D/g, "").slice(0, 10);

    if (digits.length <= 3) return digits;

    if (digits.length <= 6) {
      return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
    }

    return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6, 10)}`;
  };

  const fetchStates = async () => {
    try {
      const response = await getAllStates();
      const options = (response?.data?.data || []).map((item) => ({
        label: item.short_name,
        value: item.id,
      }));
      setStateOptions(options);
    } catch (error) { }
  };

  const fetchEducationLevels = async () => {
    try {
      const response = await getAllEducationLevels();
      const options = (response?.data?.data || []).map((item) => ({
        label: item.name,
        value: item.id,
      }));
      setEducationLevelOptions(options);
    } catch (error) { }
  };

  const fetchMaritalStatus = async () => {
    try {
      const response = await getMaritalStatus();
      const options = (response?.data?.data || []).map((item) => ({
        label: item.name.charAt(0).toUpperCase() + item.name.slice(1),
        value: item.name,
      }));
      setMaritalStatusOptions(options);
    } catch (error) { }
  };

  const handleInput = (field, value) => {
    let updatedValue = value;

    if (field === "dob") {
      updatedValue = value.replace(/[^0-9Xx-]/g, "");

      // If user enters only a year, convert to XX-XX-YYYY
      if (/^\d{4}$/.test(updatedValue)) {
        updatedValue = `XX-XX-${updatedValue}`;
      }
    }

    setFormData((prev) => ({
      ...prev,
      [field]: updatedValue,
    }));
  };

  const handleAddressInput = (index, key, value) => {
    setFormData((prev) => {
      const updated = [...(prev.addresses || [])];

      let updatedValue = value;

      if (key === "primaryPhone" || key === "mobilePhone") {
        updatedValue = formatUSPhone(value);
      }

      updated[index] = {
        ...updated[index],
        [key]: updatedValue,
      };

      return { ...prev, addresses: updated };
    });
  };

  const stepValidation = {
    1: [
      { field: formData.juryNumber, message: "Jury Number is required" },
      { field: formData.firstName, message: "First Name is required" },
      { field: formData.lastName, message: "Last Name is required" },
    ],

    3: [
      { field: formData.gender, message: "Gender is required" },
    ],
  };

  // const handleNext = () => setCurrentStep((p) => p + 1);
  const handleNext = () => {
    const validations = stepValidation[currentStep] || [];

    const invalidField = validations.find(
      (item) => !String(item.field || "").trim(),
    );

    if (invalidField) {
      toast.error(invalidField.message);
      return;
    }

    if (currentStep < 8) {
      setCurrentStep((prev) => prev + 1);
    }
  };
  const handleBack = () => setCurrentStep((p) => p - 1);

  const handleSave = () => {
    setLoading(true);

    const payload = new FormData();

    const notes = [];

    if (formData.identificationAdditionalNote?.trim()) {
      notes.push({
        tab: "identification_additional_note",
        note: formData.identificationAdditionalNote.trim(),
      });
    }

    if (formData.contactInformationAdditionalNote?.trim()) {
      notes.push({
        tab: "contact_information_additional_note",
        note: formData.contactInformationAdditionalNote.trim(),
      });
    }

    if (formData.demographicsAdditionalNote?.trim()) {
      notes.push({
        tab: "demographics_additional_note",
        note: formData.demographicsAdditionalNote.trim(),
      });
    }

    if (formData.familyBackgroundAdditionalNote?.trim()) {
      notes.push({
        tab: "family_background_additional_note",
        note: formData.familyBackgroundAdditionalNote.trim(),
      });
    }

    if (formData.employmentDetailsAdditionalNote?.trim()) {
      notes.push({
        tab: "employment_details_additional_note",
        note: formData.employmentDetailsAdditionalNote.trim(),
      });
    }

    if (formData.priorJuryExperienceAdditionalNote?.trim()) {
      notes.push({
        tab: "prior_jury_experience_additional_note",
        note: formData.priorJuryExperienceAdditionalNote.trim(),
      });
    }

    if (formData.priorTrialExperienceAdditionalNote?.trim()) {
      notes.push({
        tab: "prior_trial_experience_additional_note",
        note: formData.priorTrialExperienceAdditionalNote.trim(),
      });
    }

    if (formData.internalUseFieldsAdditionalNote?.trim()) {
      notes.push({
        tab: "internal_use_fields_additional_note",
        note: formData.internalUseFieldsAdditionalNote.trim(),
      });
    }

    payload.append("juror_number", formData.juryNumber || "");
    payload.append("case", formData.caseNumber || "");
    payload.append("first_name", formData.firstName || "");
    payload.append("middle_name", formData.middleName || "");
    payload.append("last_name", formData.lastName || "");

    if (formData.photo instanceof File) {
      payload.append("photo", formData.photo);
    }

    const addr = formData.addresses?.[0] || {};

    payload.append("email", addr.primaryEmail || "");
    payload.append(
      "primary_phone",
      (addr.primaryPhone || "").replace(/\D/g, ""),
    );
    payload.append("cell_phone", (addr.mobilePhone || "").replace(/\D/g, ""));
    payload.append("street_address", addr.streetAddress || "");
    payload.append("city", addr.city || "");
    payload.append("state", addr.state || "");
    payload.append("county", addr.county || "");
    payload.append("zipcode", addr.zipCode || "");
    payload.append("house_ownership", addr.houseOwnership || "");

    payload.append("date_of_birth", formData.dob || "");
    payload.append("age", formData.age || "");
    payload.append("gender", formData.gender || "");
    payload.append("race", formData.race || "");
    payload.append("birth_country", formData.birthCountry || "");
    payload.append("us_citizen", formData.usCitizen);
    payload.append("education_levels", formData.educationLevel || "");

    payload.append("spouse_full_name", formData.spouseFullName || "");
    payload.append(
      "spouse_employment_status",
      formData.spouseEmploymentStatus || "",
    );
    payload.append("spouse_occupation", formData.spouseOccupation || "");
    payload.append("spouse_employer_name", formData.spouseEmployerName || "");

    payload.append("employer", formData.employerBusinessName || "");
    payload.append("employment_status", formData.employmentStatus || "");
    payload.append("occupation", formData.occupation || "");
    payload.append("job_title", formData.jobTitle || "");

    payload.append("civil_jury", formData.civilJury);
    payload.append("criminal_jury", formData.criminalJury);
    payload.append("grand_jury", formData.grandJury);
    payload.append("verdict_reached", formData.verdictReached);

    payload.append("party_to_civil_suit", formData.partyToCivilSuit);
    payload.append("accused_in_criminal_trial", formData.accusedCriminalTrial);
    payload.append(
      "complainant_in_criminal_trial",
      formData.complainantCriminalTrial,
    );
    payload.append("witness_in_criminal_trial", formData.witnessCriminalTrial);
    payload.append("felony_probation_history", formData.felonyProbationHistory);
    payload.append(
      "misdemeanor_theft_conviction",
      formData.misdemeanorTheftConviction,
    );

    payload.append("religion", formData.religion || "");
    payload.append("political_party", formData.politicalAffiliation || "");
    payload.append("voting_record", formData.votingRecord || "");
    payload.append(
      "relative_in_law_enforcement",
      formData.relativeLawEnforcement || "",
    );
    payload.append("analyst_notes", formData.analystNotes || "");
    // payload.append("notes", formData.notes || "");
    payload.append("notes", JSON.stringify(notes));
    payload.append("id_json_file_name", formData.idiJson || "");
    payload.append("status", formData.status || "");
    payload.append("identification_additional_note", formData.identificationAdditionalNote || "");
    payload.append("contact_information_additional_note", formData.contactInformationAdditionalNote || "");
    payload.append("demographics_additional_note", formData.demographicsAdditionalNote || "");
    payload.append("family_background_additional_note", formData.familyBackgroundAdditionalNote || "");
    payload.append("employment_details_additional_note", formData.employmentDetailsAdditionalNote || "");
    payload.append("prior_jury_experience_additional_note", formData.priorJuryExperienceAdditionalNote || "");
    payload.append("prior_trial_experience_additional_note", formData.priorTrialExperienceAdditionalNote || "");
    payload.append("internal_use_fields_additional_note", formData.internalUseFieldsAdditionalNote || "");

    updateJuror(jurorId, payload)
      .then(() => {
        toast.success("Juror updated successfully");
        clearDraft(jurorId);
        setRefetchTick((t) => t + 1);
        // router.refresh();

        if (currentStep < STEPS.length) {
          setCurrentStep((prev) => prev + 1);
        } else {
          router.back();
          router.refresh();
        }
      })
      .catch((error) => {
        const apiError = error?.response?.data;

        if (apiError) {
          const firstError = Object.values(apiError)?.[0];

          if (Array.isArray(firstError) && firstError.length > 0) {
            toast.error(firstError[0]);
            return;
          }

          if (typeof firstError === "string") {
            toast.error(firstError);
            return;
          }
        }

        toast.error("Failed to update juror");
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const addr = formData?.addresses?.[0] || {};

  const renderStep = () => {
    switch (currentStep) {
      case 1:
        return (
          <div className="row gx-3">
            <div className="col-12">
              <h5 className="mb-3 mb-md-4">Identification</h5>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">
                  Jury Number <span style={{ color: "red" }}>*</span>
                </label>
                <input
                  type="text"
                  value={formData?.juryNumber || ""}
                  onChange={(e) => handleInput("juryNumber", e.target.value)}
                  placeholder="Jury Number"
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">
                  Last Name <span style={{ color: "red" }}>*</span>
                </label>
                <input
                  type="text"
                  value={formData?.lastName || ""}
                  onChange={(e) => handleInput("lastName", e.target.value)}
                  placeholder="Last Name"
                  required
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3" mb-md-4>
              <div className="datafrm m-0">
                <label className="text-start">
                  First Name <span style={{ color: "red" }}>*</span>
                </label>
                <input
                  type="text"
                  value={formData?.firstName || ""}
                  onChange={(e) => handleInput("firstName", e.target.value)}
                  placeholder="First Name"
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Middle Name</label>
                <input
                  type="text"
                  value={formData?.middleName || ""}
                  onChange={(e) => handleInput("middleName", e.target.value)}
                  placeholder="Middle Name"
                />
              </div>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Photo</label>
                <input
                  type="file"
                  className="form-control"
                  accept="image/*"
                  onChange={(e) => handleInput("photo", e.target.files?.[0])}
                />
              </div>
            </div>
            {formData?.photo && !(formData.photo instanceof File) && (
              <div className="col-lg-6 mb-3">
                <img
                  src={formData.photo}
                  alt="photo"
                  style={{
                    width: 60,
                    height: 60,
                    objectFit: "cover",
                    borderRadius: 6,
                  }}
                />
              </div>
            )}
            <div className="col-12 mb-3">
              <div className="datafrm m-0">
                <label className="text-start">Identification Additional Note</label>
                <textarea
                  rows={4}
                  placeholder="Additional Note"
                  value={formData.identificationAdditionalNote}
                  onChange={(e) =>
                    handleInput(
                      "identificationAdditionalNote",
                      e.target.value
                    )
                  }
                />
              </div>
            </div>
          </div>
        );

      case 2:
        return (
          <div className="row gx-3">
            <div className="col-12">
              <h5 className="mb-3 mb-md-4">Contact Information</h5>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Primary Email</label>
                <input
                  type="text"
                  value={addr.primaryEmail || ""}
                  onChange={(e) =>
                    handleAddressInput(0, "primaryEmail", e.target.value)
                  }
                  placeholder="Primary Email"
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Street Address</label>
                <input
                  type="text"
                  value={addr.streetAddress || ""}
                  onChange={(e) =>
                    handleAddressInput(0, "streetAddress", e.target.value)
                  }
                  placeholder="Street Address"
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">City</label>
                <input
                  type="text"
                  value={addr.city || ""}
                  onChange={(e) =>
                    handleAddressInput(0, "city", e.target.value)
                  }
                  placeholder="City"
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm text-start m-0">
                <label className="text-start">State</label>
                <CustomSelect
                  value={addr.state}
                  placeholder="Select State"
                  options={stateOptions}
                  onChange={(e) => {
                    handleAddressInput(0, "state", e.target.value);
                  }}
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">County</label>
                <input
                  type="text"
                  value={addr.county || ""}
                  onChange={(e) =>
                    handleAddressInput(0, "county", e.target.value)
                  }
                  placeholder="County"
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Zip</label>
                <input
                  type="text"
                  value={addr.zipCode || ""}
                  onChange={(e) =>
                    handleAddressInput(0, "zipCode", e.target.value)
                  }
                  placeholder="Zip Code"
                />
              </div>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm text-start m-0">
                <label className="text-start">House Ownership</label>
                <CustomSelect
                  value={addr.houseOwnership}
                  placeholder="House Ownership"
                  options={[
                    { label: "Owned", value: "owned" },
                    { label: "Rented", value: "rent" },
                    { label: "Family", value: "family" },
                  ]}
                  onChange={(e) => {
                    handleAddressInput(0, "houseOwnership", e.target.value);
                  }}
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Primary Phone Number</label>
                <input
                  type="text"
                  value={addr.primaryPhone || ""}
                  onChange={(e) =>
                    handleAddressInput(0, "primaryPhone", e.target.value)
                  }
                  placeholder="Primary Phone"
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Mobile Phone Number</label>
                <input
                  type="text"
                  value={addr.mobilePhone || ""}
                  onChange={(e) =>
                    handleAddressInput(0, "mobilePhone", e.target.value)
                  }
                  placeholder="Mobile Phone"
                />
              </div>
            </div>
            <div className="col-12 mb-3">
              <div className="datafrm m-0">
                <label className="text-start">Contact Additional Note</label>
                <textarea
                  rows={4}
                  value={formData.contactInformationAdditionalNote}
                  onChange={(e) =>
                    handleInput(
                      "contactInformationAdditionalNote",
                      e.target.value
                    )
                  }
                />
              </div>
            </div>

          </div>
        );

      case 3:
        return (
          <div className="row gx-3">
            <div className="col-12">
              <h5 className="mb-3 mb-md-4">Demographics</h5>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm text-start m-0">
                <label className="text-start">
                  Gender <span style={{ color: "red" }}>*</span>
                </label>
                <CustomSelect
                  value={formData.gender}
                  placeholder="Select Gender"
                  options={[
                    { label: "Male", value: "M" },
                    { label: "Female", value: "F" },
                    { label: "Other", value: "O" },
                  ]}
                  onChange={(e) => {
                    handleInput("gender", e.target.value);
                  }}
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Age</label>
                <input
                  type="number"
                  value={formData.age || ""}
                  placeholder="Age"
                  onChange={(e) => handleInput("age", e.target.value)}
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">DOB</label>
                <input
                  type="text"
                  placeholder="MM-DD-YYYY"
                  value={formData.dob || ""}
                  onChange={(e) => handleInput("dob", e.target.value)}
                  onBlur={(e) => {
                    const value = e.target.value.trim();

                    if (/^\d{4}$/.test(value)) {
                      handleInput("dob", `XX-XX-${value}`);
                    }
                  }}
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Race</label>
                <input
                  type="text"
                  value={formData.race || ""}
                  placeholder="Race"
                  onChange={(e) => handleInput("race", e.target.value)}
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Education Level</label>
                <CustomSelect
                  value={formData.educationLevel}
                  placeholder="Select Education Level"
                  options={educationLevelOptions}
                  onChange={(e) => {
                    handleInput("educationLevel", e.target.value);
                  }}
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Religion</label>
                <input
                  type="text"
                  value={formData.religion || ""}
                  placeholder="Religion"
                  onChange={(e) => handleInput("religion", e.target.value)}
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm text-start m-0">
                <label className="text-start">US Citizen</label>
                <CustomSelect
                  value={formData.usCitizen}
                  placeholder="US Citizen"
                  options={[
                    { label: "Yes", value: true },
                    { label: "No", value: false },
                  ]}
                  onChange={(e) => {
                    handleInput("usCitizen", e.target.value);
                  }}
                />
              </div>
            </div>
            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Birth Country</label>
                <input
                  type="text"
                  value={formData.birthCountry || ""}
                  placeholder="Birth Country"
                  onChange={(e) => handleInput("birthCountry", e.target.value)}
                />
              </div>
            </div>
            <div className="col-lg-12 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Political Affiliation</label>
                <input
                  type="text"
                  value={formData.politicalAffiliation || ""}
                  placeholder="Political Affiliation"
                  onChange={(e) =>
                    handleInput("politicalAffiliation", e.target.value)
                  }
                />
              </div>
            </div>
            <div className="col-12 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Voting Record</label>
                <textarea
                  rows="3"
                  value={formData.votingRecord || ""}
                  placeholder="Voting Record"
                  onChange={(e) => handleInput("votingRecord", e.target.value)}
                />
              </div>
            </div>
            <div className="col-12 mb-3">
              <div className="datafrm m-0">
                <label className="text-start">Demographics Additional Note</label>
                <textarea
                  rows={4}
                  value={formData.demographicsAdditionalNote}
                  onChange={(e) =>
                    handleInput(
                      "demographicsAdditionalNote",
                      e.target.value
                    )
                  }
                />
              </div>
            </div>
          </div>
        );

      case 4:
        return (
          <div className="row gx-3">
            <div className="col-12">
              <h5 className="mb-3 mb-md-4">Family Background</h5>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Marital Status</label>
                <CustomSelect
                  value={formData.maritalStatus}
                  placeholder="Select Marital Status"
                  options={maritalStatusOptions}
                  onChange={(e) => {
                    handleInput("maritalStatus", e.target.value);
                  }}
                />
              </div>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Spouse Full Name</label>
                <input
                  type="text"
                  value={formData.spouseFullName || ""}
                  placeholder="Spouse Full Name"
                  onChange={(e) =>
                    handleInput("spouseFullName", e.target.value)
                  }
                />
              </div>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm text-start m-0">
                <label className="text-start">Spouse Employment Status</label>
                <CustomSelect
                  value={formData.spouseEmploymentStatus}
                  placeholder="Spouse Employment Status"
                  options={[
                    {
                      label: "Unknown",
                      value: "unknown",
                    },
                    {
                      label: "Retired",
                      value: "retired",
                    },
                    {
                      label: "Self Employed",
                      value: "selfemployed",
                    },
                    {
                      label: "Employed",
                      value: "employed",
                    },
                    {
                      label: "Unemployed",
                      value: "unemployed",
                    },
                    {
                      label: "Other",
                      value: "other",
                    },
                  ]}
                  onChange={(e) => {
                    handleInput("spouseEmploymentStatus", e.target.value);
                  }}
                />
              </div>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Spouse Occupation</label>
                <input
                  type="text"
                  value={formData.spouseOccupation || ""}
                  placeholder="Spouse Occupation"
                  onChange={(e) =>
                    handleInput("spouseOccupation", e.target.value)
                  }
                />
              </div>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Spouse Employer Name</label>
                <input
                  type="text"
                  value={formData.spouseEmployerName || ""}
                  placeholder="Spouse Employer Name"
                  onChange={(e) =>
                    handleInput("spouseEmployerName", e.target.value)
                  }
                />
              </div>
            </div>

            <div className="col-12 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">
                  Relative in Law Enforcement?
                </label>
                <textarea
                  rows="4"
                  value={formData.relativeLawEnforcement || ""}
                  placeholder="Relative in Law Enforcement"
                  onChange={(e) =>
                    handleInput("relativeLawEnforcement", e.target.value)
                  }
                />
              </div>
            </div>

            <div className="col-12 mb-3">
              <div className="datafrm m-0">
                <label className="text-start">Family Background Additional Note</label>
                <textarea
                  rows={4}
                  value={formData.familyBackgroundAdditionalNote}
                  onChange={(e) =>
                    handleInput(
                      "familyBackgroundAdditionalNote",
                      e.target.value
                    )
                  }
                />
              </div>
            </div>
          </div>
        );

      case 5:
        return (
          <div className="row gx-3">
            <div className="col-12">
              <h5 className="mb-3 mb-md-4">Employment Details</h5>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm text-start m-0">
                <label className="text-start">Employment Status</label>
                <CustomSelect
                  value={formData.employmentStatus}
                  placeholder="Select Employment Status"
                  options={[
                    { label: "Unknown", value: "unknown" },
                    { label: "Retired", value: "retired" },
                    { label: "Self Employed", value: "selfemployed" },
                    { label: "Employed", value: "employed" },
                    { label: "Unemployed", value: "unemployed" },
                    { label: "Other", value: "other" },
                  ]}
                  onChange={(e) =>
                    handleInput("employmentStatus", e.target.value)
                  }
                />
              </div>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Occupation</label>
                <input
                  type="text"
                  value={formData.occupation || ""}
                  placeholder="Occupation"
                  onChange={(e) => handleInput("occupation", e.target.value)}
                />
              </div>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Job Title</label>
                <input
                  type="text"
                  value={formData.jobTitle || ""}
                  placeholder="Job Title"
                  onChange={(e) => handleInput("jobTitle", e.target.value)}
                />
              </div>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Employer / Business Name</label>
                <input
                  type="text"
                  value={formData.employerBusinessName || ""}
                  placeholder="Employer / Business Name"
                  onChange={(e) =>
                    handleInput("employerBusinessName", e.target.value)
                  }
                />
              </div>
            </div>
            <div className="col-12 mb-3">
              <div className="datafrm m-0">
                <label className="text-start">Employment Details Additional Note</label>
                <textarea
                  rows={4}
                  value={formData.employmentDetailsAdditionalNote}
                  onChange={(e) =>
                    handleInput(
                      "employmentDetailsAdditionalNote",
                      e.target.value
                    )
                  }
                />
              </div>
            </div>
          </div>
        );

      case 6:
        return (
          <div className="row gx-3">
            <div className="col-12">
              <h5 className="mb-3 mb-md-4">Prior Jury Experience</h5>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm text-start m-0">
                <label className="text-start">Civil Jury</label>
                <CustomSelect
                  value={formData.civilJury}
                  placeholder="Select Civil Jury"
                  options={[
                    { label: "Yes", value: true },
                    { label: "No", value: false },
                  ]}
                  onChange={(e) => handleInput("civilJury", e.target.value)}
                />
              </div>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm text-start m-0">
                <label className="text-start">Criminal Jury</label>
                <CustomSelect
                  value={formData.criminalJury}
                  placeholder="Select Criminal Jury"
                  options={[
                    { label: "Yes", value: true },
                    { label: "No", value: false },
                  ]}
                  onChange={(e) => handleInput("criminalJury", e.target.value)}
                />
              </div>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm text-start m-0">
                <label className="text-start">Grand Jury</label>
                <CustomSelect
                  value={formData.grandJury}
                  placeholder="Select Grand Jury"
                  options={[
                    { label: "Yes", value: true },
                    { label: "No", value: false },
                  ]}
                  onChange={(e) => handleInput("grandJury", e.target.value)}
                />
              </div>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm text-start m-0">
                <label className="text-start">Verdict Reached</label>
                <CustomSelect
                  value={formData.verdictReached}
                  placeholder="Select Verdict Reached"
                  options={[
                    { label: "Yes", value: true },
                    { label: "No", value: false },
                    { label: "N/A", value: "NA" },
                  ]}
                  onChange={(e) =>
                    handleInput("verdictReached", e.target.value)
                  }
                />
              </div>
            </div>
            <div className="col-12 mb-3">
              <div className="datafrm m-0">
                <label className="text-start">Prior Jury Experience Additional Note</label>
                <textarea
                  rows={4}
                  value={formData.priorJuryExperienceAdditionalNote}
                  onChange={(e) =>
                    handleInput(
                      "priorJuryExperienceAdditionalNote",
                      e.target.value
                    )
                  }
                />
              </div>
            </div>
          </div>
        );

      case 7:
        return (
          <div className="row gx-3">
            <div className="col-12">
              <h5 className="mb-3 mb-md-4">Prior Trial Experience</h5>
            </div>

            {[
              {
                label: "Party to Civil Suit?",
                name: "partyToCivilSuit",
              },
              {
                label: "Accused in Criminal Trial?",
                name: "accusedCriminalTrial",
              },
              {
                label: "Complainant in Criminal Trial?",
                name: "complainantCriminalTrial",
              },
              {
                label: "Witness in Criminal Trial?",
                name: "witnessCriminalTrial",
              },
              {
                label: "Felony Probation History?",
                name: "felonyProbationHistory",
              },
              {
                label: "Theft Conviction?",
                name: "misdemeanorTheftConviction",
              },
            ].map((item, index) => (
              <div className="col-lg-6 mb-3 mb-md-4" key={index}>
                <div className="datafrm text-start m-0">
                  <label className="text-start">{item.label}</label>
                  <CustomSelect
                    value={formData[item.name]}
                    placeholder={item.label}
                    options={[
                      { label: "Yes", value: true },
                      { label: "No", value: false },
                    ]}
                    onChange={(e) => handleInput(item.name, e.target.value)}
                  />
                </div>
              </div>
            ))}

            <div className="col-12 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Social Information Link</label>
                <input
                  type="text"
                  value={formData.socialInformationLink || ""}
                  placeholder="Social Information Link"
                  onChange={(e) =>
                    handleInput("socialInformationLink", e.target.value)
                  }
                />
              </div>
            </div>

            <div className="col-12 mb-3 mb-md-4">
              <div className="datafrm m-0">
                <label className="text-start">Analyst Notes</label>
                <textarea
                  rows="4"
                  value={formData.analystNotes || ""}
                  placeholder="Analyst Notes"
                  onChange={(e) => handleInput("analystNotes", e.target.value)}
                />
              </div>
            </div>

            <div className="col-12 mb-3">
              <div className="datafrm m-0">
                <label className="text-start">Prior Trial Experience Additional Note</label>
                <textarea
                  rows={4}
                  value={formData.priorTrialExperienceAdditionalNote}
                  onChange={(e) =>
                    handleInput(
                      "priorTrialExperienceAdditionalNote",
                      e.target.value
                    )
                  }
                />
              </div>
            </div>
          </div>
        );

      case 8:
        return (
          <div className="row gx-3">
            <div className="col-12">
              <h5 className="mb-3 mb-md-4">Internal Use Fields</h5>
            </div>

            <div className="col-lg-6 mb-3 mb-md-4">
              <div className="datafrm text-start m-0">
                <label className="text-start">
                  Status <span style={{ color: "red" }}>*</span>
                </label>
                <CustomSelect
                  value={formData.status}
                  placeholder="Select Status"
                  options={[
                    {
                      label: "In Process",
                      value: "in_process",
                    },
                    {
                      label: "Enriched",
                      value: "enriched",
                    },
                    {
                      label: "Complete",
                      value: "complete",
                    },
                    {
                      label: "SELECTED",
                      value: "selected",
                    },
                    {
                      label: "REJECTED",
                      value: "rejected",
                    },
                  ]}
                  onChange={(e) => handleInput("status", e.target.value)}
                />
              </div>
            </div>

            <div className="col-12 mb-3">
              <div className="datafrm m-0">
                <label className="text-start">Internal Use Fields Additional Note</label>
                <textarea
                  rows={4}
                  value={formData.internalUseFieldsAdditionalNote}
                  onChange={(e) =>
                    handleInput(
                      "internalUseFieldsAdditionalNote",
                      e.target.value
                    )
                  }
                />
              </div>
            </div>
          </div>
        );
      default:
        return <div>Step {currentStep}</div>;
    }
  };


  return (
    <Layout title={"Edit Juror"}>
      {/* Breadcrumb */}
      <div className="pagerlink mb-3">
        <ul>
          <li>
            <Link href="/dashboard">Dashboard</Link>
          </li>
          <li>
            <Link href="/juror-management">Juror Management</Link>
          </li>
          <li>Edit Juror</li>
        </ul>
      </div>
      <div className="dshboardwhtepnel">
        {loading ? (
          <div
            style={{
              minHeight: "500px",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <ClipLoader color="#0d6efd" size={35} />
          </div>
        ) : (
          <>
            <div className="d-flex justify-content-between align-items-center mb-4">
              <div>
                <h3 className="mb-1">Edit Juror</h3>
                <p className="text-muted mb-0">
                  Update juror information.
                </p>
              </div>
            </div>

            {/* <div className="tab-header-box">
              {STEPS.map((s, i) => (
                <button key={i} className={`${currentStep === i + 1 ? "active" : ""} tab-btn text-nowrap`} onClick={() => setCurrentStep(i + 1)}>
                  {s}
                </button>
              ))}
            </div> */}

            <div className="step-progress-wrapper mb-4">
              <div className="step-progress">
                {STEPS.map((s, index) => (
                  <div
                    key={index}
                    className={`text-center step-item ${currentStep >= index + 1 ? "active" : ""
                      }`}
                    onClick={() => setCurrentStep(index + 1)}
                  >
                    {s}
                  </div>
                ))}
              </div>
            </div>

            <form className="dshboardcaseform">
              {renderStep()}

              <div className="datafrmbtn mt-4">
                <ul>
                  {currentStep > 1 && (
                    <li>
                      <button
                        type="button"
                        className="canselbtn"
                        onClick={handleBack}
                      >
                        Back
                      </button>
                    </li>
                  )}

                  <li>
                    <button
                      type="button"
                      className="savebtn"
                      onClick={handleSave}
                      disabled={loading}
                    >
                      {loading ? "Saving..." : "Save"}
                    </button>
                  </li>
                </ul>
              </div>
            </form>
          </>
        )}
      </div>
    </Layout>
  );
}
