"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { useBibliographyControllerListBibliographyV1 } from "@/api/user/practitioner-bibliography/practitioner-bibliography";
import type { BibliographyControllerListBibliographyV1200Item } from "@/api/user/generated.schemas";

type BibliographyEntry = BibliographyControllerListBibliographyV1200Item;

type SortField = "pdf_file_name" | "citation" | "annotation" | null;
type SortOrder = "asc" | "desc";

const TableRowSkeleton = () => (
  <tr className="border-b border-gray-200 animate-pulse">
    <td className="px-4 py-3 border-r border-gray-200"><div className="h-4 w-40 bg-gray-200 rounded" /></td>
    <td className="px-4 py-3 border-r border-gray-200">
      <div className="h-4 w-72 bg-gray-200 rounded mb-1.5" />
      <div className="h-3 w-48 bg-gray-200 rounded" />
    </td>
    <td className="px-4 py-3 border-r border-gray-200"><div className="h-4 w-56 bg-gray-200 rounded" /></td>
    <td className="px-4 py-3 w-16" />
  </tr>
);

export default function BibliographyPage() {
  const t = useTranslations("bibliography");

  const [sortField, setSortField] = useState<SortField>(null);
  const [sortOrder, setSortOrder] = useState<SortOrder>("asc");
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 10;

  const { data, isLoading, isError } = useBibliographyControllerListBibliographyV1();
  const entries: BibliographyEntry[] = (data as unknown as BibliographyEntry[]) ?? [];

  const getCitation = (e: BibliographyEntry) => e.apa_citation ?? (e as any).citation ?? "";

  const filtered = sortField
    ? [...entries].sort((a, b) => {
        let valA = "";
        let valB = "";
        if (sortField === "pdf_file_name") {
          valA = a.pdf_file_name ?? "";
          valB = b.pdf_file_name ?? "";
        } else if (sortField === "citation") {
          valA = getCitation(a);
          valB = getCitation(b);
        } else {
          valA = a.annotation ?? "";
          valB = b.annotation ?? "";
        }
        const cmp = valA.localeCompare(valB);
        return sortOrder === "asc" ? cmp : -cmp;
      })
    : entries;

  const totalEntries = filtered.length;
  const totalPages = Math.max(1, Math.ceil(totalEntries / pageSize));
  const pagedEntries = filtered.slice((currentPage - 1) * pageSize, currentPage * pageSize);

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortOrder((o) => (o === "asc" ? "desc" : "asc"));
    } else {
      setSortField(field);
      setSortOrder("asc");
    }
    setCurrentPage(1);
  };

  const getPageNumbers = () => {
    const pages: (number | string)[] = [];
    if (totalPages <= 7) {
      for (let i = 1; i <= totalPages; i++) pages.push(i);
    } else if (currentPage <= 3) {
      pages.push(1, 2, 3, "...", totalPages);
    } else if (currentPage >= totalPages - 2) {
      pages.push(1, "...", totalPages - 2, totalPages - 1, totalPages);
    } else {
      pages.push(1, "...", currentPage - 1, currentPage, currentPage + 1, "...", totalPages);
    }
    return pages;
  };

  const SortIcon = ({ field }: { field: SortField }) => (
    <svg
      className={`w-3 h-3 ml-1 inline-block transition-transform ${sortField === field && sortOrder === "desc" ? "rotate-180" : ""} ${sortField === field ? "text-[#3B9EC9]" : "text-gray-300"}`}
      fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}
    >
      <path strokeLinecap="round" strokeLinejoin="round" d="M5 15l7-7 7 7" />
    </svg>
  );

  const hasAnyPdf = entries.some((e) => !!e.pdf_url);
  const hasAnyDoi = entries.some((e) => !!(e as any).doi);

  return (
    <main className="pt-20 pb-8">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="mb-6">
          <h1 className="text-2xl sm:text-3xl font-semibold text-gray-900">{t("title")}</h1>
          <p className="mt-1 text-sm text-gray-500">
            <strong className="text-gray-700">{entries.length}</strong> {t("articles")}
          </p>
        </div>

        {/* Card */}
        <div className="bg-white rounded-2xl border border-gray-200 shadow-sm">
          {/* Filters */}
          <div className="px-5 py-3 border-b border-gray-200 flex items-center gap-2 flex-wrap">
            <span className="text-xs text-gray-400 mr-auto">
              {t("showing")} {totalEntries === 0 ? 0 : (currentPage - 1) * pageSize + 1}–{Math.min(currentPage * pageSize, totalEntries)} {t("of")} {totalEntries} {t("articles")}
            </span>
          </div>

          {/* Table */}
          <div className="mx-5 my-4 border border-gray-200 rounded-xl overflow-hidden">
            <div className="overflow-x-auto">
            <table className="w-full min-w-[600px] border-collapse">
              <thead>
                <tr className="bg-gray-50">
                  <th
                    className="text-left px-4 py-2.5 text-xs font-semibold text-gray-500 uppercase tracking-wide border-b border-r border-gray-200 cursor-pointer select-none hover:text-[#3B9EC9] w-44"
                    onClick={() => handleSort("pdf_file_name")}
                  >
                    {t("colFileName")} <SortIcon field="pdf_file_name" />
                  </th>
                  <th
                    className="text-left px-4 py-2.5 text-xs font-semibold text-gray-500 uppercase tracking-wide border-b border-r border-gray-200 cursor-pointer select-none hover:text-[#3B9EC9]"
                    onClick={() => handleSort("citation")}
                  >
                    {t("colCitation")} <SortIcon field="citation" />
                  </th>
                  <th
                    className="text-left px-4 py-2.5 text-xs font-semibold text-gray-500 uppercase tracking-wide border-b border-r border-gray-200 cursor-pointer select-none hover:text-[#3B9EC9]"
                    onClick={() => handleSort("annotation")}
                  >
                    {t("colAnnotation")} <SortIcon field="annotation" />
                  </th>
                  {hasAnyDoi && (
                    <th className="text-center px-4 py-2.5 text-xs font-semibold text-gray-500 uppercase tracking-wide border-b border-r border-gray-200 w-16">DOI</th>
                  )}
                  {hasAnyPdf && (
                    <th className="text-center px-4 py-2.5 text-xs font-semibold text-gray-500 uppercase tracking-wide border-b border-gray-200 w-16">{t("colAction")}</th>
                  )}
                </tr>
              </thead>
              <tbody>
                {isLoading ? (
                  <>
                    <TableRowSkeleton />
                    <TableRowSkeleton />
                    <TableRowSkeleton />
                    <TableRowSkeleton />
                    <TableRowSkeleton />
                  </>
                ) : isError ? (
                  <tr>
                    <td colSpan={3 + (hasAnyDoi ? 1 : 0) + (hasAnyPdf ? 1 : 0)} className="px-5 py-12 text-center text-gray-500 text-sm">
                      {t("loadError")}
                    </td>
                  </tr>
                ) : pagedEntries.length === 0 ? (
                  <tr>
                    <td colSpan={3 + (hasAnyDoi ? 1 : 0) + (hasAnyPdf ? 1 : 0)} className="px-5 py-12 text-center text-gray-500 text-sm">
                      {t("noResults")}
                    </td>
                  </tr>
                ) : (
                  pagedEntries.map((entry, idx) => (
                    <tr key={entry.id ?? idx} className="border-b border-gray-200 hover:bg-gray-50/50 transition">
                      {/* File Name */}
                      <td className="px-4 py-3 border-r border-gray-200 w-44">
                        <p className="break-all text-xs" title={(entry as any).original_file_name || entry.pdf_file_name || ""}>
                          {(entry as any).original_file_name || entry.pdf_file_name || "—"}
                        </p>
                      </td>
                      {/* Citation — plain text, no hyperlinks */}
                      <td className="px-4 py-3 border-r border-gray-200 max-w-sm">
                        <p className="text-sm text-gray-800 leading-relaxed">
                          {getCitation(entry) || "—"}
                        </p>
                      </td>
                      {/* Annotation */}
                      <td className="px-4 py-3 border-r border-gray-200 max-w-sm">
                        <p className="text-sm text-gray-600 leading-relaxed">
                          {entry.annotation || "—"}
                        </p>
                      </td>
                      {/* DOI — only shown when dataset has any DOIs */}
                      {hasAnyDoi && (
                        <td className="px-4 py-3 border-r border-gray-200">
                          <div className="flex items-center justify-center">
                            {(entry as any).doi ? (
                              <a
                                href={(entry as any).doi}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="w-8 h-8 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition"
                                title="View DOI"
                              >
                                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
                                </svg>
                              </a>
                            ) : <span className="text-gray-400 text-sm">-</span>}
                          </div>
                        </td>
                      )}
                      {/* Action — only shown when dataset has any PDFs */}
                      {hasAnyPdf && (
                        <td className="px-4 py-3">
                          <div className="flex items-center justify-center">
                            {entry.pdf_url ? (
                              <button
                                onClick={() => window.open(entry.pdf_url, "_blank")}
                                className="w-8 h-8 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition cursor-pointer"
                                title={t("viewArticle")}
                              >
                                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                </svg>
                              </button>
                            ) : null}
                          </div>
                        </td>
                      )}
                    </tr>
                  ))
                )}
              </tbody>
            </table>
            </div>
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="px-5 py-4 border-t border-gray-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <button
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                </svg>
                {t("previous")}
              </button>
              <div className="flex items-center gap-1">
                {getPageNumbers().map((page, idx) =>
                  typeof page === "string" ? (
                    <span key={`ellipsis-${idx}`} className="px-2 text-gray-400">...</span>
                  ) : (
                    <button
                      key={page}
                      onClick={() => setCurrentPage(page)}
                      className={`w-8 h-8 rounded-lg text-sm font-medium ${currentPage === page ? "bg-gray-100 text-gray-900" : "text-gray-600 hover:bg-gray-50"}`}
                    >
                      {page}
                    </button>
                  )
                )}
              </div>
              <button
                onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                disabled={currentPage >= totalPages}
                className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {t("next")}
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                </svg>
              </button>
            </div>
          )}
        </div>
      </div>
    </main>
  );
}
