import dynamic from "next/dynamic";
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";
import useNavigate from "@/hooks/useNavigate";
import RunIdiReportModal from "../RunIdiReportModal";
import { set } from "date-fns";

const RichTextEditor = dynamic(
  () => import("@/components/common/RichTextEditor").then(mod => {
    // console.log("RichTextEditor module loaded:", mod);
    return mod;
  }),
  { ssr: false, loading: () => <p>Loading editor...</p> }
);

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

const encryptData = (data) => {
  try {
    // Convert object to JSON string, then to Base64
    const jsonString = JSON.stringify(data);
    // Use encodeURIComponent to handle special characters
    const encoded = encodeURIComponent(jsonString);
    return btoa(encoded);
  } catch (e) {
    console.error('Encryption error:', e);
    return null;
  }
};

const decryptData = (encryptedData) => {
  try {
    // Decode from Base64, then decode URI component, then parse JSON
    const decoded = atob(encryptedData);
    const decodedString = decodeURIComponent(decoded);
    return JSON.parse(decodedString);
  } catch (e) {
    console.error('Decryption error:', e);
    return null;
  }
};


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

const saveDraft = (id, data) => {
  try {
    const { photo, ...rest } = data;
    const encrypted = encryptData(rest);
    if (encrypted) {
      localStorage.setItem(draftKey(id), encrypted);
    }
  } catch (e) {
    console.error('Error saving draft:', e);
  }
};

const loadDraft = (id) => {
  try {
    const encrypted = localStorage.getItem(draftKey(id));
    if (!encrypted) return null;
    return decryptData(encrypted);
  } catch (e) {
    console.error('Error loading draft:', e);
    return null;
  }
};

const clearDraft = (id) => {
  try {
    localStorage.removeItem(draftKey(id));
  } catch (e) {
    console.error('Error clearing draft:', e);
  }
};


export default function EditJurorNew({ isComprehensive }) {
  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 [showIdiModal, setShowIdiModal] = useState(false);
  const [selectedJurorId, setSelectedJurorId] = useState(null);
  const navigate = useNavigate();
  const [fName, setFname] = useState("");
  const [mName, setMname] = useState("");
  const [lName, setLname] = useState("");

  const jurorId = params.id;
  const caseId = params.caseId;
  const baseRoute = isComprehensive
    ? "/comprehensive-report"
    : "/juror-management";

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

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

          setFname(data.first_name || "");
          setMname(data.middle_name || "");
          setLname(data.last_name || "");

          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 || "",
                houseValue: data.house_value || "",
              },
            ],

            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",
            comprehensiveReportStatus: data.comprehensive_report_status || "",

            additionalNote: data.additional_note || "",
          };

          // Try to load encrypted draft
          const draft = loadDraft(jurorId);
          hasLoadedRef.current = false;
          skipSaveRef.current = true;
          hasLoadedRef.current = true;

          setFormData(
            draft
              ? { ...draft, photo: apiFormData.photo, comprehensiveReportStatus: apiFormData.comprehensiveReportStatus } // photo always from API
              : 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 formatStatus = (text) => {
    if (!text) return "";
    return text
      .split("_")
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
      .join(" ");
  };

  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 (/^\d{4}$/.test(updatedValue)) {
        updatedValue = `XX-XX-${updatedValue}`;
      }
    }

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

    if (errors[field]) {
      setErrors((prev) => {
        const { [field]: _, ...rest } = prev;
        return rest;
      });
    }
  };

  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 [errors, setErrors] = useState({});

  const stepValidation = {
    1: [
      { name: "juryNumber", field: formData.juryNumber, message: "Jury Number is required" },
      { name: "firstName", field: formData.firstName, message: "First Name is required" },
      { name: "lastName", field: formData.lastName, message: "Last Name is required" },
    ],
    3: [
      { name: "gender", field: formData.gender, message: "Gender is required" },
    ],
    8: [
      { name: "status", field: formData.status, message: "Status is required" },
    ],
  };

  const validateStep = (step) => {
    const validations = stepValidation[step] || [];
    const newErrors = {};

    validations.forEach((item) => {
      if (!String(item.field || "").trim()) {
        newErrors[item.name] = item.message;
      }
    });

    setErrors(newErrors);

    const firstError = Object.values(newErrors)[0];
    if (firstError) {
      toast.error(firstError);
    }

    return Object.keys(newErrors).length === 0;
  };

  const handleNext = () => {
    if (!validateStep(currentStep)) return;
    if (currentStep < 8) {
      setCurrentStep((prev) => prev + 1);
    }
  };

  const handleBack = () => {
    setErrors({});
    setCurrentStep((p) => p - 1);
  };

  const handleSave = () => {
    if (!validateStep(currentStep)) return;
    setLoading(true);

    const payload = new FormData();

    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("house_value", addr.houseValue || "");

    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("marital_status", formData.maritalStatus || "");
    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("id_json_file_name", formData.idiJson || "");
    payload.append("status", formData.status || "");
    payload.append("additional_note", formData.additionalNote || "");

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

        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">Notes</label>
                <RichTextEditor
                  value={formData.additionalNote}
                  onChange={(val) => handleInput("additionalNote", val)}
                />
              </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">House Value</label>
                <input
                  type="number"
                  min="0"
                  step="1"
                  value={addr.houseValue || ""}
                  onChange={(e) => {
                    const value = e.target.value;

                    // Allow only positive integers
                    if (value === "" || /^\d+$/.test(value)) {
                      handleAddressInput(0, "houseValue", value);
                    }
                  }}
                  onKeyDown={(e) => {
                    // Prevent minus, plus, decimal, and exponent
                    if (["-", "+", ".", "e", "E"].includes(e.key)) {
                      e.preventDefault();
                    }
                  }}
                  placeholder="House 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">Notes</label>
                <RichTextEditor
                  value={formData.additionalNote}
                  onChange={(val) => handleInput("additionalNote", val)}
                />
              </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"
                  min="0"
                  step="1"
                  onKeyDown={(e) => {
                    if (e.key === "." || e.key === "," || e.key === "e" || e.key === "-") {
                      e.preventDefault();
                    }
                  }}
                  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">Notes</label>
                <RichTextEditor
                  value={formData.additionalNote}
                  onChange={(val) => handleInput("additionalNote", val)}
                />
              </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">Notes</label>
                <RichTextEditor
                  value={formData.additionalNote}
                  onChange={(val) => handleInput("additionalNote", val)}
                />
              </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">Notes</label>
                <RichTextEditor
                  value={formData.additionalNote}
                  onChange={(val) => handleInput("additionalNote", val)}
                />
              </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">Notes</label>
                <RichTextEditor
                  value={formData.additionalNote}
                  onChange={(val) => handleInput("additionalNote", val)}
                />
              </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">Notes</label>
                <RichTextEditor
                  value={formData.additionalNote}
                  onChange={(val) => handleInput("additionalNote", val)}
                />
              </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">
                  JR Status <span style={{ color: "red" }}>*</span>
                </label>
                <CustomSelect
                  value={formData.status}
                  placeholder="Select Status"
                  options={[
                    {
                      label: "In Process",
                      value: "in_process",
                      disabled: true,
                    },
                    {
                      label: "Enriched",
                      value: "enriched",
                      disabled: true,
                    },
                    {
                      label: "Complete",
                      value: "complete",
                      disabled: false,
                    },
                    {
                      label: "Selected",
                      value: "selected",
                      disabled: true,
                    },
                    {
                      label: "Assigned",
                      value: "assigned",
                      disabled: true,
                    },
                    {
                      label: "Rejected",
                      value: "rejected",
                      disabled: true,
                    },
                  ]}
                  onChange={(e) => handleInput("status", 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">
                  CR Status
                </label>
                <input
                  type="text"
                  disabled
                  value={formatStatus(formData.comprehensiveReportStatus) || ""}
                  placeholder=""
                />
              </div>
            </div>

            <div className="col-12 mb-3">
              <div className="datafrm m-0">
                <label className="text-start">Notes</label>
                <RichTextEditor
                  value={formData.additionalNote}
                  onChange={(val) => handleInput("additionalNote", val)}
                />
              </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={baseRoute}>
              {isComprehensive ? "Comprehensive Report" : "Juror Management"}
            </Link>
          </li>
          <li>Edit Juror</li>
        </ul>
      </div>
      <div
        className="actindted"
        style={{
          display: "flex",
          justifyContent: "flex-end",
          alignItems: "center",
          gap: "8px",
          padding: "10px"
        }}

      >
        {/* View Report */}
        <button
          title="View Report"
          onClick={() => navigate(`${baseRoute}/view/${jurorId}`)}
          style={{
            width: "30px",
            height: "30px",
            borderRadius: "8px",
            border: "1px solid #3b82f6",
            color: "#3b82f6",
            background: "#eff6ff",
            cursor: "pointer",
          }}
        >
          <i className="bi bi-eye-fill"></i>
        </button>

        {/* Run IDI Report */}
        <button
          title="Run Comprehensive Report"
          onClick={() => {
            setSelectedJurorId(jurorId);
            setShowIdiModal(true);
          }}
          style={{
            width: "30px",
            height: "30px",
            borderRadius: "8px",
            border: "1px solid #8b5cf6",
            color: "#8b5cf6",
            background: "#f5f3ff",
            cursor: "pointer",
          }}
        >
          <i className="bi bi-file-earmark-bar-graph-fill"></i>
        </button>

        <button
          title="Edit Juror"
          // onClick={() => {
          //   if (!caseId) {
          //     toast.error("This juror is not assigned to any case.");
          //     return;
          //   }

          //   navigate(
          //     `${baseRoute}/edit/${jurorId}?caseId=${caseId}`
          //   )
          // }}
          style={{
            width: "30px",
            height: "30px",
            borderRadius: "8px",
            border: "1px solid #10b981",
            color: "#10b981",
            background: "#ecfdf5",
            cursor: "pointer",
          }}
        >
          <i className="bi bi-pencil-fill"></i>
        </button>

        {/* Social Links */}
        <button
          title="Social Links"
          onClick={() => navigate(`${baseRoute}/social-links/${jurorId}`)}
          style={{
            width: "30px",
            height: "30px",
            borderRadius: "8px",
            border: "1px solid #f59e0b",
            color: "#f59e0b",
            background: "#fffbeb",
            cursor: "pointer",
          }}
        >
          <i className="bi bi-share-fill"></i>
        </button>
      </div>
      <div className="dshboardwhtepnel">
        {loading ? (
          <div
            className="d-flex justify-content-center align-items-center"
            style={{ height: "60vh" }}
          >
            <ClipLoader size={24} color="#0C3155" loading />
          </div>
        ) : (
          <>
            <div className="d-flex justify-content-between align-items-center mb-4">
              <div>
                <h3 className="mb-1">Edit Juror <span style={{ fontSize: "16px", color: "red" }}> - {fName} {mName} {lName} </span> <span style={{
                  fontSize: "14px",
                  marginLeft: 8,
                  padding: "2px 10px",
                  borderRadius: 12,
                  background: "#e9ecef",
                  color: "#0C3155",
                  fontWeight: 600,
                }}>{formData.status}</span></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 edit-juror-new 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>
      {showIdiModal && (
        <RunIdiReportModal
          jurorId={selectedJurorId}
          isComprehensive={isComprehensive}
          onClose={() => setShowIdiModal(false)}
        />
      )}
    </Layout>
  );
}
