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

const TABS = ["Basic Info", "Phones", "Emails", "Addresses", "Social Media"];

export default function EditJurorModalOld({ caseId, jurorId, open, onClose, onUpdated }) {
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState("Basic Info");
  const [formData, setFormData] = useState(null);

  useEffect(() => {
    if (open && caseId && jurorId) {
      setLoading(true);
      getJurorById(caseId, jurorId)
        .then((res) => {
          setFormData(res.data);
        })
        .catch(() => toast.error("Failed to load juror information"))
        .finally(() => setLoading(false));
    }
  }, [open, caseId, jurorId]);


  const handleInput = (field, value) => {
    setFormData((prev) => ({
      ...prev,
      [field]: value,
    }));
  };

  const handleSave = () => {
      setLoading(true);
      updateJuror(jurorId, formData)
          .then(() => {
              toast.success("Juror updated successfully");
              onUpdated();
              onClose();
          })
          .catch(() => toast.error("Failed to update juror"))
          .finally(() => setLoading(false));
  };

  if (!open) return null;

  return (
    <div className="modal-backdrop">
      <div className="edit-juror-modal">
        {loading ? (
          <div className="loader-section">
            <ClipLoader size={30} />
          </div>
        ) : (
          <>
            <div className="modal-header">
              <h3>Edit Juror</h3>
              <button onClick={onClose} className="close-btn">✕</button>
            </div>

            {/* Tabs */}
            <div className="tabs">
              {TABS.map((tab) => (
                <button
                  key={tab}
                  className={activeTab === tab ? "active" : ""}
                  onClick={() => setActiveTab(tab)}
                >
                  {tab}
                </button>
              ))}
            </div>

            {/* Tab Content */}
            <div className="modal-body">
              {formData && activeTab === "Basic Info" && (
                <div className="row tab-content">

                  <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.first_name || ""}
                        onChange={(e) => handleInput("first_name", e.target.value)}
                      />
                    </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.last_name || ""}
                        onChange={(e) => handleInput("last_name", e.target.value)}
                      />
                    </div>
                  </div>

                  <div className="col-lg-6 col-sm-6 col-12">
                    <div className="datafrm">
                      <label>Age *</label>
                      <input
                        type="text"
                        placeholder="Enter age"
                        value={formData.age || ""}
                        onChange={(e) => handleInput("age", e.target.value)}
                      />
                    </div>
                  </div>

                  <div className="col-lg-6 col-sm-6 col-12">
                    <div className="datafrm">
                      <label>Occupation *</label>
                      <input
                        type="text"
                        value={formData.employment_history?.[0]?.job_title || ""}
                        disabled
                      />
                    </div>
                  </div>

                  <div className="col-lg-12 col-sm-12 col-12">
                    <div className="datafrm">
                      <label>Notes</label>
                      <input
                        type="text"
                        placeholder="Enter notes"
                        value={formData.notes || ""}
                        onChange={(e) => handleInput("notes", e.target.value)}
                      />
                    </div>
                  </div>

                </div>
              )}


              {formData && activeTab === "Phones" && (
                <div className="row tab-content">

                  {formData.phone_numbers?.map((num, idx) => (
                    <div key={idx} className="col-lg-10 col-sm-10 col-10">
                      <div className="datafrm phone-item">
                        <label>Phone {idx + 1}</label>
                        <div className="phone-input-wrapper">
                          <input
                            type="text"
                            placeholder="Enter phone number"
                            value={num}
                            onChange={(e) => {
                              const updated = [...formData.phone_numbers];
                              updated[idx] = e.target.value;
                              handleInput("phone_numbers", updated);
                            }}
                          />
                          <button
                            className="delete-btn"
                            onClick={() =>
                              handleInput(
                                "phone_numbers",
                                formData.phone_numbers.filter((_, i) => i !== idx)
                              )
                            }
                          >
                            🗑
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}

                  <div className="col-12">
                    <button
                      className="add-btn"
                      onClick={() =>
                        handleInput("phone_numbers", [...formData.phone_numbers, ""])
                      }
                    >
                      ➕ Add Phone
                    </button>
                  </div>

                </div>
              )}

              {formData && activeTab === "Emails" && (
                <div className="row tab-content">
                  <label>Email Addresses</label>
                  {formData.emails?.map((email, idx) => (
                    <div key={idx} className="col-lg-10 col-sm-10 col-10">
                      <div className="datafrm email-item">
                        <label>Email {idx + 1}</label>
                        <div className="email-input-wrapper">
                          <input
                            type="text"
                            placeholder="Enter email address"
                            value={email}
                            onChange={(e) => {
                              const updated = [...formData.emails];
                              updated[idx] = e.target.value;
                              handleInput("emails", updated);
                            }}
                          />
                          <button
                            className="delete-btn"
                            onClick={() =>
                              handleInput(
                                "emails",
                                formData.emails.filter((_, i) => i !== idx)
                              )
                            }
                          >
                            🗑
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}

                  <div className="col-12">
                    <button
                      className="add-btn"
                      onClick={() =>
                        handleInput("emails", [...formData.emails, ""])
                      }
                    >
                      ➕ Add Email
                    </button>
                  </div>

                </div>
              )}

              {formData && activeTab === "Addresses" && (
                <div className="row tab-content">
                  <label>Addresses</label>

                  {formData.addresses?.map((address, idx) => (
                    <div key={idx} className="col-12 address-block">

                      <div className="row">

                        <div className="col-lg-6 col-sm-6 col-12">
                          <div className="datafrm">
                            <label>Street Address</label>
                            <input
                              type="text"
                              placeholder="Enter street address"
                              value={address.street_address || ""}
                              onChange={(e) => {
                                const updated = [...formData.addresses];
                                updated[idx].street_address = e.target.value;
                                handleInput("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={address.city || ""}
                              onChange={(e) => {
                                const updated = [...formData.addresses];
                                updated[idx].city = e.target.value;
                                handleInput("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={address.state || ""}
                              onChange={(e) => {
                                const updated = [...formData.addresses];
                                updated[idx].state = e.target.value;
                                handleInput("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"
                              value={address.zip_code || ""}
                              onChange={(e) => {
                                const updated = [...formData.addresses];
                                updated[idx].zip_code = e.target.value;
                                handleInput("addresses", updated);
                              }}
                            />
                          </div>
                        </div>

                        <div className="col-lg-6 col-sm-6 col-12">
                          <div className="datafrm">
                            <label>Start Date</label>
                            <input
                              type="date"
                              value={address.start_date || ""}
                              onChange={(e) => {
                                const updated = [...formData.addresses];
                                updated[idx].start_date = e.target.value;
                                handleInput("addresses", updated);
                              }}
                            />
                          </div>
                        </div>

                        <div className="col-lg-6 col-sm-6 col-12">
                          <div className="datafrm">
                            <label>End Date</label>
                            <input
                              type="date"
                              value={address.end_date || ""}
                              onChange={(e) => {
                                const updated = [...formData.addresses];
                                updated[idx].end_date = e.target.value;
                                handleInput("addresses", updated);
                              }}
                            />
                          </div>
                        </div>

                        {/* Delete Button */}
                        <div className="col-12">
                          <button
                            className="delete-btn"
                            onClick={() =>
                              handleInput(
                                "addresses",
                                formData.addresses.filter((_, i) => i !== idx)
                              )
                            }
                          >
                            🗑 Remove Address
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}

                  {/* Add New Empty Address */}
                  <div className="col-12">
                    <button
                      className="add-btn"
                      onClick={() =>
                        handleInput("addresses", [
                          ...formData.addresses,
                          {
                            street_address: "",
                            city: "",
                            state: "",
                            zip_code: "",
                            start_date: "",
                            end_date: ""
                          }
                        ])
                      }
                    >
                      ➕ Add Address
                    </button>
                  </div>
                </div>
              )}

              {formData && activeTab === "Social Media" && (
                <div className="row tab-content">
                  <label>Social Media</label>

                  {formData.social_media?.map((item, idx) => (
                    <div key={idx} className="col-12 social-block">

                      <div className="row">

                        {/* Platform */}
                        <div className="col-lg-6 col-sm-6 col-12">
                          <div className="datafrm">
                            <label>Platform</label>
                            <input
                              type="text"
                              placeholder="e.g. Facebook, LinkedIn"
                              value={item.platform || ""}
                              onChange={(e) => {
                                const updated = [...formData.social_media];
                                updated[idx].platform = e.target.value;
                                handleInput("social_media", updated);
                              }}
                            />
                          </div>
                        </div>

                        {/* URL */}
                        <div className="col-lg-6 col-sm-6 col-12">
                          <div className="datafrm">
                            <label>Profile URL</label>
                            <input
                              type="text"
                              placeholder="Enter profile URL"
                              value={item.url || ""}
                              onChange={(e) => {
                                const updated = [...formData.social_media];
                                updated[idx].url = e.target.value;
                                handleInput("social_media", updated);
                              }}
                            />
                          </div>
                        </div>

                        {/* Analyst Comments */}
                        <div className="col-12">
                          <div className="datafrm">
                            <label>Analyst Comments</label>
                            <textarea
                              placeholder="Any notes about this profile..."
                              value={item.analyst_comments || ""}
                              onChange={(e) => {
                                const updated = [...formData.social_media];
                                updated[idx].analyst_comments = e.target.value;
                                handleInput("social_media", updated);
                              }}
                            ></textarea>
                          </div>
                        </div>

                        {/* Delete Button */}
                        <div className="col-12">
                          <button
                            className="delete-btn"
                            onClick={() =>
                              handleInput(
                                "social_media",
                                formData.social_media.filter((_, i) => i !== idx)
                              )
                            }
                          >
                            🗑 Remove Social Link
                          </button>
                        </div>

                      </div>
                    </div>
                  ))}

                  {/* Add Button */}
                  <div className="col-12">
                    <button
                      className="add-btn"
                      onClick={() =>
                        handleInput("social_media", [
                          ...formData.social_media,
                          { platform: "", url: "", analyst_comments: "" }
                        ])
                      }
                    >
                      ➕ Add Social Link
                    </button>
                  </div>
                </div>
              )}
            </div>

            {/* Footer */}
            <div className="modal-footer">
              <button onClick={onClose} className="cancel-btn">Cancel</button>
              <button onClick={handleSave} className="save-btn">💾 Save Changes</button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
