import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import { ArrowUpRight, BookOpenCheck, FileText, FlaskConical, Plus } from 'lucide-react';

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

import { listPublishableProjects } from '@/features/papers/api/papersApi';
import { extractPapers, type Paper } from '@/features/papers/domain/paperModel';

type Tab = 'projects' | 'published';

function PaperStatusBadge({ status }: { status: Paper['status'] }) {
  return status === 'published' ? (
    <Badge className="bg-emerald-100 text-emerald-700">Đã xuất bản</Badge>
  ) : (
    <Badge className="bg-slate-100 text-slate-600">Bản thảo</Badge>
  );
}

/**
 * Landing page. Lists the investigator's APPROVED research projects (the publishable result
 * sources) with their papers, plus a cross-project "Đã xuất bản" view.
 */
export function PublishablePapersList() {
  const [tab, setTab] = useState<Tab>('projects');

  const { data: projects, isLoading, isError } = useQuery({
    queryKey: ['publisher', 'publishable-projects'],
    queryFn: listPublishableProjects,
  });

  const publishedRows = useMemo(() => {
    const rows: Array<{ projectId: string; projectTitle: string; paper: Paper }> = [];
    for (const p of projects ?? []) {
      for (const paper of extractPapers(p.content)) {
        if (paper.status === 'published') {
          rows.push({ projectId: p.id, projectTitle: p.title, paper });
        }
      }
    }
    return rows.sort((a, b) => (b.paper.publishedAt ?? '').localeCompare(a.paper.publishedAt ?? ''));
  }, [projects]);

  return (
    <div className="mx-auto max-w-5xl space-y-5">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-2.5">
          <BookOpenCheck className="h-6 w-6 shrink-0 text-primary" />
          <div>
            <h1 className="font-serif text-2xl font-semibold text-foreground">Công bố bài báo</h1>
            <p className="text-sm text-muted-foreground">
              Soạn và xuất bản bài báo từ kết quả nghiên cứu của các đề tài đã được phê duyệt.
            </p>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 border-b border-border pb-2">
        {([
          { key: 'projects', label: 'Đề tài có thể công bố' },
          { key: 'published', label: `Đã xuất bản (${publishedRows.length})` },
        ] as Array<{ key: Tab; label: string }>).map((t) => (
          <button
            key={t.key}
            type="button"
            onClick={() => setTab(t.key)}
            className={cn(
              'rounded-lg px-3 py-1.5 text-sm font-medium transition',
              tab === t.key ? 'bg-foreground text-background' : 'text-muted-foreground hover:bg-muted',
            )}
          >
            {t.label}
          </button>
        ))}
      </div>

      {isLoading && <p className="text-sm text-muted-foreground">Đang tải…</p>}
      {isError && <p className="text-sm text-destructive">Không tải được danh sách đề tài.</p>}

      {/* Projects tab */}
      {tab === 'projects' && projects && projects.length === 0 && (
        <Card className="text-center">
          <CardContent className="py-12">
            <FlaskConical className="mx-auto mb-3 h-10 w-10 text-muted-foreground" />
            <p className="text-sm text-muted-foreground">
              Chưa có đề tài nào được phê duyệt. Chỉ đề tài đã phê duyệt mới có thể công bố bài báo.
            </p>
          </CardContent>
        </Card>
      )}

      {tab === 'projects' &&
        (projects ?? []).map((project) => {
          const papers = extractPapers(project.content);
          return (
            <Card key={project.id}>
              <CardContent className="space-y-3 p-5">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div>
                    <div className="flex items-center gap-2">
                      <FlaskConical className="h-4 w-4 text-primary" />
                      <h2 className="font-serif text-lg font-semibold text-foreground">
                        {project.title || '(Chưa đặt tên đề tài)'}
                      </h2>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      {project.code ? `${project.code} · ` : ''}
                      {project.level} · {papers.length} bài báo
                    </p>
                  </div>
                  <Button asChild size="sm">
                    <Link to={`/dashboard/papers/${project.id}/compose`}>
                      <Plus className="mr-1.5 h-4 w-4" /> Soạn bài báo mới
                    </Link>
                  </Button>
                </div>

                {papers.length > 0 && (
                  <ul className="divide-y divide-border rounded-md border border-border">
                    {papers.map((paper) => (
                      <li
                        key={paper.id}
                        className="flex items-center justify-between gap-3 px-3 py-2 text-sm"
                      >
                        <div className="flex min-w-0 items-center gap-2">
                          <FileText className="h-4 w-4 shrink-0 text-muted-foreground" />
                          <span className="truncate font-medium text-foreground">
                            {paper.title || '(Chưa đặt tiêu đề)'}
                          </span>
                          <PaperStatusBadge status={paper.status} />
                        </div>
                        <div className="flex shrink-0 gap-2">
                          {paper.status === 'published' && (
                            <Button asChild variant="ghost" size="sm" className="h-8">
                              <Link to={`/dashboard/papers/${project.id}/${paper.id}`}>
                                Xem <ArrowUpRight className="ml-1 h-3.5 w-3.5" />
                              </Link>
                            </Button>
                          )}
                          <Button asChild variant="outline" size="sm" className="h-8">
                            <Link to={`/dashboard/papers/${project.id}/compose?paperId=${paper.id}`}>
                              {paper.status === 'published' ? 'Sửa' : 'Tiếp tục soạn'}
                            </Link>
                          </Button>
                        </div>
                      </li>
                    ))}
                  </ul>
                )}
              </CardContent>
            </Card>
          );
        })}

      {/* Published tab */}
      {tab === 'published' && (
        <Card>
          <CardContent className="p-5">
            {publishedRows.length === 0 ? (
              <div className="py-10 text-center text-sm text-muted-foreground">
                Chưa có bài báo nào được xuất bản.
              </div>
            ) : (
              <ul className="divide-y divide-border">
                {publishedRows.map(({ projectId, projectTitle, paper }) => (
                  <li key={paper.id} className="flex items-center justify-between gap-3 py-3 text-sm">
                    <div className="min-w-0">
                      <div className="truncate font-medium text-foreground">{paper.title}</div>
                      <div className="truncate text-xs text-muted-foreground">
                        {projectTitle} ·{' '}
                        {paper.publishedAt
                          ? new Date(paper.publishedAt).toLocaleDateString('vi-VN')
                          : ''}
                      </div>
                    </div>
                    <Button asChild variant="ghost" size="sm" className="h-8 shrink-0">
                      <Link to={`/dashboard/papers/${projectId}/${paper.id}`}>
                        Xem <ArrowUpRight className="ml-1 h-3.5 w-3.5" />
                      </Link>
                    </Button>
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}
