"use client";

import { useState, useRef } from "react";
import { useTranslations } from "next-intl";
import { useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
import {
  useAdminBibliographyControllerListBibliographyV1,
  getAdminBibliographyControllerListBibliographyV1QueryKey,
  adminBibliographyControllerCreateEntryV1,
  adminBibliographyControllerUpdateEntryV1,
  adminBibliographyControllerDeleteEntryV1,
  adminBibliographyControllerGetPdfUrlV1,
} from "@/api/admin/admin-bibliography/admin-bibliography";
import type { AdminBibliographyControllerListBibliographyV1200Item } from "@/api/admin/generated.schemas";

type AdminBibliographyEntry = AdminBibliographyControllerListBibliographyV1200Item;

const CitationText = ({ text }: { text: string }) => {
  const parts = text.split(/(https?:\/\/[^\s,;)\]]+)/g);
  return (
    <>
      {parts.map((part, i) =>
        /^https?:\/\//.test(part) ? (
          <a
            key={i}
            href={part}
            target="_blank"
            rel="noopener noreferrer"
            className="text-[#3B9EC9] underline break-all hover:text-[#2D8AB5]"
            onClick={(e) => e.stopPropagation()}
          >
            {part}
          </a>
        ) : (
          <span key={i}>{part}</span>
        )
      )}
    </>
  );
};

const TableRowSkeleton = () => (
  <tr className="border-b border-gray-200 animate-pulse">
    <td className="px-3 py-4 border-r border-gray-200"><div className="h-7 w-16 bg-gray-200 rounded mx-auto" /></td>
    <td className="px-5 py-4 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-5 py-4 border-r border-gray-200"><div className="h-4 w-56 bg-gray-200 rounded" /></td>
    <td className="px-5 py-4 border-r border-gray-200"><div className="h-5 w-24 bg-gray-200 rounded-full" /></td>
    <td className="px-5 py-4"><div className="h-8 w-20 bg-gray-200 rounded-full mx-auto" /></td>
  </tr>
);

export default function AdminBibliographyPage() {
  const t = useTranslations("admin");
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState("");
  const [deleteConfirmEntry, setDeleteConfirmEntry] = useState<AdminBibliographyEntry | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [viewingPdf, setViewingPdf] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 10;

  // Create modal state
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [createCitation, setCreateCitation] = useState("");
  const [createAnnotation, setCreateAnnotation] = useState("");
  const [createDoi, setCreateDoi] = useState("");
  const [createPdf, setCreatePdf] = useState<File | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const createPdfRef = useRef<HTMLInputElement>(null);

  // Edit modal state
  const [editEntry, setEditEntry] = useState<AdminBibliographyEntry | null>(null);
  const [editCitation, setEditCitation] = useState("");
  const [editAnnotation, setEditAnnotation] = useState("");
  const [editDoi, setEditDoi] = useState("");
  const [editPdf, setEditPdf] = useState<File | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const editPdfRef = useRef<HTMLInputElement>(null);

  const [isReordering, setIsReordering] = useState(false);

  const { data, isLoading, isError } = useAdminBibliographyControllerListBibliographyV1();
  // Backend wraps in { data: [...] } — unwrap accordingly
  const entries: AdminBibliographyEntry[] = (data as any)?.data ?? (Array.isArray(data) ? data : []);

  const filtered = entries.filter((e) => {
    const q = searchTerm.toLowerCase();
    return (
      !q ||
      (e.citation ?? "").toLowerCase().includes(q) ||
      (e.annotation ?? "").toLowerCase().includes(q)
    );
  });

  const totalEntries = filtered.length;
  const totalPages = Math.max(1, Math.ceil(totalEntries / pageSize));
  const paged = filtered.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 refreshList = () => {
    queryClient.invalidateQueries({ queryKey: getAdminBibliographyControllerListBibliographyV1QueryKey() });
  };

  const handleViewPdf = async (filename: string) => {
    setViewingPdf(filename);
    try {
      const res = await adminBibliographyControllerGetPdfUrlV1(filename);
      if (res?.url) window.open(res.url, "_blank");
    } catch {
      // silent fail
    } finally {
      setViewingPdf(null);
    }
  };

  const resetCreateForm = () => {
    setCreateCitation("");
    setCreateAnnotation("");
    setCreateDoi("");
    setCreatePdf(null);
    if (createPdfRef.current) createPdfRef.current.value = "";
  };

  const handleCreate = async () => {
    if (!createCitation.trim()) { toast.error(t("bibliography.citationRequired")); return; }

    setIsCreating(true);
    try {
      await adminBibliographyControllerCreateEntryV1({
        citation: createCitation.trim(),
        ...(createAnnotation.trim() && { annotation: createAnnotation.trim() }),
        ...(createDoi.trim() && { doi: createDoi.trim() }),
        ...(createPdf && { file: createPdf }),
      });
      toast.success(t("bibliography.articleCreated"));
      refreshList();
      setShowCreateModal(false);
      resetCreateForm();
    } catch {
      toast.error(t("bibliography.articleCreateFailed"));
    } finally {
      setIsCreating(false);
    }
  };

  const openEditModal = (entry: AdminBibliographyEntry) => {
    setEditEntry(entry);
    setEditCitation(entry.citation ?? "");
    setEditAnnotation(entry.annotation ?? "");
    setEditDoi(entry.doi ?? "");
    setEditPdf(null);
    if (editPdfRef.current) editPdfRef.current.value = "";
  };

  const closeEditModal = () => {
    setEditEntry(null);
    setEditPdf(null);
    if (editPdfRef.current) editPdfRef.current.value = "";
  };

  const handleEdit = async () => {
    if (!editEntry?.uuid) return;
    if (!editCitation.trim()) { toast.error(t("bibliography.citationRequired")); return; }

    setIsSaving(true);
    try {
      await adminBibliographyControllerUpdateEntryV1(editEntry.uuid, {
        citation: editCitation.trim(),
        ...(editAnnotation.trim() && { annotation: editAnnotation.trim() }),
        doi: editDoi.trim() || undefined,
        ...(editPdf && { file: editPdf }),
      });
      toast.success(t("bibliography.articleUpdated"));
      refreshList();
      closeEditModal();
    } catch {
      toast.error(t("bibliography.articleUpdateFailed"));
    } finally {
      setIsSaving(false);
    }
  };

  const handleReorder = async (index: number, direction: "up" | "down") => {
    const swapIndex = direction === "up" ? index - 1 : index + 1;
    if (swapIndex < 0 || swapIndex >= entries.length) return;

    if (!entries[index]?.uuid || !entries[swapIndex]?.uuid) return;

    setIsReordering(true);
    try {
      // Build new order: swap the two entries, assign sequential display_order to all
      const reordered = [...entries];
      [reordered[index], reordered[swapIndex]] = [reordered[swapIndex], reordered[index]];

      for (let i = 0; i < reordered.length; i++) {
        if (!reordered[i].uuid) continue;
        await adminBibliographyControllerUpdateEntryV1(reordered[i].uuid!, { display_order: i + 1 });
      }
      refreshList();
    } catch (err) {
      console.error("Reorder failed:", err);
      toast.error(t("bibliography.reorderFailed"));
    } finally {
      setIsReordering(false);
    }
  };

  const handleDelete = async (entry: AdminBibliographyEntry) => {
    if (!entry.uuid) return;
    setIsDeleting(true);
    try {
      await adminBibliographyControllerDeleteEntryV1(entry.uuid);
      toast.success(t("bibliography.articleDeleted"));
      refreshList();
    } catch {
      toast.error(t("bibliography.articleDeleteFailed"));
    } finally {
      setIsDeleting(false);
      setDeleteConfirmEntry(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("bibliography.title")} ({totalEntries})
            </h3>
            <div className="flex flex-wrap items-center gap-2">
              {/* Add Button */}
              <button
                onClick={() => setShowCreateModal(true)}
                className="flex items-center gap-2 px-5 py-2 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition cursor-pointer"
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
                </svg>
                {t("bibliography.uploadArticle")}
              </button>

              {/* 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("bibliography.searchPlaceholder")}
                  value={searchTerm}
                  onChange={(e) => { setSearchTerm(e.target.value); setCurrentPage(1); }}
                  className="pl-9 pr-4 py-2 w-full sm:w-48 border border-gray-200 rounded-full text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]"
                />
              </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 border-collapse">
              <thead>
                <tr className="bg-gray-50">
                  <th className="text-center px-3 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-200 w-20">{t("bibliography.colOrder")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-200">{t("bibliography.colFileName")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-200">{t("bibliography.colCitation")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-200">{t("bibliography.colAnnotation")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-gray-200">{t("bibliography.colActions")}</th>
                </tr>
              </thead>
              <tbody>
                {isLoading ? (
                  <><TableRowSkeleton /><TableRowSkeleton /><TableRowSkeleton /><TableRowSkeleton /></>
                ) : isError ? (
                  <tr>
                    <td colSpan={5} className="px-5 py-12 text-center text-gray-500 text-sm">
                      {t("bibliography.loadError")}
                    </td>
                  </tr>
                ) : paged.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="px-5 py-12 text-center text-gray-500 text-sm">
                      {t("bibliography.noData")}
                    </td>
                  </tr>
                ) : (
                  paged.map((entry, idx) => {
                    const globalIdx = (currentPage - 1) * pageSize + idx;
                    return (
                    <tr key={entry.uuid ?? idx} className="border-b border-gray-200 hover:bg-gray-50/50 transition">
                      {/* Order */}
                      <td className="px-3 py-4 border-r border-gray-200 w-20">
                        <div className="flex items-center justify-center gap-1">
                          <button
                            onClick={() => handleReorder(globalIdx, "up")}
                            disabled={globalIdx === 0 || isReordering || !!searchTerm}
                            className="w-7 h-7 flex items-center justify-center rounded-md border border-gray-200 text-gray-500 hover:bg-gray-100 transition disabled:opacity-30 disabled:cursor-not-allowed cursor-pointer"
                            title={t("bibliography.moveUp")}
                          >
                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M5 15l7-7 7 7" />
                            </svg>
                          </button>
                          <button
                            onClick={() => handleReorder(globalIdx, "down")}
                            disabled={globalIdx === entries.length - 1 || isReordering || !!searchTerm}
                            className="w-7 h-7 flex items-center justify-center rounded-md border border-gray-200 text-gray-500 hover:bg-gray-100 transition disabled:opacity-30 disabled:cursor-not-allowed cursor-pointer"
                            title={t("bibliography.moveDown")}
                          >
                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
                            </svg>
                          </button>
                        </div>
                      </td>
                      {/* File Name */}
                      <td className="px-5 py-4 text-sm text-gray-600 border-r border-gray-200">
                        <p className="break-all text-xs">{(entry as any).original_file_name || entry.pdf_file_name || "-"}</p>
                      </td>
                      {/* Citation */}
                      <td className="px-5 py-4 border-r border-gray-200 max-w-sm">
                        <p className="text-sm text-gray-900 leading-snug">
                          {entry.citation ? <CitationText text={entry.citation} /> : "—"}
                        </p>
                      </td>
                      {/* Annotation */}
                      <td className="px-5 py-4 text-sm text-gray-600 border-r border-gray-200 max-w-sm">
                        <p>{entry.annotation || "-"}</p>
                      </td>
                      {/* Actions */}
                      <td className="px-5 py-4">
                        <div className="flex items-center justify-center gap-2">
                          {/* View PDF */}
                          {entry.pdf_file_name && (
                            <button
                              onClick={() => handleViewPdf(entry.pdf_file_name!)}
                              disabled={viewingPdf === entry.pdf_file_name}
                              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("bibliography.viewPdf")}
                            >
                              {viewingPdf === entry.pdf_file_name ? (
                                <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>
                          )}
                          {/* Edit */}
                          <button
                            onClick={() => openEditModal(entry)}
                            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("bibliography.edit")}
                          >
                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                            </svg>
                          </button>
                          {/* Delete */}
                          <button
                            onClick={() => setDeleteConfirmEntry(entry)}
                            className="w-8 h-8 flex items-center justify-center rounded-full border border-red-400 text-red-500 hover:bg-red-50/50 transition cursor-pointer"
                            title={t("bibliography.deleteTooltip")}
                          >
                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </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>
              {t("bibliography.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("bibliography.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>

      {/* Create Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div
            className="absolute inset-0 bg-black/40"
            onClick={() => { if (!isCreating) { setShowCreateModal(false); resetCreateForm(); } }}
          />
          <div className="relative bg-white rounded-2xl shadow-xl w-full max-w-lg p-6">
            <h2 className="text-lg font-bold text-gray-900 mb-5">{t("bibliography.addEntry")}</h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t("bibliography.labelCitation")} <span className="text-red-500">*</span>
                </label>
                <textarea
                  value={createCitation}
                  onChange={(e) => setCreateCitation(e.target.value)}
                  placeholder={t("bibliography.citationPlaceholder")}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent resize-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t("bibliography.labelAnnotation")}</label>
                <textarea
                  value={createAnnotation}
                  onChange={(e) => setCreateAnnotation(e.target.value)}
                  placeholder={t("bibliography.annotationPlaceholder")}
                  rows={2}
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent resize-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t("bibliography.labelDoi")}</label>
                <input
                  type="url"
                  value={createDoi}
                  onChange={(e) => setCreateDoi(e.target.value)}
                  placeholder="https://doi.org/10.1000/xyz123"
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t("bibliography.labelPdf")}</label>
                <input
                  ref={createPdfRef}
                  type="file"
                  accept=".pdf,application/pdf"
                  onChange={(e) => setCreatePdf(e.target.files?.[0] ?? null)}
                  className="w-full text-sm text-gray-600 file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-[#E8F4F8] file:text-[#3B9EC9] hover:file:bg-[#3B9EC9]/10 cursor-pointer"
                />
              </div>
            </div>
            <div className="flex gap-3 mt-6">
              <button
                onClick={() => { setShowCreateModal(false); resetCreateForm(); }}
                disabled={isCreating}
                className="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 border border-gray-200 rounded-xl hover:bg-gray-50 transition disabled:opacity-50 cursor-pointer"
              >
                {t("bibliography.cancel")}
              </button>
              <button
                onClick={handleCreate}
                disabled={isCreating}
                className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white bg-[#3B9EC9] rounded-xl hover:bg-[#2D8AB5] transition disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
              >
                {isCreating && <span className="w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin" />}
                {isCreating ? t("bibliography.uploading") : t("bibliography.uploadArticle")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Modal */}
      {editEntry && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div
            className="absolute inset-0 bg-black/40"
            onClick={() => { if (!isSaving) closeEditModal(); }}
          />
          <div className="relative bg-white rounded-2xl shadow-xl w-full max-w-lg p-6">
            <h2 className="text-lg font-bold text-gray-900 mb-5">{t("bibliography.editEntry")}</h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {t("bibliography.labelCitation")} <span className="text-red-500">*</span>
                </label>
                <textarea
                  value={editCitation}
                  onChange={(e) => setEditCitation(e.target.value)}
                  placeholder={t("bibliography.citationPlaceholder")}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent resize-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t("bibliography.labelAnnotation")}</label>
                <textarea
                  value={editAnnotation}
                  onChange={(e) => setEditAnnotation(e.target.value)}
                  placeholder={t("bibliography.annotationPlaceholder")}
                  rows={2}
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent resize-none"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t("bibliography.labelDoi")}</label>
                <input
                  type="url"
                  value={editDoi}
                  onChange={(e) => setEditDoi(e.target.value)}
                  placeholder="https://doi.org/10.1000/xyz123"
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">{t("bibliography.labelReplacePdf")}</label>
                <input
                  ref={editPdfRef}
                  type="file"
                  accept=".pdf,application/pdf"
                  onChange={(e) => setEditPdf(e.target.files?.[0] ?? null)}
                  className="w-full text-sm text-gray-600 file:mr-3 file:py-1.5 file:px-3 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-[#E8F4F8] file:text-[#3B9EC9] hover:file:bg-[#3B9EC9]/10 cursor-pointer"
                />
                {editEntry.pdf_file_name && (
                  <p className="text-xs text-gray-400 mt-1">{t("bibliography.currentFile", { name: (editEntry as any).original_file_name || editEntry.pdf_file_name })}</p>
                )}
              </div>
            </div>
            <div className="flex gap-3 mt-6">
              <button
                onClick={closeEditModal}
                disabled={isSaving}
                className="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 border border-gray-200 rounded-xl hover:bg-gray-50 transition disabled:opacity-50 cursor-pointer"
              >
                {t("bibliography.cancel")}
              </button>
              <button
                onClick={handleEdit}
                disabled={isSaving}
                className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white bg-[#3B9EC9] rounded-xl hover:bg-[#2D8AB5] transition disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
              >
                {isSaving && <span className="w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin" />}
                {isSaving ? t("bibliography.saving") : t("bibliography.saveChanges")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {deleteConfirmEntry && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-black/40" onClick={() => { if (!isDeleting) setDeleteConfirmEntry(null); }} />
          <div className="relative bg-white rounded-2xl shadow-xl w-full max-w-sm p-6">
            <div className="flex items-center justify-center w-12 h-12 rounded-full bg-red-100 mx-auto mb-4">
              <svg className="w-6 h-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
              </svg>
            </div>
            <h2 className="text-lg font-bold text-gray-900 text-center mb-1">{t("bibliography.deleteArticle")}</h2>
            <p className="text-sm text-gray-500 text-center mb-6">
              {t("bibliography.deleteArticleDesc")}
            </p>
            <div className="flex gap-3">
              <button
                onClick={() => setDeleteConfirmEntry(null)}
                disabled={isDeleting}
                className="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 border border-gray-200 rounded-xl hover:bg-gray-50 transition disabled:opacity-50 cursor-pointer"
              >
                {t("bibliography.cancel")}
              </button>
              <button
                onClick={() => handleDelete(deleteConfirmEntry)}
                disabled={isDeleting}
                className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white bg-red-600 rounded-xl hover:bg-red-700 transition disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
              >
                {isDeleting && <span className="w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin" />}
                {isDeleting ? t("bibliography.deleting") : t("bibliography.delete")}
              </button>
            </div>
          </div>
        </div>
      )}
    </main>
  );
}
