import CustomSelect from "@/components/common/CustomSelect";
import {
  assignCaseAnalyst,
  assignCaseAttorney,
  getCaseAnalystAssignedList,
  getCaseAnalystSearch,
  getCaseAttorneySearch,
} from "@/services/caseService";
import { useParams } from "next/navigation";
import useNavigate from "@/hooks/useNavigate";
import React, { useEffect, useState } from "react";
import { toast } from "react-toastify";
import { useProfile } from "@/context/ProfileContext";
import AddTeamMemberModal from "./AddTeamMemberModal";
import { assetPath } from "@/utils/assetPath";
import AssignJurorsModal from "./AddJurorCountModel";

const AssigningAnalystAttorney = (caseData) => {
  const { profile } = useProfile();

  const isAnalyst = profile?.role_details?.[0]?.name?.includes("Analyst");
  const isAdmin = profile?.roles?.includes(5);

  const navigate = useNavigate();

  // Get caseId from URL
  const { id: caseId } = useParams();

  const [analyst, setAnalyst] = useState([]);
  const [analystSummary, setAnalystSummary] = useState([]);
  const [attorneys, setAttorneys] = useState([]);
  const [selectedAnalysts, setSelectedAnalysts] = useState([]);
  const [selectedAttorneys, setSelectedAttorneys] = useState([]);
  const [showAddMemberModal, setShowAddMemberModal] = useState(false);
  const [analystSearch, setAnalystSearch] = useState("");
  const [attorneySearch, setAttorneySearch] = useState("");
  const [loadingAnalyst, setLoadingAnalyst] = useState(false);
  const [loadingAttorney, setLoadingAttorney] = useState(false);
  const [removedAnalysts, setRemovedAnalysts] = useState([]);
  const [analystSummarySearch, setAnalystSummarySearch] = useState("");
  const [showAssignJurorModal, setShowAssignJurorModal] = useState(false);
  const [selectedAnalystId, setSelectedAnalystId] = useState(null);

  const canEditStatus =
    !isAnalyst ||
    Number(caseData?.data?.lead_consultant_id) === Number(profile?.id);

  const fetchAnalysts = async (search = "") => {
    setLoadingAnalyst(true);
    try {
      const response = await getCaseAnalystSearch(caseId, search);
      setAnalyst(response?.data?.results || []);
    } catch (error) {
      console.error("Failed to load analysts", error);
    }
    setLoadingAnalyst(false);
  };

  const fetchAnalystsSummary = async (search = "") => {
    setLoadingAnalyst(true);
    try {
      const response = await getCaseAnalystAssignedList(caseId, search);
      console.log(response.data);

      setAnalystSummary(response?.data?.data || []);
    } catch (error) {
      console.error("Failed to load analyst summary", error);
    } finally {
      setLoadingAnalyst(false);
    }
  };

  const fetchAttorneys = async (search = "") => {
    setLoadingAttorney(true);
    try {
      const response = await getCaseAttorneySearch(caseId, search);
      setAttorneys(response?.data?.results || []);
    } catch (error) {
      console.error("Failed to load attorneys", error);
    }
    setLoadingAttorney(false);
  };

  useEffect(() => {
    const delayDebounce = setTimeout(() => {
      fetchAnalysts(analystSearch);
    }, 500); // 500ms delay

    return () => clearTimeout(delayDebounce);
  }, [analystSearch]);

  useEffect(() => {
    const delayDebounce = setTimeout(() => {
      fetchAttorneys(attorneySearch);
    }, 500);

    return () => clearTimeout(delayDebounce);
  }, [attorneySearch]);

  useEffect(() => {
    const delayDebounce = setTimeout(() => {
      if (caseId) {
        fetchAnalystsSummary(analystSummarySearch);
      }
    }, 500);

    return () => clearTimeout(delayDebounce);
  }, [caseId, analystSummarySearch]);
  // useEffect(() => {
  //   if (caseId) {
  //     fetchAnalysts();
  //     fetchAttorneys();
  //   }
  // }, [caseId]);

  const handleAnalystCheckboxChange = (id) => {
    setSelectedAnalysts((prev) =>
      prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id],
    );

    setRemovedAnalysts((prev) =>
      prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id],
    );
  };

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

  const handleAssignAnalyst = async () => {
    if (!selectedAnalysts || selectedAnalysts.length === 0) {
      toast.warning("Please select at least one analyst");
      return;
    }
    try {
      const payload = {
        user_id: selectedAnalysts,
        case_id: Number(caseId),
      };

      await assignCaseAnalyst(payload);

      toast.success("Analyst assigned successfully");

      setAnalystSearch("");
      await fetchAnalysts("");
    } catch (error) {
      console.error(error);
      toast.error("Failed to assign analyst");
    }
  };

  const handleAssignAttorney = async () => {
    if (!selectedAttorneys || selectedAttorneys.length === 0) {
      toast.warning("Please select at least one attorney");
      return;
    }
    try {
      const payload = {
        user_id: selectedAttorneys,
        case_id: Number(caseId),
      };

      await assignCaseAttorney(payload);

      toast.success("Attorney assigned successfully");
      setAttorneySearch("");
      await fetchAttorneys("");
    } catch (error) {
      console.error(error);
      toast.error("Failed to assign attorney");
    }
  };

  useEffect(() => {
    if (analyst?.length) {
      const preSelected = analyst
        .filter((item) => item.assigned === 1)
        .map((item) => item.id);

      setSelectedAnalysts((prev) =>
        Array.from(new Set([...prev, ...preSelected])),
      );
    }
  }, [analyst]);

  useEffect(() => {
    if (attorneys?.length) {
      const preSelected = attorneys
        .filter((item) => item.assigned === 1)
        .map((item) => item.id);

      setSelectedAttorneys((prev) =>
        Array.from(new Set([...prev, ...preSelected])),
      );
    }
  }, [attorneys]);

  const handleMemberCreated = async () => {
    await fetchAnalysts();
    await fetchAttorneys();
  };

  const handleOpenAssignJurorModal = (item) => {
    const analystId = item?.analyst_id;

    if (!analystId) {
      console.log("Analyst item:", item);
      toast.error("Analyst ID is missing.");
      return;
    }

    setSelectedAnalystId(analystId);
    setShowAssignJurorModal(true);
  };

  return (
    <>
      <div className="row">
        <div className="d-flex justify-content-end mt-3">
          {isAdmin && (
            <button
              type="button"
              className="adduser d-inline-flex text-nowrap"
              onClick={() => setShowAddMemberModal(true)}
            >
              <i>
                <img src={assetPath("/assets/images/plus_icn.png")} alt="+" />
              </i>
              <span>Add Analyst</span>
            </button>
          )}
        </div>

        <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">
                <div className="d-flex flex-column justify-content-between align-items-start gap-2">
                  <div className="d-flex justify-content-between align-items-start w-100 gap-2">
                    <h4>
                      Case Analyst Summary ({analystSummary?.length || 0})
                    </h4>
                  </div>
                  <p>View analyst case summary and workload for this case.</p>
                </div>
              </div>
            </div>

            <input
              type="text"
              className="form-control mb-2"
              placeholder="Search Case Analyst..."
              value={analystSummarySearch}
              onChange={(e) => setAnalystSummarySearch(e.target.value)}
            />

            <div className="importedlistouter importednewlist importedlistoutertop">
              {analystSummary?.length === 0 ? (
                <div className="text-center py-3">
                  <p className="mb-0">
                    {analystSummarySearch
                      ? "No analyst summary found"
                      : "No data available"}
                  </p>
                </div>
              ) : (
                analystSummary.map((item) => (
                  <div className="importedlist" key={item.analyst_id}>
                    <div className="importedmediabx w-100">
                      <div className="importedmedia">
                        {item?.analyst_name
                          ?.split(" ")
                          ?.map((word) => word[0])
                          ?.join("")
                          ?.substring(0, 2)}
                      </div>

                      <div className="importedmediact w-100">
                        <h5>{item.analyst_name}</h5>
                        <p className="d-flex justify-content-between mb-1">
                          <span>Lead Cases</span>
                          <small>
                            {item.number_of_case_lead_by_analyst_count}
                          </small>
                        </p>
                        <p className="d-flex justify-content-between mb-1">
                          <span>Supported Cases</span>
                          <small>
                            {item.nuber_of_case_supported_by_analyst}
                          </small>
                        </p>
                        <p className="d-flex justify-content-between mb-1">
                          <span>Current Case Jurors</span>
                          <small>
                            {
                              item.juror_count_of_that_case_assiagned_with_respective_analyst
                            }
                          </small>
                        </p>
                        <p className="d-flex justify-content-between mb-1">
                          <span>Total Jurors</span>
                          <small>
                            {
                              item.all_juror_count_assigned_with_analyst_of_all_case
                            }
                          </small>
                        </p>
                        <div className="text-end pt-2">
                          <button
                            type="button"
                            className="theme-btn"
                            onClick={() => handleOpenAssignJurorModal(item)}
                          >
                            Add Juror
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        </div>

        {/* Analyst */}
        <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">
                <div className="d-flex flex-column justify-content-between align-items-start gap-2">
                  <div className="d-flex justify-content-between align-items-start w-100 gap-2">
                    <h4>Available Analyst ({analyst?.length || 0})</h4>
                    <div className="d-inline-flex gap-2">
                      <div class="statusbx">
                        <span
                          class="status-dot"
                          style={{ background: "#2ecc71" }}
                        ></span>
                        <span>Available</span>
                      </div>
                      <div class="statusbx">
                        <span
                          class="status-dot"
                          style={{ background: "#dc3545" }}
                        ></span>
                        <span>Busy</span>
                      </div>
                    </div>
                  </div>
                  <p>
                    Select analysts from the available pool to add to this case.
                  </p>
                </div>
              </div>
            </div>
            <input
              type="text"
              className="form-control mb-2"
              placeholder="Search Analyst..."
              value={analystSearch}
              onChange={(e) => setAnalystSearch(e.target.value)}
            />

            <div className="importedlistouter importednewlist">
              {analyst?.length === 0 ? (
                <div className="text-center py-3">
                  <p className="mb-0">
                    {analystSearch ? "No analyst found" : "No data available"}
                  </p>
                </div>
              ) : (
                analyst?.map((item) => (
                  <div
                    className="importedlist"
                    key={item.id}
                    onClick={() => {
                      if (item.status !== "busy") {
                        handleAnalystCheckboxChange(item.id);
                      }
                    }}
                    style={{
                      cursor:
                        item.status === "busy" ? "not-allowed" : "pointer",
                    }}
                  >
                    <div className="form-check">
                      <input
                        className="form-check-input"
                        type="checkbox"
                        disabled={item.status == "busy"}
                        checked={selectedAnalysts.includes(item.id)}
                        onChange={() => handleAnalystCheckboxChange(item.id)}
                        onClick={(e) => e.stopPropagation()} // 🔥 REQUIRED
                      />
                    </div>

                    <div className="importedmediabx">
                      {/* <div className="importedmedia">
                        {item?.name
                          ?.split(" ")
                          ?.map((word) => word[0])
                          ?.join("")
                          ?.substring(0, 2)}

                        <p
                          className={`busyandavailable ${item.status?.toLowerCase() === "available"
                            ? "bg-success"
                            : item.status?.toLowerCase() === "busy"
                              ? "bg-danger"
                              : ""
                            }`}
                        >
                        </p>
                      </div> */}

                      <div className="importedmediact">
                        {item.assigned === 1 && (
                          <span className="assign-badge align-self-start mb-2 left-0">
                            <svg
                              viewBox="0 0 11 11"
                              fill="none"
                              xmlns="http://www.w3.org/2000/svg"
                            >
                              <g clip-path="url(#clip0_90_1157)">
                                <path
                                  d="M5.4949 5.24663C6.64411 5.24663 7.57573 4.31501 7.57573 3.16579C7.57573 2.01658 6.64411 1.08496 5.4949 1.08496C4.34568 1.08496 3.41406 2.01658 3.41406 3.16579C3.41406 4.31501 4.34568 5.24663 5.4949 5.24663Z"
                                  fill="white"
                                />
                                <path
                                  d="M3.66442 8.14357C3.67078 7.97451 3.72711 7.81112 3.8263 7.67407C3.92549 7.53702 4.06308 7.43245 4.22169 7.37358C4.3803 7.31472 4.5528 7.3042 4.71739 7.34336C4.88198 7.38251 5.03126 7.46958 5.14637 7.59357L6.32581 8.86162L8.41581 6.53023C7.55256 5.95472 6.53517 5.6543 5.49776 5.66857C4.77814 5.65037 4.06326 5.79004 3.4034 6.07774C2.74354 6.36543 2.15471 6.79419 1.67831 7.33384C1.63801 7.38757 1.61654 7.45308 1.6172 7.52023V9.16718C1.61713 9.32613 1.67899 9.47885 1.78966 9.59294C1.90033 9.70704 2.0511 9.77352 2.20998 9.77829H4.82859L3.89054 8.76996C3.81289 8.68596 3.75287 8.58725 3.71403 8.47966C3.6752 8.37208 3.65833 8.25779 3.66442 8.14357Z"
                                  fill="white"
                                />
                                <path
                                  d="M8.78722 9.77758C8.9461 9.77281 9.09687 9.70633 9.20754 9.59223C9.31821 9.47814 9.38007 9.32542 9.38 9.16647V8.01758L7.8125 9.77758H8.78722Z"
                                  fill="white"
                                />
                                <path
                                  d="M10.3172 5.6892C10.2872 5.6621 10.2521 5.64122 10.214 5.62777C10.1759 5.61432 10.1355 5.60856 10.0952 5.61084C10.0548 5.61311 10.0153 5.62337 9.97894 5.64101C9.94257 5.65866 9.91007 5.68335 9.88332 5.71364L6.33276 9.68587L4.74387 7.97781C4.71779 7.94731 4.68596 7.92225 4.65019 7.90406C4.61443 7.88586 4.57542 7.87489 4.53542 7.87177C4.49541 7.86865 4.45518 7.87344 4.41702 7.88587C4.37887 7.89829 4.34353 7.91812 4.31304 7.9442C4.2844 7.9726 4.26167 8.0064 4.24616 8.04363C4.23064 8.08087 4.22266 8.12081 4.22266 8.16114C4.22266 8.20148 4.23064 8.24142 4.24616 8.27865C4.26167 8.31589 4.2844 8.34968 4.31304 8.37809L6.35415 10.5781L10.3386 6.11087C10.39 6.05133 10.4164 5.97428 10.4124 5.89574C10.4085 5.81721 10.3743 5.74323 10.3172 5.6892Z"
                                  fill="white"
                                />
                              </g>
                              <defs>
                                <clipPath id="clip0_90_1157">
                                  <rect width="11" height="11" fill="white" />
                                </clipPath>
                              </defs>
                            </svg>
                            <span>Assigned</span>
                          </span>
                        )}
                        <h5 className="d-flex gap-2 flex-row justify-content-start">
                          <span
                            className={`busyandavailablecircle ${
                              item.status?.toLowerCase() === "available"
                                ? "bg-success"
                                : item.status?.toLowerCase() === "busy"
                                  ? "bg-danger"
                                  : ""
                            }`}
                          ></span>
                          <span>{item.name}</span>
                        </h5>
                        <p className="mb-0">
                          {item.organization_name || "No Organization"}
                        </p>
                        {/* <p className='mb-1'>{item.phone_number || "No Phone"}</p> */}
                        {/* <p className='mb-1 text-capitalize'>{item.status}</p> */}

                        {item.lead_analyst && (
                          <span className="fw-bold" style={{ color: "blue" }}>
                            {" "}
                            (Lead Analyst)
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>

            {canEditStatus && !(analystSearch && analyst?.length === 0) && (
              <div className="text-end">
                <button
                  className="adduser d-inline-flex gap-2 mt-3"
                  type="button"
                  onClick={handleAssignAnalyst}
                >
                  <span>Assign Analyst</span>
                </button>
              </div>
            )}
          </div>
        </div>

        {/* Attorney */}
        {/* <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 flex-wrap gap-2 justify-content-between mb-2">
              <div className="indicationbtx mb-0">
                <div className="indicationbtx">
                  <em
                    style={{
                      background: "#e3f1ff",
                      border: "1px solid #c3e1ff",
                    }}
                  ></em>
                  <span>Paralegal</span>
                </div>
                <div className="indicationbtx">
                  <em
                    style={{
                      background: "#fdf6ea",
                      border: "1px solid #efe3ce",
                    }}
                  ></em>
                  <span>Attorney</span>
                </div>
              </div>
              <div className="d-inline-flex gap-2 align-self-start">
                <div class="statusbx mt-0">
                  <span
                    class="status-dot"
                    style={{ background: "#2ecc71" }}
                  ></span>
                  <span>Available</span>
                </div>
                <div class="statusbx mt-0">
                  <span
                    class="status-dot"
                    style={{ background: "#dc3545" }}
                  ></span>
                  <span>Busy</span>
                </div>
              </div>
            </div>
            <div className="d-flex justify-content-between gap-2 mb-2 mb-md-3">
              <div className="w-100">
                <h4>
                  Available Attorney / Paralegal ({attorneys?.length || 0})
                </h4>
                <p>
                  Select attorneys from the available pool to add to this case.
                </p>
              </div>
            </div>
            <input
              type="text"
              className="form-control mb-2"
              placeholder="Search Attorney / Paralegal..."
              value={attorneySearch}
              onChange={(e) => setAttorneySearch(e.target.value)}
            />

            <div className="importedlistouter">
              {attorneys?.length === 0 ? (
                <div className="text-center py-3">
                  <p className="mb-0">
                    {attorneySearch
                      ? "No attorney / paralegal found"
                      : "No data available"}
                  </p>
                </div>
              ) : (
                attorneys?.map((item) => (
                  <div
                    className={`importedlist ${item.role_name == "Attorney" ? "attorney" : "para-legal"}`}
                    key={item.id}
                    onClick={() => {
                      if (item.status !== "busy") {
                        handleAttorneyCheckboxChange(item.id);
                      }
                    }}
                    style={{
                      cursor:
                        item.status === "busy" ? "not-allowed" : "pointer",
                    }}
                  >
                    <div className="form-check">
                      <input
                        className="form-check-input"
                        type="checkbox"
                        disabled={item.status == "busy"}
                        checked={selectedAttorneys.includes(item.id)}
                        onChange={() => handleAttorneyCheckboxChange(item.id)}
                        onClick={(e) => e.stopPropagation()} // 🔥 REQUIRED
                      />
                    </div>

                    <div className="importedmediabx">
                      <div className="importedmedia">
                        {item?.name
                          ?.split(" ")
                          ?.map((word) => word[0])
                          ?.join("")
                          ?.substring(0, 2)}

                        <p
                          className={`busyandavailable ${
                            item.status?.toLowerCase() === "available"
                              ? "bg-success"
                              : item.status?.toLowerCase() === "busy"
                                ? "bg-danger"
                                : ""
                          }`}
                        >
                        </p>
                      </div>

                      <div className="importedmediact">
                        <h5>{item.name}</h5>
                        <p className="mb-0">
                          {item.organization_name || "No Organization"}
                        </p>

                        {item.lead_attorney && (
                          <span className="fw-bold" style={{ color: "blue" }}>
                            {" "}
                            (Lead Attorney)
                          </span>
                        )}
                      </div>
                    </div>


                    {item.assigned === 1 && (
                      <span className="assign-badge">Assigned</span>
                    )}
                  </div>
                ))
              )}
            </div>

            {canEditStatus && !(attorneySearch && attorneys?.length === 0) && (
              <div className="text-end">
                <button
                  className="adduser d-inline-flex gap-2 mt-3"
                  type="button"
                  onClick={handleAssignAttorney}
                >
                  <span>Assign Attorney</span>
                </button>
              </div>
            )}
          </div>
        </div> */}
      </div>

      <AddTeamMemberModal
        show={showAddMemberModal}
        onClose={() => setShowAddMemberModal(false)}
        caseId={caseId}
        onCreated={handleMemberCreated}
      />
      {showAssignJurorModal && (
        <AssignJurorsModal
          caseId={caseId}
          analystId={selectedAnalystId}
          onClose={() => {
            setShowAssignJurorModal(false);
            setSelectedAnalystId(null);
          }}
          onSuccess={() => {
            fetchAnalystsSummary(analystSummarySearch);
          }}
        />
      )}
    </>
  );
};

export default AssigningAnalystAttorney;
