import React, { useEffect, useState, useCallback, useRef } from "react";
import Layout from "../../Layout";
// import {
//   getCases, getCaseCount, completedCases,
//   priorityCases, archivedCases, archiveCase,
// } from "@/services/caseService";
import { getCases, getCaseCount, archiveCase } from "@/services/caseService";
import { assetPath } from "../../utils/assetPath";
import { toast } from "react-toastify";
import { ClipLoader } from "react-spinners";
import useNavigate from "@/hooks/useNavigate";
import { useProfile } from "@/context/ProfileContext";
import Link from "next/link";
import { formatDate } from "@/utils/dateFormat";

const PAGE_SIZE_OPTIONS = [10, 25, 50, 100];

export default function Dashboard() {
  const { profile } = useProfile();
  const isAnalyst = profile?.role_details?.[0]?.name?.includes("Analyst");
  const isAdmin = profile?.role_details?.[0]?.name?.includes("Admin");
  const navigate = useNavigate();

  const [cases, setCases] = useState([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState("total");
  const [stats, setStats] = useState({
    total_cases: 0,
    completed_cases: 0,
    high_priority_cases: 0,
    archived_cases: 0,
    leading_case_count: 0,
    supported_case_count: 0,
    juror_case_count: 0,
  });

  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [search, setSearch] = useState("");
  const [sortConfig, setSortConfig] = useState({ key: "", direction: "asc" });

  const debounceRef = useRef(null);

  useEffect(() => {
    getCaseCount()
      .then((r) => setStats(r.data || {}))
      .catch(() => toast.error("Failed to load stats"));
  }, []);

  // const fetchCases = useCallback(async (overridePage = page) => {
  //   setLoading(true);

  //   const params = { page: overridePage, limit };
  //   if (search.trim()) params.search = search.trim();
  //   if (sortConfig.key) params.sortBy = sortConfig.key;
  //   if (sortConfig.key) params.order = sortConfig.direction;

  //   try {
  //     let res;
  //     switch (activeTab) {
  //       case "completed": res = await completedCases(params); break;
  //       case "priority": res = await priorityCases(params); break;
  //       case "archived": res = await archivedCases(params); break;
  //       default: res = await getCases(params); break;
  //     }

  //     const payload = res.data;
  //     let results = payload.results ?? [];

  //     // Active = client-side filter (waiting + in_progress) — no extra param
  //     if (activeTab === "active") {
  //       results = results.filter(c =>
  //         ["active", "waiting", "in_progress"].includes(c.case_status)
  //       );
  //     }

  //     // Leading / Supported — client-side filter by consultant id
  //     if (activeTab === "leading") {
  //       results = results.filter(
  //         c => Number(c.lead_consultant_id) === Number(profile?.id)
  //       );
  //     }
  //     if (activeTab === "supported") {
  //       results = results.filter(
  //         c => Number(c.lead_consultant_id) !== Number(profile?.id)
  //       );
  //     }

  //     setCases(results);
  //     setTotalCount(payload.total_count ?? payload.count ?? 0);
  //   } catch (err) {
  //     console.error("Failed to load cases:", err);
  //     toast.error("Failed to load case list");
  //   } finally {
  //     setLoading(false);
  //   }
  // }, [activeTab, page, limit, search, sortConfig, profile?.id]);

  // Re-fetch whenever dependencies change

  const fetchCases = useCallback(
    async (overridePage = page) => {
      setLoading(true);

      const params = {
        page: overridePage,
        limit,
      };

      if (search.trim()) {
        params.search = search.trim();
      }

      if (sortConfig.key) {
        params.sortBy = sortConfig.key;
        params.order = sortConfig.direction;
      }

      // Send the selected dashboard filter
      if (activeTab !== "total") {
        params.stats = activeTab;
      }

      try {
        const res = await getCases(params);

        const payload = res.data;

        setCases(payload.results ?? []);
        setTotalCount(payload.total_count ?? payload.count ?? 0);
      } catch (err) {
        console.error("Failed to load cases:", err);
        toast.error("Failed to load case list");
      } finally {
        setLoading(false);
      }
    },
    [activeTab, page, limit, search, sortConfig],
  );

  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => fetchCases(page), 400);
    return () => clearTimeout(debounceRef.current);
  }, [activeTab, page, limit, search, sortConfig]);

  // Reset to page 1 on tab / search / sort / limit change
  const resetPage = (fn) => {
    setPage(1);
    fn();
  };

  const handleTabClick = (tab) => resetPage(() => setActiveTab(tab));
  const handleLimitChange = (val) => resetPage(() => setLimit(Number(val)));
  const handleSearchChange = (val) => {
    setSearch(val);
    setPage(1);
  };

  const handleSort = (key) => {
    setSortConfig((prev) => ({
      key,
      direction: prev.key === key && prev.direction === "asc" ? "desc" : "asc",
    }));
    setPage(1);
  };

  const handleArchiveCase = async (caseId) => {
    if (!window.confirm("Are you sure you want to archive this case?")) return;
    setLoading(true);
    try {
      await archiveCase(caseId, { case_status: "archived" });
      toast.success("Case archived successfully");
      fetchCases(page);
      setStats((prev) => ({
        ...prev,
        total_cases: prev.total_cases - 1,
        archived_cases: prev.archived_cases + 1,
      }));
    } catch (err) {
      toast.error("Failed to archive case");
    } finally {
      setLoading(false);
    }
  };

  const formatStatus = (text) =>
    text
      .split("_")
      .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
      .join(" ");

  const sortArrow = (key) =>
    sortConfig.key === key
      ? sortConfig.direction === "asc"
        ? " ↑"
        : " ↓"
      : "";

  const getHeading = () =>
    ({
      total_cases: "Total Cases",
      active_cases: "Active Cases",
      completed_cases: "Completed Cases",
      priority_cases: "High Priority Cases",
      archived_cases: "Archived Cases",
      leading_cases: "Leading Cases",
      supported_cases: "Supported Cases",
    })[activeTab] ?? "Cases";

  const totalPages = Math.max(1, Math.ceil(totalCount / limit));
  const startItem = totalCount === 0 ? 0 : (page - 1) * limit + 1;
  const endItem = Math.min(page * limit, totalCount);

  const statTiles = [
    {
      tab: "total_cases",
      label: "Total Cases",
      count: stats.total_cases,
      show: true,
    },
    {
      tab: "active_cases",
      label: "Active Cases",
      count: stats.total_cases - stats.completed_cases - stats.archived_cases,
      show: true,
    },
    {
      tab: "completed_cases",
      label: "Completed Cases",
      count: stats.completed_cases,
      show: true,
    },
    {
      tab: "priority_cases",
      label: "High Priority",
      count: stats.high_priority_cases,
      show: true,
    },
    {
      tab: "archived_cases",
      label: "Archived Cases",
      count: stats.archived_cases,
      show: isAdmin,
    },
    {
      tab: "leading_cases",
      label: "Leading Cases",
      count: stats.leading_case_count,
      show: isAnalyst,
    },
    {
      tab: "supported_cases",
      label: "Supported Cases",
      count: stats.supported_case_count,
      show: isAnalyst,
    },
    {
      tab: "jurors",
      label: "Researching Jurors",
      count: stats.juror_case_count,
      noClick: true,
      show: isAnalyst,
    },
  ].filter((t) => t.show);

  const getPaginationPages = () => {
    if (totalPages <= 7)
      return Array.from({ length: totalPages }, (_, i) => i + 1);

    const pages = new Set([
      1,
      2,
      page - 1,
      page,
      page + 1,
      totalPages - 1,
      totalPages,
    ]);
    return [...pages]
      .filter((p) => p >= 1 && p <= totalPages)
      .sort((a, b) => a - b);
  };

  const paginationPages = getPaginationPages();

  return (
    <Layout title="Dashboard Overview">
      <div className="cuntingdshbrd">
        <div className="row">
          {statTiles.map((tile) => (
            <div className="col-3" key={tile.tab}>
              <div
                className={`cuntingnmber ${activeTab === tile.tab ? "active" : ""}`}
                onClick={() => !tile.noClick && handleTabClick(tile.tab)}
                style={{ cursor: tile.noClick ? "default" : "pointer" }}
              >
                <h4>{tile.count ?? 0}+</h4>
                <span>{tile.label}</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="casestable">
        {/* Header row: title + page-size + search */}
        <div className="casesflter">
          <h2>{getHeading()}</h2>

          <div
            className="caseflter"
            style={{ display: "flex", alignItems: "center", gap: "12px" }}
          >
            {/* Search */}
            <div className="filtersrch">
              <input
                type="text"
                placeholder="Search"
                value={search}
                onChange={(e) => handleSearchChange(e.target.value)}
              />
              <input type="submit" value="" />
            </div>

            {/* Page-size selector */}
            <div className="select_number">
              <label>Show</label>
              <select
                value={limit}
                onChange={(e) => handleLimitChange(e.target.value)}
              >
                {PAGE_SIZE_OPTIONS.map((n) => (
                  <option key={n} value={n}>
                    {n}
                  </option>
                ))}
              </select>
              {/* <span>
                entries
              </span> */}
            </div>
          </div>
        </div>

        {isAnalyst && (
          <div className="case-legend">
            <span className="legend-dot" />
            <span>I am leading</span>
          </div>
        )}

        {/* Table */}
        <div className="casestablelist">
          {loading ? (
            <div
              className="d-flex justify-content-center align-items-center"
              style={{ height: 100 }}
            >
              <ClipLoader size={24} color="#0C3155" loading />
            </div>
          ) : (
            <>
              <table>
                <thead>
                  <tr>
                    <th
                      onClick={() => handleSort("case_id")}
                      style={{ cursor: "pointer" }}
                    >
                      Case ID{sortArrow("case_id")}
                    </th>
                    <th
                      onClick={() => handleSort("name")}
                      style={{ width: 220, cursor: "pointer" }}
                    >
                      Case Name{sortArrow("name")}
                    </th>
                    <th
                      onClick={() => handleSort("case_type")}
                      style={{ cursor: "pointer" }}
                    >
                      Type
                    </th>
                    <th
                      onClick={() => handleSort("lead_consultant")}
                      style={{ cursor: "pointer" }}
                    >
                      Lead Analyst
                      <br />
                      Lead Attorney
                    </th>
                    <th
                      onClick={() => handleSort("priority")}
                      style={{ cursor: "pointer" }}
                    >
                      Priority
                    </th>
                    <th
                      onClick={() => handleSort("case_status")}
                      style={{ cursor: "pointer" }}
                    >
                      Status{sortArrow("case_status")}
                    </th>
                    <th
                      onClick={() => handleSort("deadline")}
                      style={{ cursor: "pointer" }}
                    >
                      Deadline{sortArrow("deadline")}
                    </th>
                    <th>Action</th>
                  </tr>
                </thead>

                <tbody>
                  {cases.length > 0 ? (
                    cases.map((item) => {
                      const isMyCase =
                        Number(item.lead_consultant_id) === Number(profile?.id);
                      return (
                        <tr
                          key={item.id}
                          className={isMyCase ? "my-lead-case" : ""}
                        >
                          <td>
                            <Link
                              href={`/case-list/view-case/${item.id}`}
                              className="text-nowrap case-id-link"
                              style={{ color: "#0C3155" }}
                            >
                              {item.case_id}
                            </Link>
                          </td>

                          <td>
                            <span>{item.name}</span>
                            <em>{item.court_name}</em>
                          </td>

                          <td>{item.case_type}</td>

                          <td>
                            {item.lead_consultant?.name || "N/A"}
                            <br />
                            {item.lead_attorney?.name || "N/A"}
                          </td>

                          <td>
                            <span
                              className={
                                item.priority === "high"
                                  ? "redmesg"
                                  : item.priority === "medium"
                                    ? "mdiamesg"
                                    : "outlnemsg"
                              }
                            >
                              {item.priority.charAt(0).toUpperCase() +
                                item.priority.slice(1)}
                            </span>
                          </td>

                          <td>
                            <span
                              className={
                                item.case_status === "waiting"
                                  ? "pndngmsg"
                                  : item.case_status === "active"
                                    ? "prgresmsg"
                                    : item.case_status === "archived" ||
                                        item.case_status === "inactive"
                                      ? "archvedmsg"
                                      : "cmpltemsg"
                              }
                            >
                              <i>
                                <img
                                  src={assetPath(
                                    item.case_status === "waiting"
                                      ? "/assets/images/pndingicn.png"
                                      : item.case_status === "active"
                                        ? "/assets/images/progesicn.png"
                                        : item.case_status === "archived" ||
                                            item.case_status === "inactive"
                                          ? "/assets/images/archvedicn.png"
                                          : "/assets/images/compleicn.png",
                                  )}
                                  alt=""
                                />
                              </i>
                              {formatStatus(item.case_status)}
                            </span>
                          </td>

                          <td>
                            <span className="text-nowrap">
                              {formatDate(item.deadline)}
                            </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">
                                  {!(
                                    isAnalyst &&
                                    item.case_status === "archived" &&
                                    Number(item.lead_consultant_id) !==
                                      Number(profile?.id)
                                  ) && (
                                    <li style={{ cursor: "pointer" }}>
                                      <a
                                        onClick={() =>
                                          navigate(
                                            `/case-list/view-case/${item.id}`,
                                          )
                                        }
                                      >
                                        <i>
                                          <img
                                            src={assetPath(
                                              "/assets/images/action_icn1.png",
                                            )}
                                            alt=""
                                          />
                                        </i>
                                        View Details
                                      </a>
                                    </li>
                                  )}
                                  {item.case_status !== "archived" &&
                                    (!isAnalyst ||
                                      Number(item.lead_consultant_id) ===
                                        Number(profile?.id)) && (
                                      <li style={{ cursor: "pointer" }}>
                                        <a
                                          onClick={() =>
                                            navigate(
                                              `/case-list/edit-case/${item.id}`,
                                            )
                                          }
                                        >
                                          <i>
                                            <img
                                              src={assetPath(
                                                "/assets/images/action_icn2.png",
                                              )}
                                              alt=""
                                            />
                                          </i>
                                          Edit Case
                                        </a>
                                      </li>
                                    )}
                                  {item.case_status !== "archived" &&
                                    (!isAnalyst ||
                                      Number(item.lead_consultant_id) ===
                                        Number(profile?.id)) && (
                                      <li style={{ cursor: "pointer" }}>
                                        <a
                                          className="text-red"
                                          onClick={() =>
                                            handleArchiveCase(item.id)
                                          }
                                        >
                                          Archive Case
                                        </a>
                                      </li>
                                    )}
                                </ul>
                              </div>
                            </div>
                          </td>
                        </tr>
                      );
                    })
                  ) : (
                    <tr>
                      <td
                        colSpan="8"
                        style={{
                          textAlign: "center",
                          padding: "32px 0",
                          color: "#888",
                        }}
                      >
                        No cases found
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </>
          )}
        </div>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            padding: "16px 4px",
            flexWrap: "wrap",
            gap: "12px",
          }}
        >
          <span style={{ fontSize: "13px", color: "#666" }}>
            {totalCount === 0
              ? ""
              : `Showing ${startItem}–${endItem} of ${totalCount} cases`}
          </span>
          {totalPages > 1 && (
            <div style={{ display: "flex", alignItems: "center", gap: "4px" }}>
              <button
                onClick={() => setPage(1)}
                disabled={page === 1}
                style={pgBtn(page === 1)}
                title="First page"
              >
                «
              </button>
              <button
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page === 1}
                style={pgBtn(page === 1)}
                title="Previous page"
              >
                ‹
              </button>

              {paginationPages.map((p, i) => {
                const prev = paginationPages[i - 1];
                const showEllipsis = prev && p - prev > 1;
                return (
                  <React.Fragment key={p}>
                    {showEllipsis && (
                      <span
                        style={{
                          padding: "0 4px",
                          color: "#999",
                          userSelect: "none",
                        }}
                      >
                        …
                      </span>
                    )}
                    <button
                      onClick={() => setPage(p)}
                      style={pgBtn(false, p === page)}
                      title={`Page ${p}`}
                    >
                      {p}
                    </button>
                  </React.Fragment>
                );
              })}

              {/* Next */}
              <button
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={page === totalPages}
                style={pgBtn(page === totalPages)}
                title="Next page"
              >
                ›
              </button>

              {/* Last */}
              <button
                onClick={() => setPage(totalPages)}
                disabled={page === totalPages}
                style={pgBtn(page === totalPages)}
                title="Last page"
              >
                »
              </button>
            </div>
          )}
        </div>
      </div>
    </Layout>
  );
}

// ── Pagination button style helper ────────────────────────────────────
function pgBtn(disabled = false, active = false) {
  return {
    minWidth: "34px",
    height: "34px",
    padding: "0 8px",
    border: `1px solid ${active ? "#0C3155" : "#dde1e7"}`,
    borderRadius: "6px",
    background: active ? "#0C3155" : disabled ? "#f5f6f8" : "#fff",
    color: active ? "#fff" : disabled ? "#bbb" : "#444",
    fontSize: "13px",
    fontWeight: active ? "600" : "400",
    cursor: disabled ? "not-allowed" : "pointer",
    transition: "all 0.15s",
    lineHeight: "1",
  };
}
