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

export default function DashboardOld() {
  const { profile } = useProfile();
  // const isAnalyst = profile?.role_names?.includes("Analyst");
  const isAnalyst = profile?.role_details?.[0]?.name?.includes("Analyst");
  const isAdmin = profile?.role_details?.[0]?.name?.includes("Admin");
  const [cases, setCases] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [activeTab, setActiveTab] = useState("total");
  const navigate = useNavigate();
  const [stats, setStats] = useState({
    total_cases: 0,
    completed_cases: 0,
    high_priority_cases: 0,
    archived_cases: 0,
    leading_case_count: 0,
  });
  const [sortConfig, setSortConfig] = useState({
    key: "",
    direction: "asc",
  });

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

  useEffect(() => {
    loadDefaultData();
  }, []);

  // Load initial dashboard
  const loadDefaultData = async () => {
    try {
      const [casesRes, statsRes] = await Promise.all([
        getCases(),
        getCaseCount(),
      ]);

      setCases(casesRes.data || []);
      setStats(statsRes.data || {});
    } catch (err) {
      console.error("Error loading dashboard:", err);
      toast.error("Failed to load dashboard");
    } finally {
      setLoading(false);
    }
  };

  // Handle tab change
  const handleTabClick = async (tab) => {
    setActiveTab(tab);
    setLoading(true);

    try {
      let res;

      switch (tab) {
        case "total":
          res = await getCases();
          setCases(res.data || []);
          break;

        case "active":
          // Active = waiting + in_progress
          res = await getCases();
          setCases(
            (res.data || []).filter((c) =>
              ["waiting", "in_progress"].includes(c.case_status),
            ),
          );
          break;

        case "completed":
          res = await completedCases();
          setCases(res.data || []);
          break;

        case "priority":
          res = await priorityCases();
          setCases(res.data || []);
          break;

        case "archived":
          res = await archivedCases();
          setCases(res.data || []);
          break;

        case "leading":
          res = await getCases();
          setCases(
            (res.data || []).filter(
              (c) => Number(c.lead_consultant_id) === Number(profile?.id),
            ),
          );
          break;

        case "supported":
          res = await getCases();
          setCases(
            (res.data || []).filter(
              (c) => Number(c.lead_consultant_id) != Number(profile?.id),
            ),
          );
          break;

        default:
          break;
      }
    } catch (err) {
      console.error("Failed to switch filter:", err);
      toast.error("Failed to load case list");
    }

    setLoading(false);
  };

  // Heading change
  const getHeading = () => {
    switch (activeTab) {
      case "total":
        return "Total Cases";
      case "active":
        return "Active Cases";
      case "completed":
        return "Completed Cases";
      case "priority":
        return "High Priority Cases";
      case "archived":
        return "Archived Cases";
      case "leading":
        return "Leading Cases";
      case "supported":
        return "Supported Cases";
      case "jurrors":
        return "Assign Jurrors";
      default:
        return "Cases";
    }
  };

  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");
      await loadDefaultData();

      // setCases((prevCases) => prevCases.filter((c) => c.id !== caseId));

      // Update stats locally
      setStats((prev) => ({
        ...prev,
        total_cases: prev.total_cases - 1,
        archived_cases: prev.archived_cases + 1,
      }));
    } catch (err) {
      console.error("Failed to archive case:", err);
      toast.error("Failed to archive case");
    } finally {
      setLoading(false);
    }
  };
  const handleSort = (key) => {
    let direction = "asc";

    if (sortConfig.key === key && sortConfig.direction === "asc") {
      direction = "desc";
    }

    setSortConfig({ key, direction });
  };

  // const filteredCases = cases
  //   .filter(
  //     (item) =>
  //       item.name.toLowerCase().includes(search.toLowerCase()) ||
  //       item.case_id.toLowerCase().includes(search.toLowerCase())
  //   )
  //   .sort((a, b) => {
  //     if (!sortConfig.key) return 0;

  //     // ✅ Case ID (alphanumeric safe)
  //     if (sortConfig.key === "case_id") {
  //       return sortConfig.direction === "asc"
  //         ? a.case_id.localeCompare(b.case_id, undefined, { numeric: true, sensitivity: "base" })
  //         : b.case_id.localeCompare(a.case_id, undefined, { numeric: true, sensitivity: "base" });
  //     }

  //     // ✅ Status custom order
  //     if (sortConfig.key === "case_status") {
  //       const order = {
  //         waiting: 1,
  //         inactive: 2,
  //         active: 3,
  //         completed: 4,
  //         archived: 5,
  //       };

  //       return sortConfig.direction === "asc"
  //         ? (order[a.case_status] || 0) - (order[b.case_status] || 0)
  //         : (order[b.case_status] || 0) - (order[a.case_status] || 0);
  //     }

  //     // ✅ Case Name (string)
  //     if (sortConfig.key === "name") {
  //       return sortConfig.direction === "asc"
  //         ? a.name.localeCompare(b.name)
  //         : b.name.localeCompare(a.name);
  //     }

  //     return 0;
  //   });

  const filteredCases = cases
    .filter((item) => {
      const searchText = search.toLowerCase();

      return (
        item.name?.toLowerCase().includes(searchText) ||
        item.case_id?.toLowerCase().includes(searchText) ||
        item.lead_attorney?.name?.toLowerCase().includes(searchText) ||
        item.lead_consultant?.name?.toLowerCase().includes(searchText)
      );
    })
    .sort((a, b) => {
      if (!sortConfig.key) return 0;

      if (sortConfig.key === "case_id") {
        return sortConfig.direction === "asc"
          ? a.case_id.localeCompare(b.case_id, undefined, {
              numeric: true,
              sensitivity: "base",
            })
          : b.case_id.localeCompare(a.case_id, undefined, {
              numeric: true,
              sensitivity: "base",
            });
      }

      if (sortConfig.key === "case_status") {
        const order = {
          waiting: 1,
          inactive: 2,
          active: 3,
          completed: 4,
          archived: 5,
        };

        return sortConfig.direction === "asc"
          ? (order[a.case_status] || 0) - (order[b.case_status] || 0)
          : (order[b.case_status] || 0) - (order[a.case_status] || 0);
      }

      if (sortConfig.key === "name") {
        return sortConfig.direction === "asc"
          ? a.name.localeCompare(b.name)
          : b.name.localeCompare(a.name);
      }

      if (sortConfig.key === "case_type") {
        return sortConfig.direction === "asc"
          ? (a.case_type || "").localeCompare(b.case_type || "")
          : (b.case_type || "").localeCompare(a.case_type || "");
      }

      // Lead Analyst
      if (sortConfig.key === "lead_consultant") {
        return sortConfig.direction === "asc"
          ? (a.lead_consultant?.name || "").localeCompare(
              b.lead_consultant?.name || "",
            )
          : (b.lead_consultant?.name || "").localeCompare(
              a.lead_consultant?.name || "",
            );
      }

      // Lead Attorney
      if (sortConfig.key === "lead_attorney") {
        return sortConfig.direction === "asc"
          ? (a.lead_attorney?.name || "").localeCompare(
              b.lead_attorney?.name || "",
            )
          : (b.lead_attorney?.name || "").localeCompare(
              a.lead_attorney?.name || "",
            );
      }

      // Priority
      if (sortConfig.key === "priority") {
        const priorityOrder = {
          high: 1,
          medium: 2,
          low: 3,
        };

        return sortConfig.direction === "asc"
          ? (priorityOrder[a.priority] || 99) -
              (priorityOrder[b.priority] || 99)
          : (priorityOrder[b.priority] || 99) -
              (priorityOrder[a.priority] || 99);
      }

      // Deadline
      if (sortConfig.key === "deadline") {
        return sortConfig.direction === "asc"
          ? new Date(a.deadline) - new Date(b.deadline)
          : new Date(b.deadline) - new Date(a.deadline);
      }

      return 0;
    });

  return (
    <Layout title="Dashboard Overview">
      {/* Stats Boxes */}
      <div className="cuntingdshbrd">
        <div className="row">
          <div className="col-3">
            <div
              className={`cuntingnmber ${activeTab === "total" ? "active" : ""}`}
              onClick={() => handleTabClick("total")}
            >
              <h4>{stats.total_cases}+</h4>
              <span>Total Cases</span>
            </div>
          </div>

          <div className="col-3">
            <div
              className={`cuntingnmber ${activeTab === "active" ? "active" : ""}`}
              onClick={() => handleTabClick("active")}
            >
              <h4>
                {stats.total_cases -
                  stats.completed_cases -
                  stats.archived_cases}
                +
              </h4>
              <span>Active Cases</span>
            </div>
          </div>

          <div className="col-3">
            <div
              className={`cuntingnmber ${
                activeTab === "completed" ? "active" : ""
              }`}
              onClick={() => handleTabClick("completed")}
            >
              <h4>{stats.completed_cases}+</h4>
              <span>Completed Cases</span>
            </div>
          </div>

          <div className="col-3">
            <div
              className={`cuntingnmber ${
                activeTab === "priority" ? "active" : ""
              }`}
              onClick={() => handleTabClick("priority")}
            >
              <h4>{stats.high_priority_cases}+</h4>
              <span>High Priority</span>
            </div>
          </div>
          {isAdmin && (
            <div className="col-3">
              <div
                className={`cuntingnmber ${
                  activeTab === "archived" ? "active" : ""
                }`}
                onClick={() => handleTabClick("archived")}
              >
                <h4>{stats.archived_cases}+</h4>
                <span>Archived Cases</span>
              </div>
            </div>
          )}

          {isAnalyst && (
            <div className="col-3">
              <div
                className={`cuntingnmber ${activeTab === "leading" ? "active" : ""}`}
                onClick={() => handleTabClick("leading")}
              >
                <h4>{stats.leading_case_count}+</h4>
                <span>Leading Cases</span>
              </div>
            </div>
          )}

          {isAnalyst && (
            <div className="col-3">
              <div
                className={`cuntingnmber ${activeTab === "supported" ? "active" : ""}`}
                onClick={() => handleTabClick("supported")}
              >
                <h4>{stats.supported_case_count}+</h4>
                <span>Supported Cases</span>
              </div>
            </div>
          )}
          {isAnalyst && (
            <div className="col-3">
              <div
                className={`cuntingnmber ${activeTab === "supported" ? "active" : ""}`}
              >
                <h4>{stats.juror_case_count}+</h4>
                <span>Assign Jurrors</span>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Case Table */}
      <div className="casestable">
        <div className="casesflter">
          <h2>{getHeading()}</h2>

          <div className="caseflter">
            <div className="filtersrch">
              <input
                type="text"
                placeholder="Search"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
              />
              <input type="submit" value="" />
            </div>

            {/* <CustomSelect
              placeholder="Sort By"
              options={[
                { value: "1", label: "Option 1" },
                { value: "2", label: "Option 2" },
              ]}
            /> */}
          </div>
        </div>

        {isAnalyst && (
          <div className="case-legend">
            <span className="legend-dot"></span>
            <span>I am leading </span>
          </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
                    onClick={() => handleSort("case_id")}
                    style={{ cursor: "pointer" }}
                  >
                    Case ID{" "}
                    {sortConfig.key === "case_id"
                      ? sortConfig.direction === "asc"
                        ? "↑"
                        : "↓"
                      : ""}
                  </th>
                  <th
                    style={{ width: "220px", cursor: "pointer" }}
                    onClick={() => handleSort("name")}
                  >
                    Case Name{" "}
                    {sortConfig.key === "name"
                      ? sortConfig.direction === "asc"
                        ? "↑"
                        : "↓"
                      : ""}
                  </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{" "}
                    {sortConfig.key === "case_status"
                      ? sortConfig.direction === "asc"
                        ? "↑"
                        : "↓"
                      : ""}
                  </th>
                  <th
                    onClick={() => handleSort("deadline")}
                    style={{ cursor: "pointer" }}
                  >
                    Deadline
                  </th>
                  <th>Action</th>
                </tr>
              </thead>

              <tbody>
                {filteredCases.length > 0 ? (
                  filteredCases.map((item) => {
                    const isMyCase =
                      Number(item.lead_consultant_id) === Number(profile?.id);

                    return (
                      <tr
                        key={item.id}
                        className={isMyCase ? "my-lead-case" : ""}
                      >
                        {/* <td>
                        <span className="text-nowrap">{item.case_id}</span>
                      </td> */}

                        <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"
                                    ? "archvedmsg"
                                    : item.case_status === "inactive"
                                      ? "archvedmsg"
                                      : "cmpltemsg"
                            }
                          >
                            <i>
                              <img
                                src={
                                  item.case_status === "waiting"
                                    ? assetPath("/assets/images/pndingicn.png")
                                    : item.case_status === "active"
                                      ? assetPath(
                                          "/assets/images/progesicn.png",
                                        )
                                      : item.case_status === "archived"
                                        ? assetPath(
                                            "/assets/images/archvedicn.png",
                                          )
                                        : item.case_status === "inactive"
                                          ? assetPath(
                                              "/assets/images/archvedicn.png",
                                            )
                                          : assetPath(
                                              "/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">
                                {/* <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> */}

                                {!(
                                  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" }}>
                      No cases found
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </Layout>
  );
}
