import React, { useEffect, useState } from "react";
import CustomSelect from "@/components/common/CustomSelect";
import {
  caseAnalystList,
  getAllUnassignJurorsToCase,
  AssignJurorToAnalyst,
  UnassignJurorToAnalyst,
} from "@/services/caseService";
import { toast } from "react-toastify";

const ConfirmModal = ({ show, count, onConfirm, onCancel, loading }) => {
  if (!show) return null;

  return (
    <div
      className="modal fade show d-block"
      style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
      tabIndex="-1"
    >
      <div className="modal-dialog modal-dialog-centered">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">Confirm Unassign</h5>
            <button
              type="button"
              className="btn-close"
              onClick={onCancel}
              disabled={loading}
            />
          </div>
          <div className="modal-body">
            <p className="mb-0">
              Are you sure you want to unassign{" "}
              <strong>
                {count} juror{count !== 1 ? "s" : ""}
              </strong>{" "}
              from this analyst? This action cannot be undone.
            </p>
          </div>
          <div className="modal-footer">
            <button
              type="button"
              className="btn btn-secondary"
              onClick={onCancel}
              disabled={loading}
            >
              Cancel
            </button>
            <button
              type="button"
              className="btn btn-danger"
              onClick={onConfirm}
              disabled={loading}
            >
              {loading ? "Unassigning..." : "Yes, Unassign"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

const AssignJurorByAnalyst = ({ data }) => {
  const caseId = data?.id;

  const [analysts, setAnalysts] = useState([]);
  const [jurors, setJurors] = useState([]);
  const [selectedJurors, setSelectedJurors] = useState([]);
  const [selectedAnalystId, setSelectedAnalystId] = useState("");
  const [loading, setLoading] = useState(false);
  const [assigning, setAssigning] = useState(false);
  const [unassigning, setUnassigning] = useState(false);
  const [selectedUnassignJurors, setSelectedUnassignJurors] = useState([]);
  const [showConfirmModal, setShowConfirmModal] = useState(false);

  useEffect(() => {
    if (!caseId) return;
    fetchAnalysts();
    fetchJurors();
  }, [caseId]);

  useEffect(() => {
    setSelectedUnassignJurors([]);
  }, [selectedAnalystId]);

  const fetchAnalysts = async () => {
    try {
      setLoading(true);
      const res = await caseAnalystList(caseId);
      setAnalysts(res.data?.results ?? []);
    } catch (error) {
      console.error("Error fetching analysts:", error);
      setAnalysts([]);
    } finally {
      setLoading(false);
    }
  };

  const fetchJurors = async () => {
    try {
      const res = await getAllUnassignJurorsToCase(caseId);
      setJurors(res.data?.results ?? []);
    } catch (error) {
      console.error("Error fetching jurors:", error);
      setJurors([]);
    }
  };

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

  const handleUnassignSelection = (jurorId) => {
    setSelectedUnassignJurors((prev) =>
      prev.includes(jurorId)
        ? prev.filter((id) => id !== jurorId)
        : [...prev, jurorId],
    );
  };

  const handleAssignJurors = async () => {
    if (!selectedAnalystId) {
      toast.warn("Please select an analyst");
      return;
    }
    if (selectedJurors.length === 0) {
      toast.warn("Please select at least one juror");
      return;
    }

    try {
      setAssigning(true);
      await AssignJurorToAnalyst(caseId, {
        analyst_id: Number(selectedAnalystId),
        juror_ids: selectedJurors,
      });
      toast.success("Jurors assigned successfully");
      setSelectedJurors([]);
      fetchJurors();
      fetchAnalysts();
    } catch (error) {
      console.error(error);
      toast.error("Failed to assign jurors");
    } finally {
      setAssigning(false);
    }
  };

  const handleUnassignJurors = async () => {
    try {
      setUnassigning(true);
      await UnassignJurorToAnalyst(caseId, Number(selectedAnalystId), {
        data: { juror_ids: selectedUnassignJurors },
      });
      toast.success("Jurors unassigned successfully");
      setSelectedUnassignJurors([]);
      setShowConfirmModal(false);
      fetchJurors();
      fetchAnalysts();
    } catch (error) {
      console.error("Failed to unassign jurors:", error);
      toast.error("Failed to unassign jurors");
    } finally {
      setUnassigning(false);
    }
  };

  const analystOptions = analysts.map((a) => ({
    value: a.id,
    label: a.name,
  }));

  const selectedAnalyst =
    analysts.find((a) => a.id === Number(selectedAnalystId)) || null;

  const assignedJurors = selectedAnalyst?.juror ?? [];
  const allUnassignSelected =
    assignedJurors.length > 0 &&
    assignedJurors.every((j) => selectedUnassignJurors.includes(j.juror_id));

  const handleSelectAllUnassign = () => {
    if (allUnassignSelected) {
      setSelectedUnassignJurors([]);
    } else {
      setSelectedUnassignJurors(assignedJurors.map((j) => j.juror_id));
    }
  };

  return (
    <>
      <ConfirmModal
        show={showConfirmModal}
        count={selectedUnassignJurors.length}
        onConfirm={handleUnassignJurors}
        onCancel={() => setShowConfirmModal(false)}
        loading={unassigning}
      />

      <div className="casestable px-0">
        <div className="profilefrmhder">
          <h3>Assign Juror Under Case Analyst</h3>
          <p>
            Manage jurors currently assigned to this case. You can assign
            unassigned jurors to the selected analyst.
          </p>
        </div>

        <div className="row my-3">
          {/* ── Left Side ── */}
          <div className="col-xl-5 col-lg-5 col-sm-12 col-12 d-flex flex-column mt-3 mt-md-4">
            <CustomSelect
              name="analyst_id"
              value={selectedAnalystId}
              onChange={(e) => setSelectedAnalystId(e.target.value)}
              placeholder={loading ? "Loading analysts..." : "Select analyst"}
              options={analystOptions}
            />

            {selectedAnalyst && (
              <div className="casetabnx flex-grow mt-3">
                <div class="d-flex justify-content-between gap-2 mb-2 mb-md-3">
                  <div class="w-100">
                    <h4>{selectedAnalyst.name}</h4>
                  </div>
                </div>
                {/* Counts */}
                <div className="row gx-3 mb-3">
                  <div className="col-6">
                    <div className="counttx">
                      <h5>{selectedAnalyst.active_case_count}</h5>
                      <p>Active Cases</p>
                    </div>
                  </div>
                  <div className="col-6">
                    <div className="counttx">
                      <h5>{selectedAnalyst.total_juror_count}</h5>
                      <p>Total Jurors</p>
                    </div>
                  </div>
                </div>

                {/* Assigned jurors list with multi-select unassign */}
                <div className="d-flex justify-content-between align-items-center mb-2">
                  <h6 className="fw-semibold mb-0">Assigned Jurors</h6>
                  {assignedJurors.length > 0 && (
                    <div className="form-check mb-0">
                      <input
                        type="checkbox"
                        className="form-check-input"
                        id="select-all-unassign"
                        checked={allUnassignSelected}
                        onChange={handleSelectAllUnassign}
                      />
                      <label
                        className="form-check-label small"
                        htmlFor="select-all-unassign"
                      >
                        Select all
                      </label>
                    </div>
                  )}
                </div>

                {assignedJurors.length > 0 ? (
                  <>
                    <div
                      className="caseboxlistouter"
                      style={{ maxHeight: "260px", overflowY: "auto" }}
                    >
                      {assignedJurors.map((juror) => (
                        <div
                          key={juror.juror_id}
                          className="d-flex justify-content-between align-items-center importedlist"
                          onClick={() =>
                            handleUnassignSelection(juror.juror_id)
                          }
                          style={{ cursor: "pointer" }}
                        >
                          <div className="d-flex align-items-center importedmediabx w-100">
                            <div class="importedmedia">S</div>
                            <div className="importedmediact w-100">
                              <h5>{juror.full_name}</h5>
                              {juror.email && (
                                <p className="text-muted">{juror.email}</p>
                              )}
                            </div>
                            <input
                              type="checkbox"
                              className="form-check-input"
                              checked={selectedUnassignJurors.includes(
                                juror.juror_id,
                              )}
                              onChange={() =>
                                handleUnassignSelection(juror.juror_id)
                              }
                              onClick={(e) => e.stopPropagation()}
                            />
                          </div>
                          {/* <span className="badge bg-success">Assigned</span> */}
                        </div>
                      ))}
                    </div>

                    {selectedUnassignJurors.length > 0 && (
                      <div className="d-flex justify-content-end mt-2">
                        <button
                          className="btn btn-sm btn-outline-danger"
                          onClick={() => setShowConfirmModal(true)}
                        >
                          Unassign ({selectedUnassignJurors.length})
                        </button>
                      </div>
                    )}
                  </>
                ) : (
                  <p className="text-muted mb-0">
                    No jurors assigned to this analyst.
                  </p>
                )}
              </div>
            )}
          </div>

          {/* ── Right Side ── */}
          <div className="col-xl-7 col-lg-7 col-sm-12 col-12 mt-3 mt-md-4">
            <div className="casetabnx">
              <div class="d-flex justify-content-between gap-2 mb-2 mb-md-3">
                <div class="w-100">
                  <h4>Jurors</h4>
                </div>
              </div>
              {jurors.length === 0 ? (
                <p className="text-muted mb-0">No jurors found.</p>
              ) : (
                <>
                  <div className="caseboxlistouter assignrt">
                    {jurors.map((juror) => {
                      const jurorId = juror.juror_id ?? juror.id;
                      const isAssigned =
                        juror.status?.toLowerCase() === "assigned";

                      return (
                        <div
                          key={juror.id}
                          className="d-flex justify-content-between align-items-center importedlist"
                          onClick={() => {
                            if (!isAssigned) {
                              handleJurorSelection(jurorId);
                            }
                          }}
                          style={{
                            cursor: isAssigned ? "not-allowed" : "pointer",
                          }}
                        >
                          <div className="d-flex align-items-center importedmediabx w-100">
                            <div className="importedmedia">S</div>
                            <div className="importedmediact w-100">
                              <h5>
                                {juror.first_name} {juror.middle_name}{" "}
                                {juror.last_name}
                              </h5>
                              <p className="text-muted">
                                Juror No: {juror.juror_number}
                              </p>
                            </div>
                            <input
                              type="checkbox"
                              className="form-check-input"
                              checked={
                                isAssigned || selectedJurors.includes(jurorId)
                              }
                              disabled={isAssigned}
                              onChange={() => handleJurorSelection(jurorId)}
                              onClick={(e) => e.stopPropagation()}
                            />
                          </div>

                          {/* <span
                            className={`badge ${isAssigned
                                ? "bg-success"
                                : "bg-warning text-dark"
                              }`}
                          >
                            {isAssigned ? "Assigned" : "Unassigned"}
                          </span> */}
                        </div>
                      );
                    })}
                  </div>

                  <div className="d-flex justify-content-end">
                    <button
                      className="adduser d-inline-flex gap-2 mt-3"
                      type="button"
                      onClick={handleAssignJurors}
                    >
                      {assigning
                        ? "Assigning..."
                        : `Assign Jurors (${selectedJurors.length})`}
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default AssignJurorByAnalyst;
