import { assetPath } from "../../utils/assetPath";

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

export default function CaseListOld() {
  const { profile } = useProfile();
  // const isAnalyst = profile?.role_names?.includes("Analyst");
  const isAnalyst = profile?.role_details?.[0]?.name?.includes("Analyst");
  const [cases, setCases] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [sortConfig, setSortConfig] = useState({
    key: "",
    direction: "asc",
  });

  const navigate = useNavigate();

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

  const fetchCases = async () => {
    setLoading(true);
    try {
      const { data } = await getCases();
      setCases(data || []);
    } catch (err) {
      toast.error("Failed to load cases");
    } finally {
      setLoading(false);
    }
  };

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

  // Simple client-side search
  // const filteredCases = cases.filter(
  //   (item) =>
  //     item.name.toLowerCase().includes(search.toLowerCase()) ||
  //     item.case_id.toLowerCase().includes(search.toLowerCase())
  // );

  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 fetchCases();
    } 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);
      }

      // Type
      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="Case List">
      <div className="pagerlink">
        <ul>
          <li>
            <Link href="/dashboard">Dashboard</Link>
          </li>
          <li>All Cases</li>
        </ul>
      </div>

      <div className="casestable">
        <div className="casesflter">
          <h2>Active Cases</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 ? (
            <p>Loading cases...</p>
          ) : (
            <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>
  );
}
