import React, { useEffect, useState } from "react";
import { ClipLoader } from "react-spinners";
import { toast } from "react-toastify";
import { getJurorById } from "@/services/jurorsService";

export default function ViewJurorModal({
   open,
   jurorId,
   onClose,
}) {
   const [loading, setLoading] = useState(false);
   const [juror, setJuror] = useState(null);

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

         getJurorById(jurorId)
            .then((res) => {
               setJuror(res.data);
            })
            .catch(() => {
               toast.error("Failed to load juror details");
            })
            .finally(() => {
               setLoading(false);
            });
      }
   }, [open, jurorId]);

   if (!open) return null;

   const Item = ({ label, value, isHtml = false }) => (
      <div className="col-lg-4 col-md-6 mb-3">
         <div>
            <strong>{label}</strong>
         </div>

         <div>
            {value !== null && value !== undefined && value !== "" ? (
               isHtml ? (
                  <div dangerouslySetInnerHTML={{ __html: value }} />
               ) : (
                  value.toString()
               )
            ) : (
               "-"
            )}
         </div>
      </div>
   );

   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 capitalize = (str = "") =>
      str.charAt(0).toUpperCase() + str.slice(1);

   const noteOrder = [
      "identification_additional_note",
      "contact_information_additional_note",
      "demographics_additional_note",
      "family_background_additional_note",
      "employment_details_additional_note",
      "prior_jury_experience_additional_note",
      "prior_trial_experience_additional_note",
      "internal_use_fields_additional_note",
   ];

   // const sortedNotes = [...(juror.notes || [])].sort(
   //    (a, b) => noteOrder.indexOf(a.tab) - noteOrder.indexOf(b.tab)
   // );

   return (
      <div className="modal-backdrop">
         <div className="edit-juror-modal">
            {loading ? (
               <div className="text-center p-5">
                  <ClipLoader size={40} />
               </div>
            ) : (
               <>
                  <div className="modal-header">
                     <h3>Juror Details</h3>

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

                  {juror && (
                     <>
                        <div className="modal-body text-start pt-0">
                           <div className="text-center mb-2">
                              {juror.photo && (
                                 <img
                                    src={juror.photo}
                                    alt=""
                                    style={{
                                       width: "90px",
                                       height: "90px",
                                       borderRadius: "50%",
                                       objectFit: "cover"
                                    }}
                                 />
                              )}
                           </div>

                           <div className="row">
                              <div className="col-12">
                                 <div className="viewlist">
                                    <h5>Identification</h5>
                                    <div className="row gx-2">
                                       {/* <Item label="ID" value={juror.id} /> */}
                                       {/* <Item label="Case" value={juror.case} /> */}
                                       <Item label="Juror Number" value={juror.juror_number} />
                                       <Item label="First Name" value={juror.first_name} />
                                       <Item label="Middle Name" value={juror.middle_name} />
                                       <Item label="Last Name" value={juror.last_name} />
                                       <Item label="Status" value={capitalize(juror.status)} />
                                    </div>
                                 </div>
                                 <div className="viewlist">
                                    <h5>Demographics</h5>
                                    <div className="row gx-2">
                                       <Item label="Date Of Birth" value={juror.date_of_birth} />
                                       <Item label="Age" value={juror.age} />
                                       <Item label="Gender" value={juror.gender} />
                                       <Item label="US Citizen" value={juror.us_citizen ? "Yes" : "No"} />
                                       <Item label="Education Level" value={juror.education_levels} />
                                       <Item label="Marital Status" value={capitalize(juror.marital_status)} />
                                       <Item label="Religion" value={juror.religion} />
                                       <Item label="Birth Country" value={juror.birth_country} />
                                       <Item label="Political Party" value={juror.political_party} />
                                       <Item label="Race" value={juror.race} />
                                       <Item label="Voting Record" value={juror.voting_record} />
                                       <Item label="Relative In Law Enforcement" value={juror.relative_in_law_enforcement} />
                                    </div>
                                 </div>
                                 <div className="viewlist">
                                    <h5>Contact Information</h5>
                                    <div className="row gx-2">
                                       <Item label="Email" value={juror.email} />
                                       <Item label="Primary Phone" value={formatUSPhone(juror.primary_phone)} />
                                       <Item label="Cell Phone" value={formatUSPhone(juror.cell_phone)} />
                                       <Item label="Street Address" value={juror.street_address} />
                                       <Item label="City" value={juror.city} />
                                       <Item
                                          label="State"
                                          value={
                                             juror.state_details
                                                ? `${juror.state_details.name || "-"} (${juror.state_details.code || "-"})`
                                                : "-"
                                          }
                                       />
                                       <Item label="County" value={juror.county} />
                                       <Item label="Zip Code" value={juror.zipcode} />
                                       <Item label="House Value" value={juror.house_value} />
                                       <Item label="House Ownership" value={capitalize(juror.house_ownership)} />
                                    </div>
                                 </div>
                                 <div className="viewlist">
                                    <h5>Spouse Information</h5>
                                    <div className="row gx-2">
                                       <Item label="Spouse Name" value={juror.spouse_full_name} />
                                       <Item label="Employment Status" value={capitalize(juror.spouse_employment_status)} />
                                       <Item label="Occupation" value={juror.spouse_occupation} />
                                       <Item label="Employer" value={juror.spouse_employer_name} />
                                    </div>
                                 </div>
                                 <div className="viewlist">
                                    <h5>Employment Information</h5>
                                    <div className="row gx-2">
                                       <Item label="Employer" value={juror.employer} />
                                       <Item label="Job Title" value={juror.job_title} />
                                       <Item label="Employment Status" value={capitalize(juror.employment_status)} />
                                       <Item label="Occupation" value={juror.occupation} />
                                    </div>
                                 </div>
                                 <div className="viewlist">
                                    <h5>Jury Experience</h5>
                                    <div className="row gx-2">
                                       <Item label="Civil Jury" value={juror.civil_jury ? "Yes" : "No"} />
                                       <Item label="Criminal Jury" value={juror.criminal_jury ? "Yes" : "No"} />
                                       <Item label="Grand Jury" value={juror.grand_jury ? "Yes" : "No"} />
                                       <Item label="Verdict Reached" value={juror.verdict_reached ? "Yes" : "No"} />
                                    </div>
                                 </div>
                                 <div className="viewlist">
                                    <h5>Trial History</h5>
                                    <div className="row gx-2">
                                       <Item label="Party To Civil Suit" value={juror.party_to_civil_suit ? "Yes" : "No"} />
                                       <Item label="Accused Criminal Trial" value={juror.accused_in_criminal_trial ? "Yes" : "No"} />
                                       <Item label="Complainant Criminal Trial" value={juror.complainant_in_criminal_trial ? "Yes" : "No"} />
                                       <Item label="Witness Criminal Trial" value={juror.witness_in_criminal_trial ? "Yes" : "No"} />
                                       <Item label="Felony Probation History" value={juror.felony_probation_history ? "Yes" : "No"} />
                                       <Item label="Misdemeanor Theft Conviction" value={juror.misdemeanor_theft_conviction ? "Yes" : "No"} />
                                    </div>
                                 </div>
                                 <div className="viewlist">
                                    <h5>Internal Notes</h5>
                                    <div className="row gx-2">
                                       <Item label="Analyst Notes" value={juror.analyst_notes} />
                                       {/* <Item label="Notes" value={juror.notes} /> */}
                                       <Item label="ID Json File" value={juror.id_json_file_name} />
                                       {/* <Item label="Created At" value={juror.created_at} />
                                    <Item label="Updated At" value={juror.updated_at} /> */}
                                    </div>
                                    <div className="row gx-2">
                                       <Item label="Notes" value={juror.additional_note} isHtml={true}/>
                                    </div>
                                 </div>

                                 {/* <div className="viewlist">
                                    <h5>Notes</h5>
                                    <div className="row gx-2">
                                       <Item label="Notes" value={juror.additional_note} isHtml={true} />
                                    </div>
                                 </div> */}
                                 {/* <div className="viewlist">
                                    <h5>Additional Notes</h5>

                                    {juror.notes.length ? (
                                       juror.notes.map((item, index) => (
                                          <div className="mb-3" key={item.id}>
                                             <div>
                                                <strong>
                                                   {index + 1}.{" "}
                                                   {item.tab
                                                      .replace(/_/g, " ")
                                                      .replace(/\b\w/g, (c) => c.toUpperCase())}
                                                </strong>
                                             </div>

                                             <div className="mt-1">
                                                {item.note || "-"}
                                             </div>
                                          </div>
                                       ))
                                    ) : (
                                       <div>-</div>
                                    )}
                                 </div> */}
                              </div>
                           </div>
                        </div>
                        <div className="modal-footer">
                           <div className="datafrmbtn d-flex flex-wrap gap-2 m-0">
                              <button className="canselbtn" onClick={onClose}>Close</button>
                           </div>
                        </div>
                     </>
                  )}
               </>
            )}
         </div>
      </div>
   );
}