"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  FileText,
  UserPlus,
  CheckCircle2,
  RotateCcw,
  XCircle,
  Filter,
  AlertCircle,
  Eye,
  Download,
  Bot,
} from "lucide-react";
import { cn } from "@/lib/utils/cn";
import { useTranslation } from "@/lib/hooks/use-translation";
import { tToast } from "@/lib/utils/translated-toast";
import { adminApi } from "@/lib/api/client";
import type { Paper, User, PageResponse } from "@/types";
import { AdminManuscriptAccessModal } from "@/components/admin/AdminManuscriptAccessModal";
import { AdminMetadataModal } from "@/components/admin/AdminMetadataModal";

/* ───── Status config ───── */

const ALL_STATUSES = [
  "ALL",
  "PAYMENT_PENDING",
  "SUBMITTED",
  "SCREENING",
  "PENDING_ASSIGNMENT",
  "UNDER_REVIEW",
  "REVISION_REQUESTED",
  "REVISION_SUBMITTED",
  "REVIEW_COMPLETE",
  "ACCEPTED",
  "REJECTED",
  "PUBLISHED",
] as const;

const statusBadgeColor: Record<string, string> = {
  PAYMENT_PENDING: "bg-amber-100 text-amber-800",
  SUBMITTED: "bg-blue-100 text-blue-700",
  SCREENING: "bg-blue-100 text-blue-700",
  PENDING_ASSIGNMENT: "bg-amber-100 text-amber-700",
  UNDER_REVIEW: "bg-yellow-100 text-yellow-700",
  REVISION_REQUESTED: "bg-orange-100 text-orange-700",
  REVISION_SUBMITTED: "bg-orange-100 text-orange-700",
  REVIEW_COMPLETE: "bg-teal-100 text-teal-700",
  ACCEPTED: "bg-green-100 text-green-700",
  REJECTED: "bg-red-100 text-red-700",
  PUBLISHED: "bg-green-100 text-green-800",
};

/* ───── Page ───── */

export default function AdminPapers() {
  const queryClient = useQueryClient();
  const { t: cms, language } = useTranslation(["ADMIN_PAPERS", "STATUS_LABELS", "COMMON"]);
  const [statusFilter, setStatusFilter] = useState<string>("ALL");
  const [assignPaperId, setAssignPaperId] = useState<string | null>(null);
  const [reviewerIdInput, setReviewerIdInput] = useState("");
  const [notesInput, setNotesInput] = useState("");
  const [actionModal, setActionModal] = useState<{
    type: "revision" | "reject";
    paperId: string;
  } | null>(null);
  const [manuscriptModal, setManuscriptModal] = useState<{
    paperId: string;
    paperReferenceNo: string;
    action: "preview" | "download";
  } | null>(null);
  const [metadataModal, setMetadataModal] = useState<{
    paperId: string;
    paperReferenceNo: string;
  } | null>(null);

  const params: Record<string, unknown> = {};
  if (statusFilter !== "ALL") params.status = statusFilter;

  const { data, isLoading, error } = useQuery<PageResponse<Paper>>({
    queryKey: ["admin-papers", statusFilter],
    queryFn: async () => {
      const res = await adminApi.papers(params);
      return res.data;
    },
  });

  // Fetch reviewers for the assign modal
  const { data: reviewersData } = useQuery<PageResponse<User>>({
    queryKey: ["admin-reviewers"],
    queryFn: async () => {
      const res = await adminApi.users({ role: "REVIEWER", size: 100 });
      return res.data;
    },
    enabled: !!assignPaperId,
  });

  // Fetch already-assigned reviewer IDs for the selected paper
  const { data: assignedReviewerIds } = useQuery<string[]>({
    queryKey: ["assigned-reviewers", assignPaperId],
    queryFn: async () => {
      const res = await adminApi.assignedReviewers(assignPaperId!);
      return res.data;
    },
    enabled: !!assignPaperId,
  });

  // Filter out already-assigned reviewers from dropdown
  const assignedSet = new Set(assignedReviewerIds ?? []);
  const availableReviewers = (reviewersData?.content ?? []).filter(r => !assignedSet.has(r.id));

  const papers = data?.content ?? [];

  /* ─── Mutations ─── */

  const assignMutation = useMutation({
    mutationFn: ({ paperId, reviewerId }: { paperId: string; reviewerId: string }) =>
      adminApi.assignReviewer(paperId, reviewerId),
    onSuccess: () => {
      tToast("success", "admin_papers.reviewer_assigned", "Reviewer assigned");
      setAssignPaperId(null);
      setReviewerIdInput("");
      queryClient.invalidateQueries({ queryKey: ["admin-papers"] });
    },
    onError: (err: unknown) => {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message
        ?? "Failed to assign reviewer";
      tToast("error", "admin_papers.assign_failed", msg);
    },
  });

  const publishMutation = useMutation({
    mutationFn: (id: string) => adminApi.publishPaper(id),
    onSuccess: () => {
      tToast("success", "admin_papers.paper_published", "Paper published");
      queryClient.invalidateQueries({ queryKey: ["admin-papers"] });
    },
    onError: () => tToast("error", "admin_papers.publish_failed", "Failed to publish"),
  });

  const revisionMutation = useMutation({
    mutationFn: ({ id, notes }: { id: string; notes?: string }) =>
      adminApi.requestRevision(id, notes ? { notes } : undefined),
    onSuccess: () => {
      tToast("success", "admin_papers.revision_requested", "Revision requested");
      setActionModal(null);
      setNotesInput("");
      queryClient.invalidateQueries({ queryKey: ["admin-papers"] });
    },
    onError: () => tToast("error", "admin_papers.revision_failed", "Request failed"),
  });

  const rejectMutation = useMutation({
    mutationFn: ({ id, notes }: { id: string; notes?: string }) =>
      adminApi.rejectPaper(id, notes ? { notes } : undefined),
    onSuccess: () => {
      tToast("success", "admin_papers.paper_rejected", "Paper rejected");
      setActionModal(null);
      setNotesInput("");
      queryClient.invalidateQueries({ queryKey: ["admin-papers"] });
    },
    onError: () => tToast("error", "admin_papers.reject_failed", "Rejection failed"),
  });

  /* ─── Action buttons per status ─── */

  function renderActions(paper: Paper) {
    const btns: React.ReactNode[] = [];

    // Manuscript access — available for every paper regardless of status
    btns.push(
      <button
        key="preview"
        onClick={() => setManuscriptModal({ paperId: paper.id, paperReferenceNo: paper.referenceNo, action: "preview" })}
        className="inline-flex items-center gap-1 rounded-md bg-sky-50 px-2.5 py-1.5 text-xs font-medium text-sky-700 hover:bg-sky-100 transition"
      >
        <Eye className="h-3.5 w-3.5" />
        {cms("ADMIN_PAPERS.papers_actions.preview", "Preview")}
      </button>
    );
    btns.push(
      <button
        key="download"
        onClick={() => setManuscriptModal({ paperId: paper.id, paperReferenceNo: paper.referenceNo, action: "download" })}
        className="inline-flex items-center gap-1 rounded-md bg-sky-50 px-2.5 py-1.5 text-xs font-medium text-sky-700 hover:bg-sky-100 transition"
      >
        <Download className="h-3.5 w-3.5" />
        {cms("ADMIN_PAPERS.papers_actions.download", "Download")}
      </button>
    );

    // Editorial metadata. Not offered on a published paper: its title is already
    // in the registry and in any magazine PDF, neither of which is regenerated.
    if (paper.status !== "PUBLISHED") {
      btns.push(
        <button
          key="metadata"
          onClick={() => setMetadataModal({ paperId: paper.id, paperReferenceNo: paper.referenceNo })}
          className="inline-flex items-center gap-1 rounded-md bg-violet-50 px-2.5 py-1.5 text-xs font-medium text-violet-700 hover:bg-violet-100 transition"
        >
          <Bot className="h-3.5 w-3.5" />
          {cms("ADMIN_PAPERS.papers_actions.ai_details", "AI details")}
        </button>
      );
    }

    // Assign reviewer — only for new submissions awaiting first assignment
    if (
      ["SUBMITTED", "SCREENING", "PENDING_ASSIGNMENT"].includes(paper.status)
    ) {
      btns.push(
        <button
          key="assign"
          onClick={() => setAssignPaperId(paper.id)}
          className="inline-flex items-center gap-1 rounded-md bg-indigo-50 px-2.5 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100 transition"
        >
          <UserPlus className="h-3.5 w-3.5" />
          {cms("ADMIN_PAPERS.papers_actions.assign", "Assign")}
        </button>
      );
    }

    // REVISION_SUBMITTED without auto-reassignment — admin needs to assign manually
    if (paper.status === "REVISION_SUBMITTED") {
      btns.push(
        <button
          key="assign"
          onClick={() => setAssignPaperId(paper.id)}
          className="inline-flex items-center gap-1 rounded-md bg-indigo-50 px-2.5 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100 transition"
        >
          <UserPlus className="h-3.5 w-3.5" />
          {cms("ADMIN_PAPERS.papers_actions.assign", "Assign")}
        </button>
      );
    }

    // UNDER_REVIEW — review in progress + option to add more reviewers
    if (paper.status === "UNDER_REVIEW") {
      btns.push(
        <span key="info" className="inline-flex items-center gap-1 rounded-md bg-purple-50 px-2.5 py-1.5 text-xs font-medium text-purple-600">
          समीक्षाधीन / Review in progress
        </span>
      );
      btns.push(
        <button
          key="add-reviewer"
          onClick={() => setAssignPaperId(paper.id)}
          className="inline-flex items-center gap-1 rounded-md bg-indigo-50 px-2.5 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100 transition"
        >
          <UserPlus className="h-3.5 w-3.5" />
          {cms("ADMIN_PAPERS.papers_actions.add_reviewer", "+ Reviewer")}
        </button>
      );
    }

    // Publish for review-complete or accepted
    if (["REVIEW_COMPLETE", "ACCEPTED"].includes(paper.status)) {
      btns.push(
        <button
          key="publish"
          onClick={() => publishMutation.mutate(paper.id)}
          disabled={publishMutation.isPending}
          className="inline-flex items-center gap-1 rounded-md bg-green-50 px-2.5 py-1.5 text-xs font-medium text-green-700 hover:bg-green-100 transition disabled:opacity-50"
        >
          <CheckCircle2 className="h-3.5 w-3.5" />
          {cms("ADMIN_PAPERS.papers_actions.publish", "Publish")}
        </button>
      );
    }

    // Request revision — only when reviews are complete and admin is making a decision
    if (paper.status === "REVIEW_COMPLETE") {
      btns.push(
        <button
          key="revision"
          onClick={() => setActionModal({ type: "revision", paperId: paper.id })}
          className="inline-flex items-center gap-1 rounded-md bg-orange-50 px-2.5 py-1.5 text-xs font-medium text-orange-700 hover:bg-orange-100 transition"
        >
          <RotateCcw className="h-3.5 w-3.5" />
          {cms("ADMIN_PAPERS.papers_actions.revision", "Revision")}
        </button>
      );
    }

    // Reject — only when admin is making a decision (review complete or new submissions)
    if (
      ["SUBMITTED", "SCREENING", "REVIEW_COMPLETE"].includes(paper.status)
    ) {
      btns.push(
        <button
          key="reject"
          onClick={() => setActionModal({ type: "reject", paperId: paper.id })}
          className="inline-flex items-center gap-1 rounded-md bg-red-50 px-2.5 py-1.5 text-xs font-medium text-red-700 hover:bg-red-100 transition"
        >
          <XCircle className="h-3.5 w-3.5" />
          {cms("ADMIN_PAPERS.papers_actions.reject", "Reject")}
        </button>
      );
    }

    return <div className="flex flex-wrap gap-1.5">{btns}</div>;
  }

  /* ───── Render ───── */

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">
            {cms("ADMIN_PAPERS.papers_header.title", "Paper Management")}
          </h1>
          <p className="text-gray-500 text-sm mt-1">
            {cms("ADMIN_PAPERS.papers_header.subtitle", "View & manage all papers")}
          </p>
        </div>

        {/* Status filter */}
        <div className="flex items-center gap-2">
          <Filter className="h-4 w-4 text-gray-400" />
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="rounded-md border border-gray-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
          >
            {ALL_STATUSES.map((s) => (
              <option key={s} value={s}>
                {s === "ALL" ? cms("ADMIN_PAPERS.papers_filter.all", "All") : cms(`STATUS_LABELS.paper.${s.toLowerCase()}`, s)}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* Loading / Error */}
      {isLoading && (
        <div className="flex items-center justify-center py-20">
          <p className="text-gray-500 text-lg">{cms("COMMON.labels.loading", "Loading...")}</p>
        </div>
      )}

      {error && !isLoading && (
        <div className="flex items-center justify-center py-20">
          <div className="text-center">
            <AlertCircle className="mx-auto h-10 w-10 text-red-400 mb-2" />
            <p className="text-red-600">{cms("COMMON.labels.error_loading", "Error loading data")}</p>
          </div>
        </div>
      )}

      {/* Papers table */}
      {!isLoading && !error && (
        <div className="rounded-lg border border-gray-200 bg-white shadow-sm overflow-hidden">
          {papers.length === 0 ? (
            <div className="px-5 py-16 text-center text-gray-500">
              <FileText className="mx-auto h-10 w-10 text-gray-300 mb-3" />
              <p>{cms("ADMIN_PAPERS.papers_table.no_papers", "No papers found")}</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 text-left">
                  <tr>
                    <th className="px-5 py-3 font-medium text-gray-500">{cms("ADMIN_PAPERS.papers_table.col_ref", "Ref No.")}</th>
                    <th className="px-5 py-3 font-medium text-gray-500">{cms("ADMIN_PAPERS.papers_table.col_title", "Title")}</th>
                    <th className="px-5 py-3 font-medium text-gray-500">{cms("ADMIN_PAPERS.papers_table.col_status", "Status")}</th>
                    <th className="px-5 py-3 font-medium text-gray-500">{cms("ADMIN_PAPERS.papers_table.col_date", "Date")}</th>
                    <th className="px-5 py-3 font-medium text-gray-500">{cms("ADMIN_PAPERS.papers_table.col_actions", "Actions")}</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {papers.map((paper) => (
                    <tr key={paper.id} className="hover:bg-gray-50 transition">
                      <td className="px-5 py-4 text-gray-600 font-mono text-xs">
                        {paper.referenceNo}
                      </td>
                      <td className="px-5 py-4 font-medium text-gray-900 max-w-xs truncate">
                        {paper.titleEn}
                      </td>
                      <td className="px-5 py-4">
                        <span
                          className={cn(
                            "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium",
                            statusBadgeColor[paper.status] ?? "bg-gray-100 text-gray-700"
                          )}
                        >
                          {cms(`STATUS_LABELS.paper.${paper.status.toLowerCase()}`, paper.status)}
                        </span>
                      </td>
                      <td className="px-5 py-4 text-gray-500">
                        {paper.submittedAt
                          ? new Date(paper.submittedAt).toLocaleDateString("en-IN")
                          : "—"}
                      </td>
                      <td className="px-5 py-4">{renderActions(paper)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {/* ─── Assign Reviewer Modal ─── */}
      {assignPaperId && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="w-full max-w-sm bg-white rounded-xl shadow-xl p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">
              {cms("ADMIN_PAPERS.papers_modal.assign_title", "Assign Reviewer")}
            </h3>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {cms("ADMIN_PAPERS.papers_modal.reviewer_label", "Select Reviewer")}
            </label>
            <select
              className="w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 mb-4"
              value={reviewerIdInput}
              onChange={(e) => setReviewerIdInput(e.target.value)}
            >
              <option value="">
                {availableReviewers.length === 0
                  ? cms("ADMIN_PAPERS.papers_modal.loading_reviewers", "Loading reviewers...")
                  : cms("ADMIN_PAPERS.papers_modal.select_reviewer", "-- Select a reviewer --")}
              </option>
              {availableReviewers.map((r) => (
                <option key={r.id} value={r.id}>
                  {language === "hi" ? r.nameHi : r.nameEn} ({r.email})
                </option>
              ))}
            </select>
            <div className="flex justify-end gap-2">
              <button
                onClick={() => {
                  setAssignPaperId(null);
                  setReviewerIdInput("");
                }}
                className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
              >
                {cms("COMMON.buttons.cancel", "Cancel")}
              </button>
              <button
                onClick={() =>
                  assignMutation.mutate({ paperId: assignPaperId, reviewerId: reviewerIdInput })
                }
                disabled={!reviewerIdInput || assignMutation.isPending}
                className="rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow hover:bg-indigo-700 disabled:opacity-50 transition"
              >
                {assignMutation.isPending ? "..." : cms("ADMIN_PAPERS.papers_modal.assign_btn", "Assign")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ─── Revision / Reject Modal ─── */}
      {actionModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="w-full max-w-sm bg-white rounded-xl shadow-xl p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">
              {actionModal.type === "revision"
                ? cms("ADMIN_PAPERS.papers_modal.revision_title", "Request Revision")
                : cms("ADMIN_PAPERS.papers_modal.reject_title", "Reject Paper")}
            </h3>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {cms("ADMIN_PAPERS.papers_modal.notes_label", "Notes (optional)")}
            </label>
            <textarea
              rows={3}
              className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500 mb-4"
              value={notesInput}
              onChange={(e) => setNotesInput(e.target.value)}
            />
            <div className="flex justify-end gap-2">
              <button
                onClick={() => {
                  setActionModal(null);
                  setNotesInput("");
                }}
                className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
              >
                {cms("COMMON.buttons.cancel", "Cancel")}
              </button>
              <button
                onClick={() => {
                  const payload = { id: actionModal.paperId, notes: notesInput || undefined };
                  if (actionModal.type === "revision") {
                    revisionMutation.mutate(payload);
                  } else {
                    rejectMutation.mutate(payload);
                  }
                }}
                disabled={revisionMutation.isPending || rejectMutation.isPending}
                className={cn(
                  "rounded-md px-4 py-2 text-sm font-semibold text-white shadow disabled:opacity-50 transition",
                  actionModal.type === "revision"
                    ? "bg-orange-600 hover:bg-orange-700"
                    : "bg-red-600 hover:bg-red-700"
                )}
              >
                {revisionMutation.isPending || rejectMutation.isPending
                  ? "..."
                  : actionModal.type === "revision"
                  ? cms("ADMIN_PAPERS.papers_modal.revision_btn", "Request")
                  : cms("ADMIN_PAPERS.papers_modal.reject_btn", "Reject")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ─── AI metadata ─── */}
      <AdminMetadataModal
        open={metadataModal !== null}
        onClose={() => setMetadataModal(null)}
        paperId={metadataModal?.paperId ?? null}
        paperReferenceNo={metadataModal?.paperReferenceNo ?? null}
      />

      {/* ─── Manuscript Access Modal ─── */}
      <AdminManuscriptAccessModal
        open={manuscriptModal !== null}
        onClose={() => setManuscriptModal(null)}
        paperId={manuscriptModal?.paperId ?? null}
        paperReferenceNo={manuscriptModal?.paperReferenceNo ?? null}
        action={manuscriptModal?.action ?? null}
      />
    </div>
  );
}
