import { useQuery } from '@tanstack/react-query';
import { Link, useParams } from 'react-router-dom';
import { PDFDownloadLink } from '@react-pdf/renderer';
import { ArrowLeft, Download, Pencil, ShieldCheck } from 'lucide-react';

import { Badge, Button, Card, CardContent, Separator, listProjectAudit } from '@ump/shared';

import { getProjectResearch } from '@/features/papers/api/papersApi';
import { findPaper } from '@/features/papers/domain/paperModel';
import { PaperPdfDocument } from '@/features/papers/presentation/PaperPdfDocument';

export function PaperPreviewPage() {
  const { projectId = '', paperId = '' } = useParams();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['publisher', 'project-research', projectId],
    queryFn: () => getProjectResearch(projectId),
    enabled: !!projectId,
  });

  const { data: audit } = useQuery({
    queryKey: ['publisher', 'audit', projectId],
    queryFn: () => listProjectAudit(projectId),
    enabled: !!projectId,
  });

  if (isLoading) return <p className="p-6 text-sm text-muted-foreground">Đang tải…</p>;
  if (isError || !data) return <p className="p-6 text-sm text-destructive">Không tải được dữ liệu.</p>;

  const paper = findPaper(data.papers, paperId);
  if (!paper) return <p className="p-6 text-sm text-destructive">Không tìm thấy bài báo.</p>;

  const projectTitle = data.bundle.project.title;
  const pdfName = `${(paper.title || 'bai-bao').slice(0, 60).replace(/\s+/g, '-')}.pdf`;

  return (
    <div className="mx-auto max-w-4xl space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <Button asChild variant="ghost" size="sm" className="h-8">
          <Link to="/dashboard/papers">
            <ArrowLeft className="mr-1.5 h-4 w-4" /> Danh sách
          </Link>
        </Button>
        <div className="flex gap-2">
          <Button asChild variant="outline" size="sm" className="h-8">
            <Link to={`/dashboard/papers/${projectId}/compose?paperId=${paper.id}`}>
              <Pencil className="mr-1.5 h-4 w-4" /> Sửa
            </Link>
          </Button>
          <Button asChild size="sm" className="h-8">
            <PDFDownloadLink
              document={<PaperPdfDocument paper={paper} projectTitle={projectTitle} />}
              fileName={pdfName}
            >
              {({ loading }) => (
                <span className="inline-flex items-center">
                  <Download className="mr-1.5 h-4 w-4" />
                  {loading ? 'Đang tạo PDF…' : 'Tải PDF'}
                </span>
              )}
            </PDFDownloadLink>
          </Button>
        </div>
      </div>

      {/* Approval banner (INV-1) */}
      {paper.status === 'published' && paper.approval ? (
        <div className="flex items-start gap-2 rounded-md bg-emerald-50 p-3 text-sm text-emerald-700">
          <ShieldCheck className="mt-0.5 h-4 w-4 shrink-0" />
          <span>
            Đã phê duyệt &amp; xuất bản bởi <strong>{paper.approval.approvedByName}</strong> —{' '}
            {new Date(paper.approval.approvedAt).toLocaleString('vi-VN')}
            {paper.approval.note ? ` · “${paper.approval.note}”` : ''}
          </span>
        </div>
      ) : (
        <Badge className="bg-slate-100 text-slate-600">Bản thảo (chưa xuất bản)</Badge>
      )}

      {/* Rendered paper */}
      <Card>
        <CardContent className="space-y-4 p-8">
          <header>
            <h1 className="font-serif text-2xl font-semibold text-foreground">
              {paper.title || '(Chưa đặt tiêu đề)'}
            </h1>
            {paper.titleEn ? <p className="text-muted-foreground">{paper.titleEn}</p> : null}
            <p className="mt-1 text-xs text-muted-foreground">Đề tài: {projectTitle}</p>
          </header>

          {paper.abstractVi ? (
            <section>
              <h2 className="font-serif text-sm font-semibold">Tóm tắt</h2>
              <p className="whitespace-pre-wrap text-sm text-foreground">{paper.abstractVi}</p>
            </section>
          ) : null}
          {paper.abstractEn ? (
            <section>
              <h2 className="font-serif text-sm font-semibold">Abstract</h2>
              <p className="whitespace-pre-wrap text-sm text-foreground">{paper.abstractEn}</p>
            </section>
          ) : null}
          {paper.body ? (
            <section>
              <h2 className="font-serif text-sm font-semibold">Nội dung</h2>
              <p className="whitespace-pre-wrap text-sm text-foreground">{paper.body}</p>
            </section>
          ) : null}

          {paper.sources.length > 0 ? (
            <section>
              <h2 className="font-serif text-sm font-semibold">Tài liệu tham khảo</h2>
              <ol className="list-decimal space-y-1 pl-5 text-sm text-foreground">
                {paper.sources.map((s) => (
                  <li key={s.id}>
                    {s.title}
                    {s.authors ? ` — ${s.authors}` : ''}
                    {s.doiOrUrl ? ` (${s.doiOrUrl})` : ''}
                    {s.verifiedReal ? ' ✓' : ''}
                  </li>
                ))}
              </ol>
            </section>
          ) : null}
        </CardContent>
      </Card>

      {/* Process / provenance log (INV-6) */}
      <Card>
        <CardContent className="space-y-2 p-5">
          <h2 className="font-serif text-sm font-semibold">Nhật ký quá trình</h2>
          <Separator />
          <ol className="space-y-1.5">
            {(audit ?? []).slice(0, 12).map((a) => (
              <li key={a.id} className="flex items-start gap-2 text-xs text-muted-foreground">
                <span className="tabular-nums">
                  {a.occurredAt ? new Date(a.occurredAt).toLocaleString('vi-VN') : ''}
                </span>
                <span className="text-foreground">
                  {a.actorName}: {a.action} {a.subject}
                </span>
              </li>
            ))}
            {(audit ?? []).length === 0 && (
              <li className="text-xs text-muted-foreground">Chưa có hoạt động.</li>
            )}
          </ol>
        </CardContent>
      </Card>
    </div>
  );
}
