import React, { useEffect, useState } from "react";
import {
  createJurors,
  getAllJurors,
  importJurors,
  getAllEducationLevels,
  getAllStates,
} from "@/services/jurorsService";
import {
  assignJurorToCase,
  alreadyAssignedToCase,
  getMaritalStatus,
} from "@/services/caseService";
import CustomSelect from "../../../common/CustomSelect";
import { toast } from "react-toastify";
import { ClipLoader } from "react-spinners";

// export default function AddJurorsUpdated({ data }) {
export default function AddJurorModel({ data, onClose, onSuccess }) {
  const [availableJurors, setAvailableJurors] = useState([]);
  const [selectedJurors, setSelectedJurors] = useState([]);
  const [currentStep, setCurrentStep] = useState(1);
  const [loading, setLoading] = useState(true);
  const [assignedJurors, setAssignedJurors] = useState([]);
  const [maritalStatusOptions, setMaritalStatusOptions] = useState([]);
  const [educationLevelOptions, setEducationLevelOptions] = useState([]);
  const [stateOptions, setStateOptions] = useState([]);
  const [errors, setErrors] = useState({
    addresses: [],
  });

  const fetchJurors = async () => {
    try {
      const { data } = await getAllJurors();
      // let a=data.results.filter(i=>{return })
      setAvailableJurors(data.results || []);
    } catch {
      // toast.error("Failed to load jurors");
    } finally {
      setLoading(false);
    }
  };

  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 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 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 fetchAssignedJurors = async () => {
    try {
      const response = await alreadyAssignedToCase(data.id);
      setAssignedJurors(response.data.jurors.map((j) => j.id));
    } catch (error) {
      // toast.error("Failed to load assigned jurors");
    }
  };

  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)}`;
  };

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

  useEffect(() => {
    if (data) {
      setFormData((prev) => ({
        ...prev,
        caseNumber: data.case_id || "",
        caseName: data.name || "",
      }));
    }
  }, [data]);

  const [formData, setFormData] = useState({
    id: `JUR-${Date.now()}`,

    firstName: "",
    middleName: "",
    lastName: "",
    juryNumber: "",
    caseNumber: "",
    caseName: "",

    dob: "",
    age: "",
    gender: "",
    usCitizen: "",
    educationLevel: "",
    maritalStatus: "",
    race: "",
    birthCountry: "",

    spouseFullName: "",
    spouseEmploymentStatus: "",
    spouseOccupation: "",
    spouseEmployerName: "",

    religion: "",
    politicalAffiliation: "",
    votingRecord: "",
    relativeLawEnforcement: "",

    employerBusinessName: "",
    employmentStatus: "",
    occupation: "",
    jobTitle: "",

    civilJury: false,
    criminalJury: false,
    grandJury: false,
    verdictReached: "",

    partyToCivilSuit: false,
    accusedCriminalTrial: false,
    complainantCriminalTrial: false,
    witnessCriminalTrial: false,
    felonyProbationHistory: false,
    misdemeanorTheftConviction: false,

    analystNotes: "",
    notes: "",
    idiJson: "",
    status: "unassigned",

    photo: null,
    socialInformationLink: "",

    addresses: [
      {
        primaryEmail: "",
        streetAddress: "",
        city: "",
        state: "",
        county: "",
        zipCode: "",
        primaryPhone: "",
        mobilePhone: "",
        houseOwnership: "",
      },
    ],
  });

  const handleCheckbox = (id) => {
    setSelectedJurors((prev) =>
      prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id],
    );
  };

  const allowOnlyText = (value) => {
    return value.replace(/[^a-zA-Z\s]/g, "");
  };

  const allowOnlyNumbers = (value) => {
    return value.replace(/[^0-9]/g, "");
  };

  const allowAlphaNumeric = (value) => {
    return value.replace(/[^a-zA-Z0-9\s]/g, "");
  };

  const handleAddressChange = (index, field, value) => {
    const updated = [...formData.addresses];
    let updatedValue = value;

    if (["city", "state", "county"].includes(field)) {
      updatedValue = allowOnlyText(value);
    }

    if (field === "zipCode") {
      updatedValue = allowOnlyNumbers(value).slice(0, 6);
    }

    if (["primaryPhone", "mobilePhone"].includes(field)) {
      updatedValue = formatUSPhone(value);
    }

    if (field === "zipCode") {
      updatedValue = updatedValue.slice(0, 6);
    }

    if (field === "streetAddress") {
      updatedValue = allowAlphaNumeric(value);
    }

    updated[index][field] = updatedValue;

    setFormData({
      ...formData,
      addresses: updated,
    });

    // 🔹 Validation
    let errorMsg = "";

    if (["primaryPhone", "mobilePhone"].includes(field)) {
      const digitsOnly = updatedValue.replace(/\D/g, "");
      if (digitsOnly && digitsOnly.length !== 10) {
        errorMsg = "Please enter a valid US phone number";
      }
    }

    // 🔹 Update Errors (Nested)
    const updatedErrors = { ...errors };
    if (!updatedErrors.addresses[index]) {
      updatedErrors.addresses[index] = {};
    }

    updatedErrors.addresses[index][field] = errorMsg;

    setErrors(updatedErrors);
  };

  const handleInput = (e) => {
    const { name, value, files, type, checked } = e.target;

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

      // If only year is entered
      if (/^\d{4}$/.test(updatedValue)) {
        updatedValue = `XX-XX-${updatedValue}`;
      }
    }
    if (
      [
        "firstName",
        "middleName",
        "lastName",
        "city",
        "state",
        "county",
        "spouseFullName",
        "spouseEmployerName",
        "occupation",
        "jobTitle",
        "religion",
      ].includes(name)
    ) {
      updatedValue = allowOnlyText(value);
    }
    if (["age", "zipCode", "primaryPhone", "mobilePhone"].includes(name)) {
      updatedValue = allowOnlyNumbers(value);
    }

    setFormData((prev) => ({
      ...prev,
      [name]:
        type === "file"
          ? files[0]
          : type === "checkbox"
            ? checked
            : updatedValue,
    }));
  };

  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.age, message: "Age is required" },
      { field: formData.gender, message: "Gender is required" },
    ],
  };

  // const handleNext = () => {
  //   if (currentStep < 8) setCurrentStep(currentStep + 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 handlePrev = () => {
    if (currentStep > 1) setCurrentStep(currentStep - 1);
  };

  const handleAddJuror = async (e, addMore = false) => {
    if (e) e.preventDefault();

    const validations = stepValidation[1] || [];

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

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

    try {
      const payload = new FormData();
      // payload.append("id", formData.id);
      payload.append("case", data?.id || formData.caseNumber || "");
      payload.append("first_name", formData.firstName || "");
      payload.append("middle_name", formData.middleName || "");
      payload.append("last_name", formData.lastName || "");
      payload.append("juror_number", formData.juryNumber || "");
      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 === "Yes");
      payload.append("education_level", formData.educationLevel || "");
      payload.append("marital_status", formData.maritalStatus || "");
      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 || "");
      const address = formData.addresses?.[0] || {};
      payload.append("email", address.primaryEmail || "");
      payload.append(
        "primary_phone",
        toUSPhoneE164(address.primaryPhone) || "",
      );
      payload.append("cell_phone", toUSPhoneE164(address.mobilePhone) || "");
      payload.append("street_address", address.streetAddress || "");
      payload.append("city", address.city || "");
      payload.append("state", address.state || "");
      payload.append("county", address.county || "");
      payload.append("zipcode", address.zipCode || "");
      payload.append("house_ownership", address.houseOwnership || "");
      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("employer", formData.employerBusinessName || "");
      payload.append("job_title", formData.jobTitle || "");
      payload.append("employment_status", formData.employmentStatus || "");
      payload.append("occupation", formData.occupation || "");
      payload.append("civil_jury", formData.civilJury);
      payload.append("criminal_jury", formData.criminalJury);
      payload.append("grand_jury", formData.grandJury);
      payload.append("verdict_reached", formData.verdictReached === "Y");
      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("analyst_notes", formData.analystNotes || "");
      payload.append("notes", formData.notes || "");
      payload.append("id_json_file_name", formData.idiJson || "");
      payload.append("status", formData.status);
      const socialMedia = [];
      if (formData.socialInformationLink) {
        socialMedia.push({
          platform: "custom",
          url: formData.socialInformationLink,
          username: "",
        });
      }
      payload.append("social_media", JSON.stringify(socialMedia));
      if (formData.photo) {
        payload.append("photo", formData.photo);
      }
      await createJurors(payload);
      toast.success("Juror Added Successfully");
      fetchJurors();
      onSuccess?.();

      if (addMore) {
        // Reset form only
        handleCancel();
        setCurrentStep(1);
        return;
      }

      // Close modal
      onClose();

      setFormData((prev) => ({
        ...prev,
        id: `JUR-${Date.now()}`,
        firstName: "",
        middleName: "",
        lastName: "",
        juryNumber: "",
        dob: "",
        age: "",
        gender: "",
        photo: null,
      }));

      setCurrentStep(1);
    } 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 add juror");
    }
  };

  const toUSPhoneE164 = (value) => {
    const digits = value.replace(/\D/g, "").slice(0, 10);
    return digits.length === 10 ? digits : "";
  };

  const handleCsvUpload = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append("file", file);

    try {
      await importJurors(formData);

      toast.success("CSV Imported Successfully!");
      const { data } = await getAllJurors();
      setAvailableJurors(data.results || []);

      event.target.value = "";
    } catch (error) {
      console.error("CSV Import Error:", error);
      toast.error("Failed to import CSV. Check CSV format.");
    }
  };

  const handleAssignJurors = async () => {
    if (selectedJurors.length === 0) {
      toast.warn("Select at least one juror");
      return;
    }

    try {
      await assignJurorToCase(data.id, { juror_ids: selectedJurors });
      toast.success("Jurors Assigned Successfully!");

      // Refresh UI
      fetchAssignedJurors();
      setSelectedJurors([]);
    } catch (error) {
      toast.error("Failed to assign jurors");
    }
  };

  const handleDownloadSampleCsv = () => {
    const csvContent = [
      [
        "Juror #",
        "Name",
        "City",
        "State",
        "Age",
        "Gender",
        "Race",
        "Occupation",
        "Marital Status",
      ],
      [
        "2025-11906602",
        "Hall Sally",
        "Austin",
        "TX",
        "38",
        "Female",
        "White or Caucasian",
        "Project Manager",
        "Married",
      ],
      [
        "2025-11906603",
        "Kihnel Candice",
        "Austin",
        "TX",
        "42",
        "Female",
        "American Indian / Alaskan Native",
        "Pharmacy Technician",
        "Divorced",
      ],
      [
        "2025-11906604",
        "Sutton Jill Podlech",
        "Austin",
        "TX",
        "47",
        "Female",
        "White or Caucasian",
        "Not Specified",
        "Married",
      ],
    ]
      .map((row) => row.join(","))
      .join("\n");

    const blob = new Blob([csvContent], {
      type: "text/csv;charset=utf-8;",
    });

    const url = window.URL.createObjectURL(blob);

    const link = document.createElement("a");
    link.href = url;
    link.download = "juror_sample.csv";

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    window.URL.revokeObjectURL(url);
  };

  const handleCancel = () => {
    setFormData({
      id: `JUR-${Date.now()}`,

      firstName: "",
      middleName: "",
      lastName: "",
      juryNumber: "",
      caseNumber: data?.case_id || "",
      caseName: data?.name || "",

      dob: "",
      age: "",
      gender: "",
      usCitizen: "",
      educationLevel: "",
      maritalStatus: "",
      race: "",
      birthCountry: "",

      spouseFullName: "",
      spouseEmploymentStatus: "",
      spouseOccupation: "",
      spouseEmployerName: "",

      religion: "",
      politicalAffiliation: "",
      votingRecord: "",
      relativeLawEnforcement: "",

      employerBusinessName: "",
      employmentStatus: "",
      occupation: "",
      jobTitle: "",

      civilJury: false,
      criminalJury: false,
      grandJury: false,
      verdictReached: "",

      partyToCivilSuit: false,
      accusedCriminalTrial: false,
      complainantCriminalTrial: false,
      witnessCriminalTrial: false,
      felonyProbationHistory: false,
      misdemeanorTheftConviction: false,

      analystNotes: "",
      notes: "",
      idiJson: "",
      status: "unassigned",

      photo: null,
      socialInformationLink: "",

      addresses: [
        {
          primaryEmail: "",
          streetAddress: "",
          city: "",
          state: "",
          county: "",
          zipCode: "",
          primaryPhone: "",
          mobilePhone: "",
          houseOwnership: "",
        },
      ],
    });

    setErrors({
      addresses: [],
    });
  };

  return (
    <div className="modal-backdrop">
      <div className="edit-juror-modal">
        {loading ? (
          <div
            style={{
              position: "absolute",
              inset: 0,
              background: "rgba(0,0,0,0.45)",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              zIndex: 999,
              borderRadius: "12px",
            }}
          >
            <ClipLoader color="#fff" size={30} />
          </div>
        ) : (
          <>
            {/* Header */}
            <div className="modal-header">
              <div>
                <h3 className="m-0">Add New Juror</h3>
                <p className="mb-0">
                  Create a new juror profile and add them to this case.
                </p>
              </div>

              <button className="btn-close" onClick={onClose}></button>
            </div>

            {/* Body */}
            <div className="modal-body">
              {/* Top Actions */}
              <div className="d-flex justify-content-end gap-2 mb-4 flex-wrap">
                <button
                  className="heading-btn"
                  type="button"
                  onClick={handleDownloadSampleCsv}
                >
                  <svg
                    viewBox="0 0 15 15"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M7.5 1V9M7.5 9L4.5 6M7.5 9L10.5 6"
                      stroke="currentColor"
                      strokeWidth="1.5"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                    <path
                      d="M2 11.5V12.5C2 13.0523 2.44772 13.5 3 13.5H12C12.5523 13.5 13 13.0523 13 12.5V11.5"
                      stroke="currentColor"
                      strokeWidth="1.5"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>

                  <span>Download Sample CSV</span>
                </button>

                <button
                  className="heading-btn"
                  type="button"
                  onClick={() => document.getElementById("uploadCsv").click()}
                >
                  <svg viewBox="0 0 13 15" fill="none">
                    <path
                      d="M7.4987 0.5V3.29948C7.4987 3.67071 7.64617 4.02674 7.90867 4.28924C8.17117 4.55175 8.5272 4.69922 8.89844 4.69922H11.6979M3.29948 8.19857H4.69922M7.4987 8.19857H8.89844M3.29948 10.998H4.69922M7.4987 10.998H8.89844M8.19857 0.5H1.89974C1.52851 0.5 1.17248 0.647472 0.909974 0.909974C0.647472 1.17248 0.5 1.52851 0.5 1.89974V13.0977C0.5 13.4689 0.647472 13.8249 0.909974 14.0874C1.17248 14.3499 1.52851 14.4974 1.89974 14.4974H10.2982C10.6694 14.4974 11.0254 14.3499 11.2879 14.0874C11.5504 13.8249 11.6979 13.4689 11.6979 13.0977V3.99935L8.19857 0.5Z"
                      stroke="currentColor"
                    />
                  </svg>

                  <span>Import CSV</span>
                </button>

                <input
                  type="file"
                  id="uploadCsv"
                  accept=".csv"
                  hidden
                  onChange={handleCsvUpload}
                />
              </div>

              <div className="row gx-2">
                {/* Juror Number */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">
                      Juror Number <span style={{ color: "red" }}>*</span>
                    </label>
                    <input
                      type="text"
                      placeholder="Enter Juror Number"
                      name="juryNumber"
                      value={formData.juryNumber}
                      onChange={handleInput}
                    />
                  </div>
                </div>

                {/* Case Name */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">
                      Case Name <span style={{ color: "red" }}>*</span>
                    </label>
                    <input
                      type="text"
                      name="caseName"
                      value={formData.caseName}
                      readOnly
                    />
                  </div>
                </div>
                {/* Last Name */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">
                      Last Name <span style={{ color: "red" }}>*</span>
                    </label>
                    <input
                      type="text"
                      placeholder="Enter last name"
                      name="lastName"
                      value={formData.lastName}
                      onChange={handleInput}
                    />
                  </div>
                </div>
                {/* First Name */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">
                      First Name <span style={{ color: "red" }}>*</span>
                    </label>
                    <input
                      type="text"
                      placeholder="Enter first name"
                      name="firstName"
                      value={formData.firstName}
                      onChange={handleInput}
                    />
                  </div>
                </div>

                {/* Middle Name */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">Middle Name</label>
                    <input
                      type="text"
                      placeholder="Enter middle name"
                      name="middleName"
                      value={formData.middleName}
                      onChange={handleInput}
                    />
                  </div>
                </div>

                {/* Gender */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">Gender</label>

                    <CustomSelect
                      name="gender"
                      value={formData.gender}
                      onChange={handleInput}
                      placeholder="Select Gender"
                      options={[
                        { label: "Male", value: "M" },
                        { label: "Female", value: "F" },
                        { label: "Other", value: "O" },
                      ]}
                    />
                  </div>
                </div>

                {/* Birth Year */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">Birth Year</label>
                    <input
                      type="text"
                      placeholder="MM-DD-YYYY"
                      name="dob"
                      value={formData.dob}
                      onChange={handleInput}
                      onBlur={(e) => {
                        const value = e.target.value.trim();

                        if (/^\d{4}$/.test(value)) {
                          setFormData((prev) => ({
                            ...prev,
                            dob: `XX-XX-${value}`,
                          }));
                        }
                      }}
                    />
                  </div>
                </div>

                {/* Age */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">Age</label>
                    <input
                      type="number"
                      placeholder="Enter age"
                      name="age"
                      value={formData.age}
                      onChange={handleInput}
                    />
                  </div>
                </div>

                {/* Address */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">Address</label>
                    <input
                      type="text"
                      placeholder="Enter address"
                      value={formData.addresses?.[0]?.streetAddress || ""}
                      onChange={(e) =>
                        handleAddressChange(0, "streetAddress", e.target.value)
                      }
                    />
                  </div>
                </div>

                {/* City */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">City</label>
                    <input
                      type="text"
                      placeholder="Enter city"
                      value={formData.addresses?.[0]?.city || ""}
                      onChange={(e) =>
                        handleAddressChange(0, "city", e.target.value)
                      }
                    />
                  </div>
                </div>

                {/* State */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">
                      State <span style={{ color: "red" }}>*</span>
                    </label>

                    <CustomSelect
                      value={formData.addresses?.[0]?.state || ""}
                      placeholder="Select State"
                      options={stateOptions}
                      onChange={(e) => {
                        const updated = [...formData.addresses];
                        updated[0].state = e.target.value;

                        setFormData({
                          ...formData,
                          addresses: updated,
                        });
                      }}
                    />
                  </div>
                </div>

                {/* County */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">County</label>
                    <input
                      type="text"
                      placeholder="Enter county"
                      value={formData.addresses?.[0]?.county || ""}
                      onChange={(e) =>
                        handleAddressChange(0, "county", e.target.value)
                      }
                    />
                  </div>
                </div>

                {/* Phone */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">Phone </label>
                    <input
                      type="text"
                      placeholder="Enter phone number"
                      value={formData.addresses?.[0]?.primaryPhone || ""}
                      onChange={(e) =>
                        handleAddressChange(0, "primaryPhone", e.target.value)
                      }
                    />

                    {errors?.addresses?.[0]?.primaryPhone && (
                      <p className="text-danger d-block mt-1">
                        {errors.addresses[0].primaryPhone}
                      </p>
                    )}
                  </div>
                </div>

                {/* Email */}
                <div className="col-lg-4 col-sm-6 col-12">
                  <div className="datafrm">
                    <label className="text-start">Email</label>
                    <input
                      type="email"
                      placeholder="Enter email"
                      value={formData.addresses?.[0]?.primaryEmail || ""}
                      onChange={(e) =>
                        handleAddressChange(0, "primaryEmail", e.target.value)
                      }
                    />
                  </div>
                </div>
              </div>
            </div>

            {/* Footer */}
            <div className="modal-footer">
              <div className="datafrmbtn d-flex flex-wrap gap-2 m-0">
                <button
                  className="savebtn px-3"
                  type="button"
                  onClick={(e) => handleAddJuror(e, true)}
                >
                  Save &amp; Add More
                </button>

                <button
                  className="savebtn"
                  type="button"
                  onClick={(e) => handleAddJuror(e, false)}
                >
                  Save
                </button>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
