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

import {
  Button,
  Card,
  CardContent,
  Input,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  cn,
  listMyProjects,
  PROJECT_STATUS_LABEL,
  type ProjectStatus,
  type ResearchProject,
} from '@ump/shared';

/**
 * Semantic status pill — keyed by the lifecycle enum (the proposal labels differ slightly
 * from the cockpit status vocabulary, so the shared `toneClass` map can't be reused as-is).
 * Colours mirror the cockpit TONE_CLASS palette for visual consistency.
 */
const STATUS_TONE: Record<ProjectStatus, string> = {
  approved: 'bg-emerald-100 text-emerald-700 border-emerald-200',
  submitted: 'bg-amber-100 text-amber-700 border-amber-200',
  draft: 'bg-slate-100 text-slate-600 border-slate-200',
  rejected: 'bg-rose-100 text-rose-700 border-rose-200',
};

function StatusBadge({ status }: { status: ProjectStatus }) {
  return (
    <span
      className={cn(
        'inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium',
        STATUS_TONE[status],
      )}
    >
      {PROJECT_STATUS_LABEL[status]}
    </span>
  );
}

type TabKey = 'all' | ProjectStatus;

// Filter tabs, ordered along the proposal lifecycle (mirrors the báo cáo list ordering).
const TABS: Array<{ key: TabKey; label: string }> = [
  { key: 'all', label: 'Tất cả' },
  { key: 'draft', label: PROJECT_STATUS_LABEL.draft },
  { key: 'submitted', label: PROJECT_STATUS_LABEL.submitted },
  { key: 'approved', label: PROJECT_STATUS_LABEL.approved },
  { key: 'rejected', label: PROJECT_STATUS_LABEL.rejected },
];

/**
 * Landing page — the PI's research projects, presented as a filterable table (matching the
 * "Danh sách báo cáo" layout). Approved projects open the cockpit; anything else opens the
 * proposal (draft editor / read-only pending view).
 */
export function ProjectsListPage() {
  const navigate = useNavigate();
  const [tab, setTab] = useState<TabKey>('all');
  const [query, setQuery] = useState('');

  const { data: projects, isLoading, isError } = useQuery({
    queryKey: ['research', 'projects', 'mine'],
    queryFn: () => listMyProjects(),
  });

  const open = (p: ResearchProject) =>
    navigate(p.status === 'approved' ? `/dashboard/projects/${p.id}` : `/dashboard/proposals/${p.id}`);

  // Per-status counts for the filter-tab badges.
  const counts = useMemo(() => {
    const c: Record<TabKey, number> = { all: 0, draft: 0, submitted: 0, approved: 0, rejected: 0 };
    for (const p of projects ?? []) {
      c.all += 1;
      c[p.status] += 1;
    }
    return c;
  }, [projects]);

  const visible = useMemo(() => {
    const q = query.trim().toLowerCase();
    return (projects ?? []).filter((p) => {
      if (tab !== 'all' && p.status !== tab) return false;
      if (!q) return true;
      return (
        (p.title || '').toLowerCase().includes(q) ||
        (p.code || '').toLowerCase().includes(q) ||
        (p.level || '').toLowerCase().includes(q)
      );
    });
  }, [projects, tab, query]);

  return (
    <div className="mx-auto max-w-6xl space-y-5">
      {/* Page header */}
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-2.5">
          <FlaskConical className="h-6 w-6 shrink-0 text-primary" />
          <div>
            <h1 className="font-serif text-2xl font-semibold text-foreground">Đề tài của tôi</h1>
            <p className="text-sm text-muted-foreground">
              Đăng ký thuyết minh và quản lý tiến độ đề tài nghiên cứu.
            </p>
          </div>
        </div>
        <Button asChild>
          <Link to="/dashboard/proposals/new">
            <Plus className="mr-2 h-4 w-4" /> Đăng ký đề tài mới
          </Link>
        </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>}

      {/* Empty (no projects at all) */}
      {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">
              Bạn chưa có đề tài nào. Bấm “Đăng ký đề tài mới” để bắt đầu.
            </p>
          </CardContent>
        </Card>
      )}

      {/* List panel: section header + count, search, filter tabs, table */}
      {projects && projects.length > 0 && (
        <Card>
          <CardContent className="space-y-4 p-5">
            {/* Section header: title + count (left) · search (right) */}
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div>
                <h2 className="font-serif text-lg font-semibold text-foreground">Danh sách đề tài</h2>
                <p className="text-sm text-muted-foreground">{projects.length} đề tài</p>
              </div>
              <div className="relative">
                <Search className="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  placeholder="Tìm mã số, tên đề tài, cấp…"
                  className="h-9 w-64 pl-8"
                />
              </div>
            </div>

            {/* Filter tabs */}
            <div className="flex flex-wrap gap-1 border-b border-border pb-2">
              {TABS.map((tb) => (
                <button
                  key={tb.key}
                  type="button"
                  onClick={() => setTab(tb.key)}
                  className={cn(
                    'inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium transition',
                    tab === tb.key ? 'bg-foreground text-background' : 'text-muted-foreground hover:bg-muted',
                  )}
                >
                  {tb.label}
                  <span
                    className={cn(
                      'rounded-full px-1.5 text-xs',
                      tab === tb.key ? 'bg-background/20' : 'bg-muted text-muted-foreground',
                    )}
                  >
                    {counts[tb.key]}
                  </span>
                </button>
              ))}
            </div>

            {/* Table / filtered-empty */}
            {visible.length === 0 ? (
              <div className="py-12 text-center text-sm text-muted-foreground">
                Không tìm thấy đề tài phù hợp.
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[130px]">Mã số</TableHead>
                    <TableHead>Tên đề tài</TableHead>
                    <TableHead className="w-[140px]">Cấp</TableHead>
                    <TableHead className="w-[110px]">Thời gian</TableHead>
                    <TableHead className="w-[150px]">Trạng thái</TableHead>
                    <TableHead className="w-[110px] text-right">Thao tác</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {visible.map((p) => (
                    <TableRow key={p.id} className="cursor-pointer" onClick={() => open(p)}>
                      <TableCell className="font-medium tabular-nums text-foreground">
                        {p.code || '—'}
                      </TableCell>
                      <TableCell className="max-w-[420px]">
                        <div className="flex items-center gap-2">
                          <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                          <span className="truncate font-medium text-foreground">
                            {p.title || '(Chưa đặt tên đề tài)'}
                          </span>
                        </div>
                        {p.status === 'rejected' && p.reviewNote ? (
                          <div className="mt-0.5 truncate pl-5 text-xs text-destructive">
                            Lý do từ chối: {p.reviewNote}
                          </div>
                        ) : null}
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">{p.level || '—'}</TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {p.periodMonths ? `${p.periodMonths} tháng` : '—'}
                      </TableCell>
                      <TableCell>
                        <StatusBadge status={p.status} />
                      </TableCell>
                      <TableCell className="text-right">
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-8"
                          onClick={(e) => {
                            e.stopPropagation();
                            open(p);
                          }}
                        >
                          Mở <ArrowUpRight className="ml-1 h-3.5 w-3.5" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}
