"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { instance } from "@/config/axios";
import { useDocumentsControllerListDocumentsV1 } from "@/api/user/documents/documents";
import type { DocumentItem } from "@/api/user/generated.schemas";

const formatFileSize = (bytes: number): string => {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
};

const getFileTypeLabel = (fileType: string): string => {
  const lower = fileType.toLowerCase();
  if (lower.includes("pdf")) return "PDF";
  if (lower.includes("word") || lower.includes("doc")) return "DOC";
  return lower.split("/").pop()?.toUpperCase() ?? fileType.toUpperCase();
};

const FileTypeIcon = ({ fileType }: { fileType: string }) => {
  const label = getFileTypeLabel(fileType);
  if (label === "PDF") {
    return (
      <svg className="w-5 h-5 text-red-500" fill="currentColor" viewBox="0 0 24 24">
        <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8l-6-6z" />
        <path fill="white" d="M14 2v6h6" />
        <text x="4.5" y="18.5" fontSize="5.5" fill="white" fontWeight="bold" fontFamily="sans-serif">PDF</text>
      </svg>
    );
  }
  if (label === "DOC") {
    return (
      <svg className="w-5 h-5 text-blue-500" fill="currentColor" viewBox="0 0 24 24">
        <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8l-6-6z" />
        <path fill="white" d="M14 2v6h6" />
        <text x="4" y="18.5" fontSize="5.5" fill="white" fontWeight="bold" fontFamily="sans-serif">DOC</text>
      </svg>
    );
  }
  return (
    <svg className="w-5 h-5 text-gray-400" fill="currentColor" viewBox="0 0 24 24">
      <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8l-6-6z" />
      <path fill="white" d="M14 2v6h6" />
    </svg>
  );
};

const TableRowSkeleton = () => (
  <tr className="border-b border-gray-200 animate-pulse">
    <td className="px-5 py-4 border-r border-gray-200">
      <div className="flex items-center gap-3">
        <div className="w-9 h-9 rounded-xl bg-gray-200 flex-shrink-0" />
        <div>
          <div className="h-4 w-40 bg-gray-200 rounded mb-1.5" />
          <div className="h-3 w-16 bg-gray-200 rounded" />
        </div>
      </div>
    </td>
    <td className="px-5 py-4 border-r border-gray-200"><div className="h-4 w-20 bg-gray-200 rounded" /></td>
    <td className="px-5 py-4 border-r border-gray-200"><div className="h-4 w-14 bg-gray-200 rounded" /></td>
    <td className="px-5 py-4"><div className="h-4 w-20 bg-gray-200 rounded" /></td>
  </tr>
);

export default function DocumentsPage() {
  const t = useTranslations("practiceManager");
  const [searchTerm, setSearchTerm] = useState("");
  const [filterType, setFilterType] = useState<string>("all");
  const [viewingDoc, setViewingDoc] = useState<string | null>(null);
  const [downloadingDoc, setDownloadingDoc] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 10;

  const { data, isLoading, isError } = useDocumentsControllerListDocumentsV1({ limit: 100 });
  const documents: DocumentItem[] = (data?.data ?? []);

  const filteredDocs = documents
    .filter((doc) => {
      const matchesSearch = doc.title.toLowerCase().includes(searchTerm.toLowerCase());
      const matchesType =
        filterType === "all" ||
        (filterType === "pdf" && getFileTypeLabel(doc.file_type) === "PDF") ||
        (filterType === "doc" && getFileTypeLabel(doc.file_type) === "DOC");
      return matchesSearch && matchesType;
    })
    .sort((a, b) => {
      const aIsGuide = a.title.toLowerCase().includes("user guide") ? 0 : 1;
      const bIsGuide = b.title.toLowerCase().includes("user guide") ? 0 : 1;
      return aIsGuide - bIsGuide;
    });

  const totalDocs = filteredDocs.length;
  const totalPages = Math.max(1, Math.ceil(totalDocs / pageSize));
  const pagedDocs = filteredDocs.slice((currentPage - 1) * pageSize, currentPage * pageSize);

  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 handleView = async (doc: DocumentItem) => {
    setViewingDoc(doc.uuid);
    try {
      const res = await instance.get(`/v1/documents/${doc.file_name}`);
      const url = res.data.url;
      const isWord =
        doc.file_type.toLowerCase().includes("word") ||
        doc.file_type.toLowerCase().includes("msword") ||
        doc.file_name.toLowerCase().endsWith(".doc") ||
        doc.file_name.toLowerCase().endsWith(".docx");
      if (isWord) {
        const a = document.createElement("a");
        a.href = url;
        a.download = doc.file_name;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } else {
        window.open(url, "_blank");
      }
    } catch {
      // silent fail
    } finally {
      setViewingDoc(null);
    }
  };

  const handleDownload = async (doc: DocumentItem) => {
    setDownloadingDoc(doc.uuid);
    try {
      const res = await instance.get(`/v1/documents/${doc.file_name}`);
      window.open(res.data.url, "_blank");
    } catch {
      // silent fail
    } finally {
      setDownloadingDoc(null);
    }
  };

  return (
    <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 pt-24">
      <div className="bg-white rounded-xl border border-gray-200 shadow-sm">

        {/* Card Header */}
        <div className="p-5 border-b border-gray-200">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <h3 className="text-lg font-semibold text-gray-900">
              {t("documents.title")} ({totalDocs})
            </h3>
            <div className="flex flex-wrap items-center gap-2">
              {/* Search */}
              <div className="relative flex-1 sm:flex-none">
                <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
                <input
                  type="text"
                  placeholder={t("documents.searchPlaceholder")}
                  value={searchTerm}
                  onChange={(e) => { setSearchTerm(e.target.value); setCurrentPage(1); }}
                  className="pl-9 pr-4 py-2 w-full sm:w-56 border border-gray-200 rounded-full text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]"
                />
              </div>

              {/* Type Filter */}
              <div className="relative">
                <select
                  value={filterType}
                  onChange={(e) => { setFilterType(e.target.value); setCurrentPage(1); }}
                  className="appearance-none bg-white pl-4 pr-9 py-2 border border-gray-200 rounded-full text-base sm:text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] cursor-pointer"
                >
                  <option value="all">{t("documents.filterAll")}</option>
                  <option value="pdf">{t("documents.filterPDF")}</option>
                  <option value="doc">{t("documents.filterWord")}</option>
                </select>
                <svg className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                </svg>
              </div>
            </div>
          </div>
        </div>

        {/* Table */}
        <div className="mx-5 my-5 border border-gray-200 rounded-xl overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full min-w-[550px] border-collapse">
              <thead>
                <tr className="bg-gray-50">
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-200">{t("documents.colDocument")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-200">{t("documents.colDescription")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-200">{t("documents.colSize")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-gray-200">{t("documents.colAction")}</th>
                </tr>
              </thead>
              <tbody>
                {isLoading ? (
                  <>
                    <TableRowSkeleton />
                    <TableRowSkeleton />
                    <TableRowSkeleton />
                    <TableRowSkeleton />
                    <TableRowSkeleton />
                  </>
                ) : isError ? (
                  <tr>
                    <td colSpan={4} className="px-5 py-12 text-center text-gray-500 text-sm">
                      {t("documents.loadError")}
                    </td>
                  </tr>
                ) : pagedDocs.length === 0 ? (
                  <tr>
                    <td colSpan={4} className="px-5 py-12 text-center text-gray-500 text-sm">
                      {t("documents.noDocuments")}
                    </td>
                  </tr>
                ) : (
                  pagedDocs.map((doc) => {
                    const isUserGuide = doc.title.toLowerCase().includes("user guide");
                    return (
                    <tr key={doc.uuid} className={`border-b border-gray-200 transition ${isUserGuide ? "bg-[#3B9EC9]/5 hover:bg-[#3B9EC9]/10" : "hover:bg-gray-50/50"}`}>
                      {/* Document */}
                      <td className="px-5 py-4 border-r border-gray-200">
                        <div className="flex items-center gap-3">
                          <div className={`w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0 ${isUserGuide ? "border-2 border-[#3B9EC9] bg-[#3B9EC9]/5" : "border border-[#3B9EC9]"}`}>
                            <FileTypeIcon fileType={doc.file_type} />
                          </div>
                          <div className="min-w-0 flex items-center gap-2">
                            <p className={`text-sm truncate max-w-xs ${isUserGuide ? "font-semibold text-[#2B8EB9]" : "font-medium text-gray-900"}`}>{doc.title}</p>
                            {isUserGuide && (
                              <span className="inline-flex items-center px-1.5 py-0.5 text-xs font-medium rounded bg-[#3B9EC9] text-white flex-shrink-0">
                                Guide
                              </span>
                            )}
                          </div>
                        </div>
                      </td>
                      {/* Description */}
                      <td className="px-5 py-4 text-sm text-gray-600 border-r border-gray-200 max-w-xs">
                        <p className="truncate">{doc.description || "-"}</p>
                      </td>
                      {/* Size */}
                      <td className="px-5 py-4 text-sm text-gray-600 border-r border-gray-200">
                        {formatFileSize(doc.file_size)}
                      </td>
                      {/* Actions */}
                      <td className="px-5 py-4">
                        <div className="flex items-center justify-center gap-2">
                          <button
                            onClick={() => handleView(doc)}
                            disabled={viewingDoc === doc.uuid}
                            className="w-8 h-8 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
                            title={t("documents.view")}
                          >
                            {viewingDoc === doc.uuid ? (
                              <span className="w-3.5 h-3.5 border-2 border-[#3B9EC9] border-t-transparent rounded-full animate-spin block" />
                            ) : (
                              <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>
                          <button
                            onClick={() => handleDownload(doc)}
                            disabled={downloadingDoc === doc.uuid}
                            className="w-8 h-8 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
                            title={t("documents.download")}
                          >
                            {downloadingDoc === doc.uuid ? (
                              <span className="w-3.5 h-3.5 border-2 border-[#3B9EC9] border-t-transparent rounded-full animate-spin block" />
                            ) : (
                              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                <path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                              </svg>
                            )}
                          </button>
                        </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>
              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"
            >
              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>
    </main>
  );
}
