import React, { useEffect, useState, useCallback, useRef } from "react";
import Layout from "../../Layout";
import useNavigate from '@/hooks/useNavigate';
import { toast } from "react-toastify";
import { ClipLoader } from "react-spinners";
import { getAllJurors, deleteJuror, getAllJurorsAssigned } from "@/services/jurorsService";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import RunIdiReportModal from "@/components/admin/juror-management/RunIdiReportModal";
import EditJurorModal from "@/components/admin/case-management/edit-juror/EditJurorModal";

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

// Sort direction indicator component
const SortIcon = ({ column, sortConfig }) => {
  if (sortConfig.key !== column) {
    return (
      <span style={{ marginLeft: 4, opacity: 0.35, fontSize: 11 }}></span>
    );
  }
  return (
    <span style={{ marginLeft: 4, fontSize: 14, fontWeight: 600, color: "#0C3155" }}>
      {sortConfig.direction === "asc" ? "↑" : "↓"}
    </span>
  );
};

const JurorManagement = ({ isComprehensive }) => {
  const navigate = useNavigate();
  const searchParams = useSearchParams();

  const [jurors, setJurors] = useState([]);
  const [loading, setLoading] = useState(true);

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

  const [showIdiModal, setShowIdiModal] = useState(false);
  const [selectedJurorId, setSelectedJurorId] = useState(null);
  const [selectedCaseId, setSelectedCaseId] = useState(null);
  const [showEditModal, setShowEditModal] = useState(false);

  const debounceRef = useRef(null);
  const baseRoute = isComprehensive
    ? "/comprehensive-report"
    : "/juror-management";

  useEffect(() => {
    const currentPage = Number(searchParams.get("page")) || 1;
    setPage(currentPage);
  }, [searchParams]);

  const fetchJurors = 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;
    }

    try {
      const res = await getAllJurorsAssigned(params);
      const payload = res.data;

      const jurorData = payload?.results || payload?.data?.results || [];
      setJurors(jurorData);
      setTotalCount(payload?.total_count ?? payload?.count ?? 0);
    } catch (error) {
      toast.error("Failed to load jurors");
    } finally {
      setLoading(false);
    }
  }, [page, limit, search, sortConfig]);

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

  const changePage = (newPage) => {
    setPage(newPage);
    navigate(`${baseRoute}?page=${newPage}`);
  };

  const handleLimitChange = (val) => {
    setLimit(Number(val));
    changePage(1);
  };

  const handleSearchChange = (val) => {
    setSearch(val);
    changePage(1);
  };

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

  const formatText = (text) => {
    if (!text) return "---";
    return text
      .replace(/_/g, " ")
      .replace(/\b\w/g, (char) => char.toUpperCase());
  };

  const handleDelete = async (id) => {
    const confirmDelete = window.confirm(
      "Are you sure you want to delete this juror?"
    );
    if (!confirmDelete) return;
    try {
      await deleteJuror(id);
      toast.success("Juror deleted successfully");
      fetchJurors(page);
    } catch (error) {
      toast.error(
        error?.response?.data?.message || "Failed to delete juror"
      );
    }
  };

  const getStatusStyle = (status) => {
    const value = (status ?? "").trim().toLowerCase();
    switch (value) {
      case "available":
        return { color: "#15803d", backgroundColor: "#dcfce7", border: "1px solid #86efac" };
      case "busy":
        return { color: "#b45309", backgroundColor: "#fef3c7", border: "1px solid #fcd34d" };
      case "assigned":
        return { color: "#b91c1c", backgroundColor: "#fee2e2", border: "1px solid #fca5a5" };
      case "pending":
        return { color: "#92400e", backgroundColor: "#fef9c3", border: "1px solid #fde047" };
      case "unassigned":
        return { color: "#4b5563", backgroundColor: "#f3f4f6", border: "1px solid #d1d5db" };
      default:
        return { color: "#374151", backgroundColor: "#f3f4f6", border: "1px solid #d1d5db" };
    }
  };

  const thStyle = {
    cursor: "pointer",
    userSelect: "none",
    whiteSpace: "nowrap",
  };

  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 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();
  const handleCloseEditModal = () => {
    setShowEditModal(false);
    setSelectedJurorId(null);
    setSelectedCaseId(null);
  };
  return (
    <Layout
      title={isComprehensive ? "Comprehensive Report" : "Juror Management"}
    >

      {/* Top Header */}
      <div className="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <div className="pagerlink mb-0">
          <ul>
            <li>
              <Link href="/dashboard">Dashboard</Link>
            </li>
            <li>
              <Link href={baseRoute}>
                {isComprehensive ? "Comprehensive Report" : "Juror Management"}
              </Link>
            </li>
          </ul>
        </div>
      </div>

      <div className="casestable">
        <div className="casesflter">
          <h2>Juror List</h2>

          <div className="caseflter mt-3" style={{ display: "flex", alignItems: "center", gap: "12px" }}>

            {/* Search */}
            <div className="filtersrch">
              <input
                type="text"
                placeholder="Search by name, email, phone, juror number…"
                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>
            </div>
          </div>
        </div>

        <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 style={thStyle} onClick={() => handleSort("juror_number")}>
                    Juror Number
                    <SortIcon column="juror_number" sortConfig={sortConfig} />
                  </th>

                  <th style={thStyle} onClick={() => handleSort("name")}>
                    Juror Name
                    <SortIcon column="name" sortConfig={sortConfig} />
                  </th>

                  <th style={thStyle} onClick={() => handleSort("case_name")}>
                    Case Name
                    <SortIcon column="case_name" sortConfig={sortConfig} />
                  </th>

                  <th style={thStyle} onClick={() => handleSort("status")}>
                    Status
                    <SortIcon column="status" sortConfig={sortConfig} />
                  </th>

                  <th>Action</th>
                </tr>
              </thead>

              <tbody>
                {jurors.length > 0 ? (
                  jurors.map((item) => (
                    <tr key={item.id}>
                      <td>{item.juror_number}</td>

                      <td>
                        <div className="d-flex gap-2">
                          <span>
                            {item.first_name} {item.last_name}
                          </span>
                        </div>
                      </td>

                      <td>
                        <div className="d-flexd gap-2">
                          <span>{item.case_name}</span>
                        </div>
                      </td>

                      <td>
                        <span
                          style={{
                            ...getStatusStyle(item.status),
                            display: "inline-flex",
                            alignItems: "center",
                            justifyContent: "center",
                            padding: "4px 8px",
                            borderRadius: "30px",
                            fontSize: "13px",
                            minWidth: "100px",
                            textTransform: "capitalize",
                          }}
                        >
                          {formatText(item.status)}
                        </span>
                      </td>

                      <td>
                        <div
                          className="actindted"
                          style={{
                            display: "flex",
                            alignItems: "center",
                            gap: "8px",
                          }}
                        >
                          {/* View Report */}
                          <button
                            title="View Report"
                            onClick={() => navigate(`${baseRoute}/view/${item.id}`)}
                            style={{
                              width: "30px",
                              height: "30px",
                              borderRadius: "8px",
                              border: "1px solid #3b82f6",
                              color: "#3b82f6",
                              background: "#eff6ff",
                              cursor: "pointer",
                            }}
                          >
                            <i className="bi bi-eye-fill"></i>
                          </button>

                          {/* Run IDI Report */}
                          <button
                            title="Run IDI Report"
                            onClick={() => {
                              setSelectedJurorId(item.id);
                              setShowIdiModal(true);
                            }}
                            style={{
                              width: "30px",
                              height: "30px",
                              borderRadius: "8px",
                              border: "1px solid #8b5cf6",
                              color: "#8b5cf6",
                              background: "#f5f3ff",
                              cursor: "pointer",
                            }}
                          >
                            <i className="bi bi-file-earmark-bar-graph-fill"></i>
                          </button>

                          {/* Edit */}
                          {/* <button
                            title="Edit Juror"
                            onClick={() => {
                              if (!item.case_id) {
                                toast.error("This juror is not assigned to any case.");
                                return;
                              }

                              setSelectedJurorId(item.id);
                              setSelectedCaseId(item.case_id);
                              setShowEditModal(true);
                            }}
                            style={{
                              width: "30px",
                              height: "30px",
                              borderRadius: "8px",
                              border: "1px solid #10b981",
                              color: "#10b981",
                              background: "#ecfdf5",
                              cursor: "pointer",
                            }}
                          >
                            <i className="bi bi-pencil-fill"></i>
                          </button> */}

                          <button
                            title="Edit Juror"
                            onClick={() => {
                              if (!item.case_id) {
                                toast.error("This juror is not assigned to any case.");
                                return;
                              }

                              navigate(
                                `${baseRoute}/edit/${item.id}?caseId=${item.case_id}&page=${page}`
                              )
                            }}
                            style={{
                              width: "30px",
                              height: "30px",
                              borderRadius: "8px",
                              border: "1px solid #10b981",
                              color: "#10b981",
                              background: "#ecfdf5",
                              cursor: "pointer",
                            }}
                          >
                            <i className="bi bi-pencil-fill"></i>
                          </button>

                          {/* Social Links */}
                          <button
                            title="Social Links"
                            onClick={() => navigate(`${baseRoute}/social-links/${item.id}`)}
                            style={{
                              width: "30px",
                              height: "30px",
                              borderRadius: "8px",
                              border: "1px solid #f59e0b",
                              color: "#f59e0b",
                              background: "#fffbeb",
                              cursor: "pointer",
                            }}
                          >
                            <i className="bi bi-share-fill"></i>
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan="5" className="text-center">
                      No jurors 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} jurors`}
          </span>

          {totalPages > 1 && (
            <div style={{ display: "flex", alignItems: "center", gap: "4px" }}>
              <button
                onClick={() => changePage(1)}
                disabled={page === 1}
                style={pgBtn(page === 1)}
                title="First page"
              >«</button>
              <button
                onClick={() => changePage(Math.max(1, page - 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={() => changePage(p)}
                      style={pgBtn(false, p === page)}
                      title={`Page ${p}`}
                    >{p}</button>
                  </React.Fragment>
                );
              })}

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

              <button
                onClick={() => changePage(totalPages)}
                disabled={page === totalPages}
                style={pgBtn(page === totalPages)}
                title="Last page"
              >»</button>
            </div>
          )}
        </div>
      </div>
      {showIdiModal && (
        <RunIdiReportModal
          jurorId={selectedJurorId}
          isComprehensive={isComprehensive}
          onClose={() => setShowIdiModal(false)}
        />
      )}
      <EditJurorModal
        caseId={selectedCaseId}
        jurorId={selectedJurorId}
        open={showEditModal}
        // onClose={() => setShowEditModal(false)}
        onClose={handleCloseEditModal}
        onUpdated={() => fetchJurors(page)}
      />
    </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",
  };
}

export default JurorManagement;