import React, { useEffect, useState } from "react";
import { ClipLoader } from "react-spinners";
import useNavigate from "@/hooks/useNavigate";
import {
  getAllJurorsToCase,
  removeJurorFromCase,
} from "../../../../services/caseService";
import { toast } from "react-toastify";
import EditJurorModal from "../edit-juror/EditJurorModal";
import { assetPath } from "../../../../utils/assetPath";
import ViewJurorModal from "../view-juror/ViewJurorModal";
import { useProfile } from "@/context/ProfileContext";
import AddJurorModel from "./AddJurorModel";
import RunIdiReportModal from "@/components/admin/juror-management/RunIdiReportModal";
import JurorSocialLinksModal from "../JurorSocialLinksModal";

export default function ManageJurors({ data }) {
  const { profile } = useProfile();

  const isAnalyst = profile?.role_details?.[0]?.name?.includes("Analyst");
  const [loading, setLoading] = useState(true);
  const [jurors, setJurors] = useState([]);
  const navigate = useNavigate();
  const caseId = data?.id;
  const [selectedJurorId, setSelectedJurorId] = useState(null);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showViewModal, setShowViewModal] = useState(false);
  const [showAddJurorModal, setShowAddJurorModal] = useState(false);
  const [showIdiModal, setShowIdiModal] = useState(false);
  const [showSocialModal, setShowSocialModal] = useState(false);

  useEffect(() => {
    if (caseId) {
      setLoading(true);
      getAllJurorsToCase(caseId)
        .then((res) => {
          if (res.data?.jurors) {
            setJurors(res.data.jurors);
          } else {
            setJurors([]);
          }
        })
        .catch((err) => {
          console.error("Error fetching jurors:", err);
          setJurors([]);
        })
        .finally(() => setLoading(false));
    }
  }, [caseId]);

  const handleDelete = (caseJurorId) => {
    if (
      !window.confirm(
        "Are you sure you want to remove this juror from the case?",
      )
    )
      return;

    removeJurorFromCase(caseId, caseJurorId)
      .then(() => {
        setJurors((prevJurors) =>
          prevJurors.filter((j) => j.case_juror_id !== caseJurorId),
        );
        toast.success("Juror removed successfully!");
      })
      .catch((err) => {
        console.error("Error removing juror:", err);
        toast.error("Failed to remove juror. Please try again.");
      });
  };

  const formatStatus = (text) => {
    if (!text) return "";
    return text
      .split("_")
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
      .join(" ");
  };

  return (
    <>
      <div className="casestable">
        <div className="d-flex justify-content-end">
          <button
            type="button"
            className="adduser d-inline-flex text-nowrap"
            onClick={() => setShowAddJurorModal(true)}
          >
            <i>
              <img src={assetPath("/assets/images/plus_icn.png")} alt="+" />
            </i>
            <span>Add Juror</span>
          </button>
        </div>
        <div className="profilefrmhder">
          <h3>Current Case Jurors ({jurors.length})</h3>
          <p>
            Manage jurors currently assigned to this case. You can remove jurors
            or update their information.
          </p>
        </div>

        <div className="casestablelist">
          {loading ? (
            <div
              className="d-flex justify-content-center align-items-center"
              style={{ height: "100px" }}
            >
              <ClipLoader size={24} color="#0C3155" loading={loading} />
            </div>
          ) : (
            <table>
              <thead>
                <tr>
                  <th>Juror</th>
                  <th>Juror Name</th>
                  {/* <th>Occupation</th> */}
                  <th>Analyst</th>
                  <th>Status</th>
                  <th>Action</th>
                </tr>
              </thead>

              <tbody>
                {jurors.length > 0 ? (
                  jurors.map((juror) => (
                    <tr key={juror.id}>
                      <td
                        style={{ cursor: "pointer", color: "#007bff" }}
                        onClick={() => {
                          setSelectedJurorId(juror.id);
                          setShowEditModal(true);
                        }}
                      >
                        {juror.juror_number}
                      </td>
                      <td>{`${juror.last_name} ${juror.first_name} ${juror.middle_name}`}</td>
                      {/* <td>{juror.occupation || "N/A"}</td> */}
                      <td>{juror.analyst_name || "N/A"}</td>
                      <td>
                        <span
                          className={
                            juror.status === "unassigned"
                              ? "pndngmsg"
                              : juror.status === "in_process"
                                ? "prgresmsg"
                                : juror.status === "enriched"
                                  ? "archvedmsg"
                                  : juror.status === "rejected"
                                    ? "archvedmsg"
                                    : juror.status === "selected"
                                      ? "cmpltemsg"
                                      : juror.status === "complete"
                                        ? "cmpltemsg"
                                        : "pndngmsg"
                          }
                        >
                          <i>
                            <img
                              src={
                                juror.status === "unassigned"
                                  ? assetPath("/assets/images/pndingicn.png")
                                  : juror.status === "in_process"
                                    ? assetPath("/assets/images/progesicn.png")
                                    : juror.status === "enriched"
                                      ? assetPath(
                                        "/assets/images/archvedicn.png",
                                      )
                                      : juror.status === "rejected"
                                        ? assetPath(
                                          "/assets/images/archvedicn.png",
                                        )
                                        : juror.status === "selected"
                                          ? assetPath(
                                            "/assets/images/compleicn.png",
                                          )
                                          : juror.status === "complete"
                                            ? assetPath(
                                              "/assets/images/compleicn.png",
                                            )
                                            : assetPath(
                                              "/assets/images/pndingicn.png",
                                            )
                              }
                              alt=""
                            />
                          </i>
                          {formatStatus(juror.status)}
                        </span>
                      </td>
                      {/* <td>
                        <div className="actindted">
                          <div className="dropdown">
                            <button
                              className="dropdown-toggle"
                              type="button"
                              data-bs-toggle="dropdown"
                            >
                              <img
                                src={assetPath("/assets/images/dtedbig.png")}
                                alt=""
                              />
                            </button>

                            <ul className="dropdown-menu">
                              <li style={{ cursor: "pointer" }}>
                                <a
                                  onClick={() => {
                                    setSelectedJurorId(juror.id);
                                    setShowViewModal(true);
                                  }}
                                >
                                  <i>
                                    <img
                                      src={assetPath(
                                        "/assets/images/action_icn1.png",
                                      )}
                                      alt=""
                                    />
                                  </i>
                                  View
                                </a>
                              </li>
                              <li style={{ cursor: "pointer" }}>
                                <a
                                  onClick={() => {
                                    setSelectedJurorId(juror.id);
                                    setShowEditModal(true);
                                  }}
                                >
                                  <i>
                                    <img
                                      src={assetPath(
                                        "/assets/images/action_icn2.png",
                                      )}
                                      alt=""
                                    />
                                  </i>
                                  Edit
                                </a>
                              </li>

                              {!isAnalyst && (
                                <li style={{ cursor: "pointer" }}>
                                  <a
                                    onClick={() =>
                                      handleDelete(juror.case_juror_id)
                                    }
                                  >
                                    <i>
                                      <img
                                        src={assetPath(
                                          "/assets/images/dlt_icn.png",
                                        )}
                                        alt=""
                                      />
                                    </i>
                                    Delete
                                  </a>
                                </li>
                              )}
                            </ul>
                          </div>
                        </div>
                      </td> */}

                      <td>
                        <div
                          className="actindted"
                          style={{
                            display: "flex",
                            alignItems: "center",
                            gap: "8px",
                          }}
                        >
                          {/* View */}
                          <button
                            title="View Juror"
                            onClick={() => {
                              setSelectedJurorId(juror.id);
                              setShowViewModal(true);
                            }}
                            style={{
                              width: "30px",
                              height: "30px",
                              borderRadius: "8px",
                              border: "1px solid #3b82f6",
                              color: "#3b82f6",
                              background: "#eff6ff",
                              cursor: "pointer",
                            }}
                          >
                            <i className="bi bi-eye-fill"></i>
                          </button>

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

                          {/* Edit */}
                          <button
                            title="Edit Juror"
                            onClick={() => {
                              setSelectedJurorId(juror.id);
                              setShowEditModal(true);
                            }}
                            style={{
                              width: "30px",
                              height: "30px",
                              borderRadius: "8px",
                              border: "1px solid #10b981",
                              color: "#10b981",
                              background: "#ecfdf5",
                              cursor: "pointer",
                            }}
                          >
                            <i className="bi bi-pencil-fill"></i>
                          </button>

                          {/* Social Links */}
                          {/* <button
                            title="Social Links"
                            onClick={() => navigate(`/juror-management/social-links/${juror.id}`)}
                            style={{
                              width: "30px",
                              height: "30px",
                              borderRadius: "8px",
                              border: "1px solid #f59e0b",
                              color: "#f59e0b",
                              background: "#fffbeb",
                              cursor: "pointer",
                            }}
                          >
                            <i className="bi bi-share-fill"></i>
                          </button> */}
                          <button
                            title="Social Links"
                            onClick={() => {
                              setSelectedJurorId(juror.id);
                              setShowSocialModal(true);
                            }}
                            style={{
                              width: "30px",
                              height: "30px",
                              borderRadius: "8px",
                              border: "1px solid #f59e0b",
                              color: "#f59e0b",
                              background: "#fffbeb",
                              cursor: "pointer",
                            }}
                          >
                            <i className="bi bi-share-fill"></i>
                          </button>
                          {/* Delete (analyst hidden) */}
                          {!isAnalyst && (
                            <button
                              title="Remove Juror"
                              onClick={() => handleDelete(juror.case_juror_id)}
                              style={{
                                width: "30px",
                                height: "30px",
                                borderRadius: "8px",
                                border: "1px solid #ef4444",
                                color: "#ef4444",
                                background: "#fef2f2",
                                cursor: "pointer",
                              }}
                            >
                              <i className="bi bi-trash-fill"></i>
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={6} style={{ textAlign: "center" }}>
                      No jurors assigned to this case.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          )}
        </div>
        <EditJurorModal
          key={selectedJurorId}
          caseId={caseId}
          jurorId={selectedJurorId}
          open={showEditModal}
          onClose={() => setShowEditModal(false)}
          onUpdated={() => getAllJurorsToCase(caseId)}
        />
        <ViewJurorModal
          caseId={caseId}
          jurorId={selectedJurorId}
          open={showViewModal}
          onClose={() => setShowViewModal(false)}
          onUpdated={() => getAllJurorsToCase(caseId)}
        />
        {showAddJurorModal && (
          <AddJurorModel
            data={data}
            onClose={() => setShowAddJurorModal(false)}
            onSuccess={() => {
              getAllJurorsToCase(caseId).then((res) => {
                setJurors(res.data?.jurors || []);
              });
            }}
          />
        )}
        {showIdiModal && (
          <RunIdiReportModal
            jurorId={selectedJurorId}
            isComprehensive={false}
            onClose={() => setShowIdiModal(false)}
          />
        )}
        {showSocialModal && (
          <JurorSocialLinksModal
            jurorId={selectedJurorId}
            onClose={() => setShowSocialModal(false)}
          />
        )}
      </div>
    </>
  );
}
