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

export default function AddJurors({ data }) {
  const [availableJurors, setAvailableJurors] = useState([]);
  const [selectedJurors, setSelectedJurors] = useState([]);
  const [currentStep, setCurrentStep] = useState(1);
  const [loading, setLoading] = useState(true);
  const [assignedJurors, setAssignedJurors] = useState([]);


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


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

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


  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    age: "",
    maritalStatus: "",
    hasChildren: false,
    educationLevel: "",
    profilePicture: null,
    profilePictureSource: "",
    phoneNumbers: [""],
    emails: [""],
    addresses: [
      {
        streetAddress: "",
        city: "",
        state: "",
        zipCode: "",
        startDate: "",
        endDate: ""
      }
    ],
    employmentHistory: [
      {
        empName: "",
        empAddress: "",
        jobTitle: "",
        zipCode: "",
        startDate: "",
        endDate: ""
      }
    ],
    socialMedia: [
      {
        platform: "",
        url: "",
        analystComments: ""
      }
    ],
    notes: ""
  });


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

  const handleInput = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleNext = () => {
    if (currentStep < 5) setCurrentStep(currentStep + 1);
  };

  const handlePrev = () => {
    if (currentStep > 1) setCurrentStep(currentStep - 1);
  };

  const handleAddJuror = async (e) => {
    e.preventDefault();

    try {
      const payload = new FormData();

      payload.append("first_name", formData.firstName);
      payload.append("last_name", formData.lastName);
      payload.append("age", formData.age);
      payload.append("marital_status", formData.maritalStatus);
      payload.append("has_children", formData.hasChildren);
      payload.append("education_level", formData.educationLevel);
      payload.append("notes", formData.notes);
      payload.append("phone_numbers", JSON.stringify(formData.phoneNumbers));
      payload.append("emails", JSON.stringify(formData.emails));
      const formattedAddresses = formData.addresses.map(addr => ({
        street_address: addr.streetAddress,
        city: addr.city,
        state: addr.state,
        zip_code: addr.zipCode,
        start_date: addr.startDate,
        end_date: addr.endDate
      }));
      payload.append("addresses", JSON.stringify(formattedAddresses));
      const formattedEmployment = formData.employmentHistory.map(job => ({
        emp_name: job.empName,
        emp_address: job.empAddress,
        job_title: job.jobTitle,
        zip_code: job.zipCode,
        start_date: job.startDate,
        end_date: job.endDate
      }));
      payload.append("employment_history", JSON.stringify(formattedEmployment));
      const formattedSocial = formData.socialMedia.map(sm => ({
        platform: sm.platform,
        url: sm.url,
        analyst_comments: sm.analystComments
      }));
      payload.append("social_media", JSON.stringify(formattedSocial));
      if (formData.profilePicture) {
        payload.append("profile_picture", formData.profilePicture);
      }

      await createJurors(payload);

      toast.success("Juror Added Successfully!");

      // Reset form
      setFormData({
        firstName: "",
        lastName: "",
        age: "",
        maritalStatus: "",
        hasChildren: false,
        educationLevel: "",
        profilePicture: null,
        profilePictureSource: "",
        phoneNumbers: [""],
        emails: [""],
        addresses: [
          {
            streetAddress: "",
            city: "",
            state: "",
            zipCode: "",
            startDate: "",
            endDate: ""
          }
        ],
        employmentHistory: [
          {
            empName: "",
            empAddress: "",
            jobTitle: "",
            zipCode: "",
            startDate: "",
            endDate: ""
          }
        ],
        socialMedia: [
          {
            platform: "",
            url: "",
            analystComments: ""
          }
        ],
        notes: ""
      });

    } catch (error) {
      console.error("Error while creating juror:", error);
      toast.error("Failed to add juror. Please try again.");
    }
  };


  const handleChange = (e) => {
    const { name, value } = e.target;

    setFormData((prev) => ({
      ...prev,
      [name]: value
    }));
  };

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



  return (
    <div className="profilefrmtabopen">
      <div className="tab-content" id="myTabContent">

        <div
          className="tab-pane fade show active"
          id="ViewCaseInfo-tab-pane"
          role="tabpanel"
          aria-labelledby="ViewCaseInfo-tab"
          tabIndex="0"
        >
          <div className="profilefrmshowsd">

            <div className="profilefrmhder">
              <h3>Juror Selection Status</h3>
              <p>
                {selectedJurors.length} juror(s) selected from {availableJurors.length} available • {availableJurors.length} currently
              </p>
            </div>

            <div className="row">

              {/* Left side Available Jurors */}
              <div className="col-xl-6 col-lg-6 col-sm-12 col-12 mt-3 mt-md-4">
              {/* <div className="col-xl-12 col-lg-12 col-sm-12 col-12 mt-3 mt-md-4"> */}
                <div className="casetabnx">

                  <div className="d-flex justify-content-between gap-2 mb-2 mb-md-3">
                    <div className="w-100">
                      <h4>Available Jurors ({availableJurors.length})</h4>
                      <p>Select jurors from the available pool to add to this case.</p>
                    </div>

                    <button
                      className="import-btn"
                      type="button"
                      onClick={() => document.getElementById("uploadCsv").click()}
                    >
                      <svg width="13" height="15" 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"
                      style={{ display: "none" }}
                      onChange={handleCsvUpload}
                    />

                  </div>

                  <div className="importedlistouter">
                    {availableJurors.map((juror) => (
                      <div className="importedlist" key={juror.id}>
                        <div className="form-check">
                          <input
                            className="form-check-input"
                            type="checkbox"
                            id={`juror-${juror.id}`}
                            disabled={assignedJurors.includes(juror.id)}
                            checked={
                              assignedJurors.includes(juror.id) || selectedJurors.includes(juror.id)
                            }
                            onChange={() => handleCheckbox(juror.id)}
                          />

                        </div>

                        <div className="importedmediabx">
                          <div className="importedmedia">
                            {`${juror.first_name?.[0] || ""}${juror.last_name?.[0] || ""}`.toUpperCase()}
                          </div>
                          <div className="importedmediact">
                            
                            <h5 className="">
                              {juror.first_name} {juror.last_name}
                              {assignedJurors.includes(juror.id) && (
                                <span className="importedbadge">Already in case</span>
                              )}
                            </h5>
                            <p>
                              {juror.employment_history && juror.employment_history.length > 0
                                ? juror.employment_history
                                  .map(
                                    (emp) =>
                                      `${emp.emp_name} (${emp.job_title}, ${emp.emp_address})`
                                  )
                                  .join(", ")
                                : "No employment info"}
                            </p>
                          </div>
                        </div>

                        <div className="importedlistbtm">
                          <p>
                            {juror.addresses?.[0]?.street_address}, {juror.addresses?.[0]?.city},
                            {juror.addresses?.[0]?.state} {juror.addresses?.[0]?.zip_code}
                          </p>

                          <p>{juror.phone_numbers?.[0] || "No phone"}</p>

                        </div>
                      </div>
                    ))}
                  </div>

                  <div className="text-end">
                    <button className="adduser d-inline-flex gap-2 mt-3" type="button" onClick={handleAssignJurors}>
                      <svg width="15" height="13" viewBox="0 0 15 13" fill="none">
                        <path
                          d="M9.76002 12.4057V11.0829C9.76002 10.3812 9.48128 9.70824 8.98511 9.21207C8.48894 8.7159 7.81599 8.43716 7.1143 8.43716H3.14572C2.44403 8.43716 1.77108 8.7159 1.27491 9.21207C0.778745 9.70824 0.5 10.3812 0.5 11.0829V12.4057M12.3633 3.97656V6.11328M12.3633 6.11328V8.25M12.3633 6.11328H14.5M12.3633 6.11328H10.2266M7.77573 3.14572C7.77573 4.60691 6.5912 5.79144 5.13001 5.79144C3.66882 5.79144 2.48429 4.60691 2.48429 3.14572C2.48429 1.68453 3.66882 0.5 5.13001 0.5C6.5912 0.5 7.77573 1.68453 7.77573 3.14572Z"
                          stroke="currentColor"
                        />
                      </svg>
                      <span>Assign Analyst</span>
                    </button>
                  </div>
                </div>
              </div>

              {/* Right side Step Form */}
              <div className="col-xl-6 col-lg-6 col-sm-12 col-12 mt-3 mt-md-4">
                <div className="casetabnx">

                  <div className="d-flex justify-content-between gap-2 mb-2 mb-md-3">
                    <div className="w-100">
                      <h4>Add New Juror</h4>
                      <p>Create a new juror profile and add them to this case.</p>
                    </div>
                    <span className="step-label">Step {currentStep} of 5</span>
                  </div>

                  <div className="step-progress-wrapper">
                    <div className="step-progress">
                      {[1, 2, 3, 4, 5].map((step) => (
                        <div
                          key={step}
                          className={`step-item ${currentStep >= step ? "active" : ""}`}
                        ></div>
                      ))}
                    </div>
                  </div>


                  <div className="row gx-2">
                    {currentStep === 1 && (
                      <>
                        <div className="col-lg-12 col-sm-12 col-12">
                          <div className="datafrm">
                            <label>Step 1: Personal Information </label>
                          </div>
                        </div>
                        <div className="col-lg-6 col-sm-6 col-12">
                          <div className="datafrm">
                            <label>First Name *</label>
                            <input type="text" placeholder="Enter first name" name="firstName" value={formData.firstName} onChange={handleInput} />
                          </div>
                        </div>

                        <div className="col-lg-6 col-sm-6 col-12">
                          <div className="datafrm">
                            <label>Last Name *</label>
                            <input type="text" placeholder="Enter last name" name="lastName" value={formData.lastName} onChange={handleInput} />
                          </div>
                        </div>

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

                        <div className="col-lg-6 col-sm-6 col-12">
                          <div className="datafrm">
                            <label>Education Level</label>

                            <CustomSelect
                              name="educationLevel"
                              value={formData.educationLevel}
                              onChange={handleChange}
                              placeholder="Select education level"
                              options={[
                                { label: "High School", value: "High School" },
                                { label: "Associate Degree", value: "Associate Degree" },
                                { label: "Bachelor's Degree", value: "Bachelor's Degree" },
                                { label: "Master's Degree", value: "Master's Degree" },
                                { label: "Doctorate (PhD)", value: "Doctorate" },
                                { label: "Other", value: "Other" }
                              ]}
                            />
                          </div>
                        </div>


                        <div className="col-lg-6 col-sm-6 col-12">
                          <div className="datafrm">
                            <label>
                              Marital Status <span className="required">*</span>
                            </label>

                            <CustomSelect
                              name="maritalStatus"
                              value={formData.maritalStatus}
                              onChange={handleChange}
                              placeholder="Select marital status"
                              options={[
                                { value: "single", label: "Single" },
                                { value: "married", label: "Married" },
                                { value: "divorced", label: "Divorced" },
                                { value: "widowed", label: "Widowed" }
                              ]}
                            />

                          </div>
                        </div>

                        <div className="col-lg-6 col-sm-6 col-12">
                          <div className="datafrm">
                            <label>Has Children</label>

                            <CustomSelect
                              name="hasChildren"
                              value={formData.hasChildren}
                              onChange={handleChange}
                              placeholder="Select marital status"
                              options={[
                                { value: "true", label: "Yes" },
                                { value: "false", label: "No" },
                              ]}
                            />
                          </div>
                        </div>

                        <div className="col-12">
                          <div className="datafrm">
                            <div className="d-flex justify-content-between align-items-center mb-1">
                              <label className="m-0">Phone Numbers *</label>

                              <button
                                type="button"
                                className="add-btn"
                                onClick={() =>
                                  setFormData({
                                    ...formData,
                                    phoneNumbers: [...formData.phoneNumbers, ""],
                                  })
                                }
                              >
                                + Add Phone
                              </button>
                            </div>

                            {formData.phoneNumbers.map((phone, i) => (
                              <div
                                className="d-flex align-items-center gap-2 mb-2"
                                key={i}
                              >
                                <input
                                  type="text"
                                  placeholder="Enter phone number"
                                  value={phone}
                                  onChange={(e) => {
                                    const updatedPhones = [...formData.phoneNumbers];
                                    updatedPhones[i] = e.target.value;
                                    setFormData({ ...formData, phoneNumbers: updatedPhones });
                                  }}
                                />

                                <button
                                  type="button"
                                  className="remove-btn"
                                  onClick={() => {
                                    const updatedPhones = formData.phoneNumbers.filter(
                                      (_, index) => index !== i
                                    );
                                    setFormData({ ...formData, phoneNumbers: updatedPhones });
                                  }}
                                >
                                  <svg width="20" height="22" viewBox="0 0 20 22" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M0.583008 4.69538H19.0887M17.0325 4.69538V19.0887C17.0325 20.1168 16.0044 21.1449 14.9763 21.1449H4.69538C3.66729 21.1449 2.63919 20.1168 2.63919 19.0887V4.69538M5.72347 4.69538V2.63919C5.72347 1.6111 6.75156 0.583008 7.77965 0.583008H11.892C12.9201 0.583008 13.9482 1.6111 13.9482 2.63919V4.69538M7.77966 9.83584V16.0044M11.892 9.83584V16.0044" stroke="#0C3155" stroke-width="1.16667" stroke-linecap="round" stroke-linejoin="round" />
                                  </svg>
                                </button>
                              </div>
                            ))}
                          </div>
                        </div>

                        <div className="col-12">
                          <div className="datafrm">
                            <div className="d-flex justify-content-between align-items-center mb-1">
                              <label className="m-0">Email Address *</label>

                              <button
                                type="button"
                                className="add-btn"
                                onClick={() =>
                                  setFormData({
                                    ...formData,
                                    emails: [...formData.emails, ""],
                                  })
                                }
                              >
                                + Add Email
                              </button>
                            </div>

                            {formData.emails.map((email, i) => (
                              <div
                                className="d-flex align-items-center gap-2 mb-2"
                                key={i}
                              >
                                <input
                                  type="email"
                                  placeholder="Enter email address"
                                  value={email}
                                  onChange={(e) => {
                                    const updatedEmails = [...formData.emails];
                                    updatedEmails[i] = e.target.value;
                                    setFormData({ ...formData, emails: updatedEmails });
                                  }}
                                />

                                <button
                                  type="button"
                                  className="remove-btn"
                                  onClick={() => {
                                    const updatedEmails = formData.emails.filter(
                                      (_, index) => index !== i
                                    );
                                    setFormData({ ...formData, emails: updatedEmails });
                                  }}
                                >
                                  <svg width="20" height="22" viewBox="0 0 20 22" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M0.583008 4.69538H19.0887M17.0325 4.69538V19.0887C17.0325 20.1168 16.0044 21.1449 14.9763 21.1449H4.69538C3.66729 21.1449 2.63919 20.1168 2.63919 19.0887V4.69538M5.72347 4.69538V2.63919C5.72347 1.6111 6.75156 0.583008 7.77965 0.583008H11.892C12.9201 0.583008 13.9482 1.6111 13.9482 2.63919V4.69538M7.77966 9.83584V16.0044M11.892 9.83584V16.0044" stroke="#0C3155" stroke-width="1.16667" stroke-linecap="round" stroke-linejoin="round" />
                                  </svg>
                                </button>
                              </div>
                            ))}
                          </div>
                        </div>


                        <div className="col-12">
                          <div className="datafrm">
                            <label className="required">* Required fields</label>
                          </div>
                        </div>

                        <div className="col-12">
                          <div className="datafrmbtn">
                            <ul>
                              <li><button className="canselbtn">Cancel</button></li>
                              <li><button onClick={handleNext}>Save & Next</button></li>
                            </ul>
                          </div>
                        </div>
                      </>
                    )}

                    {currentStep === 2 && (
                      <>
                        <div className="col-lg-12 col-sm-12 col-12">
                          <div className="datafrm d-flex justify-content-between align-items-center">
                            <label>Step 2: Address Information</label>
                            <button
                              type="button"
                              className="add-btn"
                              onClick={() => {
                                setFormData({
                                  ...formData,
                                  addresses: [
                                    ...formData.addresses,
                                    {
                                      streetAddress: "",
                                      city: "",
                                      state: "",
                                      zipCode: "",
                                      addressType: "",
                                      startDate: "",
                                      endDate: ""
                                    }
                                  ]
                                });
                              }}
                            >
                              + Add Address
                            </button>
                          </div>
                        </div>

                        {formData.addresses.map((addr, index) => (
                          <div className="col-12">
                            <div className="row gx-2" key={index}>
                              {index > 0 && (
                                <div className="col-12 d-flex justify-content-end mt-4">
                                  <button
                                    style={{ color: "red" }}
                                    type="button"
                                    className="remove-btn"
                                    onClick={() => {
                                      const updated = formData.addresses.filter((_, i) => i !== index);
                                      setFormData({ ...formData, addresses: updated });
                                    }}
                                  >
                                    - Remove Address
                                  </button>
                                </div>
                              )}


                              <div className="col-12">
                                <div className="datafrm">
                                  <label>Street Address *</label>
                                  <input
                                    type="text"
                                    placeholder="Enter street address"
                                    value={addr.streetAddress}
                                    onChange={(e) => {
                                      const updated = [...formData.addresses];
                                      updated[index].streetAddress = e.target.value;
                                      setFormData({ ...formData, addresses: updated });
                                    }}
                                  />
                                </div>
                              </div>

                              <div className="col-lg-6 col-sm-6 col-12">
                                <div className="datafrm">
                                  <label>City</label>
                                  <input
                                    type="text"
                                    placeholder="Enter city"
                                    value={addr.city}
                                    onChange={(e) => {
                                      const updated = [...formData.addresses];
                                      updated[index].city = e.target.value;
                                      setFormData({ ...formData, addresses: updated });
                                    }}
                                  />
                                </div>
                              </div>

                              <div className="col-lg-6 col-sm-6 col-12">
                                <div className="datafrm">
                                  <label>State</label>
                                  <input
                                    type="text"
                                    placeholder="Enter state"
                                    value={addr.state}
                                    onChange={(e) => {
                                      const updated = [...formData.addresses];
                                      updated[index].state = e.target.value;
                                      setFormData({ ...formData, addresses: updated });
                                    }}
                                  />
                                </div>
                              </div>

                              <div className="col-lg-6 col-sm-6 col-12">
                                <div className="datafrm">
                                  <label>Zip Code</label>
                                  <input
                                    type="text"
                                    placeholder="Enter Zip Code"
                                    value={addr.zipCode}
                                    onChange={(e) => {
                                      const updated = [...formData.addresses];
                                      updated[index].zipCode = e.target.value;
                                      setFormData({ ...formData, addresses: updated });
                                    }}
                                  />
                                </div>
                              </div>

                              <div className="col-lg-6 col-sm-6 col-12">
                                <div className="datafrm">
                                  <label>Address Type</label>
                                  <CustomSelect
                                    value={addr.addressType || ""}
                                    name={`addressType_${index}`}
                                    options={[
                                      { label: "Home", value: "home" },
                                      { label: "Work", value: "work" },
                                      { label: "Temporary", value: "temporary" },
                                    ]}
                                    placeholder="Select Address Type"
                                    onChange={(e) => {
                                      const updated = [...formData.addresses];
                                      updated[index].addressType = e.target.value;
                                      setFormData({ ...formData, addresses: updated });
                                    }}
                                  />
                                </div>
                              </div>

                              <div className="col-lg-6 col-sm-6 col-12">
                                <div className="datafrm">
                                  <label>Start Date (YYYY-MM-DD) *</label>
                                  <div className="datafrminner">
                                    <svg width="16" height="18" viewBox="0 0 16 18" className="form-icon" fill="none" xmlns="http://www.w3.org/2000/svg">
                                      <path d="M4.62139 0.5V2.97412M11.2156 0.5V2.97412M0.912139 6.34725H14.9249M10.964 10.149H10.9714M10.964 12.6232H10.9714M7.91478 10.149H7.92218M7.91478 12.6232H7.92218M4.86398 10.149H4.87139M4.86398 12.6232H4.87139M15.337 5.8606V12.8706C15.337 15.3447 14.1006 16.9941 11.2156 16.9941H4.62139C1.73642 16.9941 0.5 15.3447 0.5 12.8706V5.8606C0.5 3.38647 1.73642 1.73706 4.62139 1.73706H11.2156C14.1006 1.73706 15.337 3.38647 15.337 5.8606Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>
                                    <input
                                      type="text"
                                      placeholder="2020-12-30"
                                      value={addr.startDate}
                                      onChange={(e) => {
                                        const updated = [...formData.addresses];
                                        updated[index].startDate = e.target.value;
                                        setFormData({ ...formData, addresses: updated });
                                      }}
                                    />
                                  </div>
                                </div>
                              </div>

                              <div className="col-lg-6 col-sm-6 col-12">
                                <div className="datafrm">
                                  <label>End Date (YYYY-MM-DD)</label>
                                  <div className="datafrminner">
                                    <svg width="16" height="18" viewBox="0 0 16 18" className="form-icon" fill="none" xmlns="http://www.w3.org/2000/svg">
                                      <path d="M4.62139 0.5V2.97412M11.2156 0.5V2.97412M0.912139 6.34725H14.9249M10.964 10.149H10.9714M10.964 12.6232H10.9714M7.91478 10.149H7.92218M7.91478 12.6232H7.92218M4.86398 10.149H4.87139M4.86398 12.6232H4.87139M15.337 5.8606V12.8706C15.337 15.3447 14.1006 16.9941 11.2156 16.9941H4.62139C1.73642 16.9941 0.5 15.3447 0.5 12.8706V5.8606C0.5 3.38647 1.73642 1.73706 4.62139 1.73706H11.2156C14.1006 1.73706 15.337 3.38647 15.337 5.8606Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>
                                    <input
                                      type="text"
                                      placeholder="Leave blank if current"
                                      value={addr.endDate}
                                      onChange={(e) => {
                                        const updated = [...formData.addresses];
                                        updated[index].endDate = e.target.value;
                                        setFormData({ ...formData, addresses: updated });
                                      }}
                                    />
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        ))}

                        <div className="col-12">
                          <div className="datafrm">
                            <label className="required">* Required fields</label>
                          </div>
                        </div>

                        <div className="col-12">
                          <div className="datafrmbtn">
                            <ul>
                              <li><button className="canselbtn" onClick={handlePrev}>Previous</button></li>
                              <li><button onClick={handleNext}>Next</button></li>
                            </ul>
                          </div>
                        </div>
                      </>
                    )}

                    {currentStep === 3 && (
                      <>
                        <div className="col-lg-12 col-sm-12 col-12">
                          <div className="datafrm d-flex justify-content-between align-items-center">
                            <label>Step 3: Employment History</label>
                            <button
                              type="button"
                              className="add-btn"
                              onClick={() => {
                                setFormData({
                                  ...formData,
                                  employmentHistory: [
                                    ...formData.employmentHistory,
                                    {
                                      empName: "",
                                      jobTitle: "",
                                      empAddress: "",
                                      zipCode: "",
                                      startDate: "",
                                      endDate: ""
                                    }
                                  ]
                                });
                              }}
                            >
                              + Add Employment
                            </button>
                          </div>
                        </div>

                        {formData.employmentHistory.map((job, index) => (
                          <div className="row gx-2" key={index}>

                            {index > 0 && (
                              <div className="col-12 d-flex justify-content-end mt-3">
                                <button
                                  type="button"
                                  style={{ color: "red" }}
                                  className="remove-btn"
                                  onClick={() => {
                                    const updated = formData.employmentHistory.filter((_, i) => i !== index);
                                    setFormData({ ...formData, employmentHistory: updated });
                                  }}
                                >
                                  - Remove Employment
                                </button>
                              </div>
                            )}

                            <div className="col-lg-6 col-sm-6 col-12">
                              <div className="datafrm">
                                <label>Employer Name *</label>
                                <input
                                  type="text"
                                  placeholder="Enter employer name"
                                  value={job.empName}
                                  onChange={(e) => {
                                    const updated = [...formData.employmentHistory];
                                    updated[index].empName = e.target.value;
                                    setFormData({ ...formData, employmentHistory: updated });
                                  }}
                                />
                              </div>
                            </div>

                            <div className="col-lg-6 col-sm-6 col-12">
                              <div className="datafrm">
                                <label>Job Title *</label>
                                <input
                                  type="text"
                                  placeholder="Enter job title"
                                  value={job.jobTitle}
                                  onChange={(e) => {
                                    const updated = [...formData.employmentHistory];
                                    updated[index].jobTitle = e.target.value;
                                    setFormData({ ...formData, employmentHistory: updated });
                                  }}
                                />
                              </div>
                            </div>

                            <div className="col-12">
                              <div className="datafrm">
                                <label>Employer Address</label>
                                <input
                                  type="text"
                                  placeholder="Enter employer address"
                                  value={job.empAddress}
                                  onChange={(e) => {
                                    const updated = [...formData.employmentHistory];
                                    updated[index].empAddress = e.target.value;
                                    setFormData({ ...formData, employmentHistory: updated });
                                  }}
                                />
                              </div>
                            </div>

                            <div className="col-lg-6 col-sm-6 col-12">
                              <div className="datafrm">
                                <label>Zip Code</label>
                                <input
                                  type="text"
                                  placeholder="Enter zip code"
                                  value={job.zipCode}
                                  onChange={(e) => {
                                    const updated = [...formData.employmentHistory];
                                    updated[index].zipCode = e.target.value;
                                    setFormData({ ...formData, employmentHistory: updated });
                                  }}
                                />
                              </div>
                            </div>

                            <div className="col-lg-6 col-sm-6 col-12">
                              <div className="datafrm">
                                <label>Start Date (YYYY-MM-DD) *</label>
                                <div className="datafrminner">
                                  <svg width="16" height="18" viewBox="0 0 16 18" className="form-icon" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M4.62139 0.5V2.97412M11.2156 0.5V2.97412M0.912139 6.34725H14.9249M10.964 10.149H10.9714M10.964 12.6232H10.9714M7.91478 10.149H7.92218M7.91478 12.6232H7.92218M4.86398 10.149H4.87139M4.86398 12.6232H4.87139M15.337 5.8606V12.8706C15.337 15.3447 14.1006 16.9941 11.2156 16.9941H4.62139C1.73642 16.9941 0.5 15.3447 0.5 12.8706V5.8606C0.5 3.38647 1.73642 1.73706 4.62139 1.73706H11.2156C14.1006 1.73706 15.337 3.38647 15.337 5.8606Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
                                  </svg>  
                                  <input
                                    type="text"
                                    placeholder="2020-12-30"
                                    value={job.startDate}
                                    onChange={(e) => {
                                      const updated = [...formData.employmentHistory];
                                      updated[index].startDate = e.target.value;
                                      setFormData({ ...formData, employmentHistory: updated });
                                    }}
                                  />
                                </div>
                              </div>
                            </div>

                            <div className="col-lg-6 col-sm-6 col-12">
                              <div className="datafrm">
                                <label>End Date (YYYY-MM-DD)</label>
                                <div className="datafrminner">
                                  <svg width="16" height="18" viewBox="0 0 16 18" className="form-icon" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M4.62139 0.5V2.97412M11.2156 0.5V2.97412M0.912139 6.34725H14.9249M10.964 10.149H10.9714M10.964 12.6232H10.9714M7.91478 10.149H7.92218M7.91478 12.6232H7.92218M4.86398 10.149H4.87139M4.86398 12.6232H4.87139M15.337 5.8606V12.8706C15.337 15.3447 14.1006 16.9941 11.2156 16.9941H4.62139C1.73642 16.9941 0.5 15.3447 0.5 12.8706V5.8606C0.5 3.38647 1.73642 1.73706 4.62139 1.73706H11.2156C14.1006 1.73706 15.337 3.38647 15.337 5.8606Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
                                  </svg>
                                  <input
                                    type="text"
                                    placeholder="Leave blank if current"
                                    value={job.endDate}
                                    onChange={(e) => {
                                      const updated = [...formData.employmentHistory];
                                      updated[index].endDate = e.target.value;
                                      setFormData({ ...formData, employmentHistory: updated });
                                    }}
                                  />
                                </div>
                              </div>
                            </div>
                          </div>
                        ))}

                        <div className="col-12">
                          <div className="datafrm">
                            <label className="required">* Required fields</label>
                          </div>
                        </div>

                        <div className="col-12">
                          <div className="datafrmbtn">
                            <ul>
                              <li><button className="canselbtn" onClick={handlePrev}>Previous</button></li>
                              <li><button onClick={handleNext}>Next</button></li>
                            </ul>
                          </div>
                        </div>
                      </>
                    )}


                    {currentStep === 4 && (
                      <>
                        <div className="col-lg-12 col-sm-12 col-12">
                          <div className="datafrm d-flex justify-content-between align-items-center">
                            <label>Step 4: Social Media Links</label>

                            <button
                              type="button"
                              className="add-btn"
                              onClick={() => {
                                setFormData({
                                  ...formData,
                                  socialMedia: [
                                    ...formData.socialMedia,
                                    { platform: "", url: "", notes: "" }
                                  ]
                                });
                              }}
                            >
                              + Add Social Profile
                            </button>
                          </div>
                        </div>
                        {formData.socialMedia.map((item, index) => (
                          <div className="row gx-2" key={index}>
                            {index > 0 && (
                              <div className="col-12 d-flex justify-content-end mt-3">
                                <button
                                  type="button"
                                  style={{ color: "red" }}
                                  className="remove-btn"
                                  onClick={() => {
                                    const updated = formData.socialMedia.filter((_, i) => i !== index);
                                    setFormData({ ...formData, socialMedia: updated });
                                  }}
                                >
                                  - Remove Social Profile
                                </button>
                              </div>
                            )}
                            <div className="col-lg-6 col-sm-6 col-12">
                              <div className="datafrm">
                                <label>Social Media Platform</label>
                                <input
                                  type="text"
                                  placeholder="Facebook / Twitter / Instagram"
                                  value={item.platform}
                                  onChange={(e) => {
                                    const updated = [...formData.socialMedia];
                                    updated[index].platform = e.target.value;
                                    setFormData({ ...formData, socialMedia: updated });
                                  }}
                                />
                              </div>
                            </div>
                            <div className="col-lg-6 col-sm-6 col-12">
                              <div className="datafrm">
                                <label>Profile URL</label>
                                <input
                                  type="text"
                                  placeholder="https://facebook.com/username"
                                  value={item.url}
                                  onChange={(e) => {
                                    const updated = [...formData.socialMedia];
                                    updated[index].url = e.target.value;
                                    setFormData({ ...formData, socialMedia: updated });
                                  }}
                                />
                              </div>
                            </div>

                            <div className="col-12">
                              <div className="datafrm">
                                <label>Analyst Comments</label>
                                <textarea
                                  placeholder="Enter analyst observations or notes about this social media account..."
                                  value={item.analystComments}
                                  onChange={(e) => {
                                    const updated = [...formData.socialMedia];
                                    updated[index].analystComments = e.target.value;
                                    setFormData({ ...formData, socialMedia: updated });
                                  }}
                                ></textarea>
                              </div>
                            </div>
                          </div>
                        ))}

                        <div className="col-12">
                          <div className="datafrmbtn">
                            <ul>
                              <li><button className="canselbtn" onClick={handlePrev}>Previous</button></li>
                              <li><button onClick={handleNext}>Next</button></li>
                            </ul>
                          </div>
                        </div>
                      </>
                    )}

                    {currentStep === 5 && (
                      <>
                        <div className="col-lg-12 col-sm-12 col-12">
                          <div className="datafrm">
                            <label>Step 5: Additional Notes</label>
                          </div>
                        </div>

                        <div className="col-12">
                          <div className="datafrm">
                            <label>Notes</label>
                            <textarea
                              name="notes"
                              placeholder="Enter any additional notes or comments about this juror..."
                              value={formData.notes}
                              onChange={handleInput}
                            ></textarea>
                          </div>
                        </div>

                        <div className="col-12">
                          <div className="datafrmbtn">
                            <ul>
                              <li>
                                <button className="canselbtn" onClick={handlePrev}>
                                  Previous
                                </button>
                              </li>
                              <li>
                                <button onClick={handleAddJuror}>
                                  Add Juror
                                </button>
                              </li>
                            </ul>
                          </div>
                        </div>
                      </>
                    )}

                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
