import { useMemo, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { CheckCircle2, XCircle } from 'lucide-react';

import {
  Badge,
  Button,
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  Input,
  Label,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Textarea,
  approveProject,
  detailFromApiError,
  formatIsoToDdMmYyyyHhMm,
  listMyProjects,
  rejectProject,
  PROJECT_STATUS_LABEL,
  useAuth,
  type ProjectStatus,
  type ResearchProject,
} from '@ump/shared';

const STATUS_FILTERS: { value: ProjectStatus | 'all'; label: string }[] = [
  { value: 'submitted', label: 'Chờ duyệt' },
  { value: 'approved', label: 'Đã duyệt' },
  { value: 'rejected', label: 'Bị từ chối' },
  { value: 'all', label: 'Tất cả' },
];

function statusBadge(s: ProjectStatus) {
  const variant = s === 'approved' ? 'default' : s === 'rejected' ? 'destructive' : s === 'submitted' ? 'secondary' : 'outline';
  return <Badge variant={variant}>{PROJECT_STATUS_LABEL[s]}</Badge>;
}

function prettyKey(k: string): string {
  const base = k.split('.').pop() ?? k;
  return base.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/^./, (c) => c.toUpperCase());
}

function contentEntries(content: Record<string, unknown>): { key: string; label: string; value: string }[] {
  return Object.entries(content)
    .filter(([, v]) => v !== '' && v != null && !(Array.isArray(v) && v.length === 0))
    .map(([k, v]) => ({
      key: k,
      label: prettyKey(k),
      value: Array.isArray(v) ? `${v.length} mục` : String(v),
    }));
}

export function ResearchReviewPage() {
  const { hasRole } = useAuth();
  const isAdmin = hasRole('admin');
  const qc = useQueryClient();
  const [statusFilter, setStatusFilter] = useState<ProjectStatus | 'all'>('submitted');
  const [review, setReview] = useState<ResearchProject | null>(null);

  const projectsQuery = useQuery({
    queryKey: ['research-review'],
    queryFn: () => listMyProjects({ mine: false }),
    enabled: isAdmin,
  });
  const all = projectsQuery.data ?? [];
  const rows = useMemo(
    () => (statusFilter === 'all' ? all : all.filter((p) => p.status === statusFilter)),
    [all, statusFilter],
  );

  const invalidate = () => qc.invalidateQueries({ queryKey: ['research-review'] });
  const approveMut = useMutation({
    mutationFn: (v: { id: string; code?: string; note?: string }) => approveProject(v.id, { code: v.code, note: v.note }),
    onSuccess: () => {
      toast.success('Đã phê duyệt đề tài — bảng điều khiển của chủ nhiệm đã mở.');
      setReview(null);
      void invalidate();
    },
    onError: (e) => toast.error(detailFromApiError(e, 'Phê duyệt thất bại.')),
  });
  const rejectMut = useMutation({
    mutationFn: (v: { id: string; note?: string }) => rejectProject(v.id, { note: v.note }),
    onSuccess: () => {
      toast.success('Đã từ chối đề tài.');
      setReview(null);
      void invalidate();
    },
    onError: (e) => toast.error(detailFromApiError(e, 'Từ chối thất bại.')),
  });

  if (!isAdmin) {
    return <p className="text-sm text-muted-foreground">Chỉ tài khoản quản trị mới thẩm định được đề tài.</p>;
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-xl font-semibold tracking-tight">Thẩm định đề tài nghiên cứu</h1>
          <p className="text-sm text-muted-foreground">
            Xem các thuyết minh đề tài đã nộp và phê duyệt / từ chối. Phê duyệt sẽ mở bảng điều khiển quản lý cho chủ nhiệm.
          </p>
        </div>
        <Select value={statusFilter} onValueChange={(v) => setStatusFilter(v as ProjectStatus | 'all')}>
          <SelectTrigger className="w-44">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {STATUS_FILTERS.map((s) => (
              <SelectItem key={s.value} value={s.value}>
                {s.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Danh sách đề tài</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[50px]">STT</TableHead>
                  <TableHead className="min-w-[240px]">Tên đề tài</TableHead>
                  <TableHead className="min-w-[160px]">Chủ nhiệm</TableHead>
                  <TableHead className="w-[140px]">Cấp</TableHead>
                  <TableHead className="w-[150px]">Ngày nộp</TableHead>
                  <TableHead className="w-[120px]">Trạng thái</TableHead>
                  <TableHead className="w-[120px] text-center">Thao tác</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {projectsQuery.isLoading ? (
                  <TableRow>
                    <TableCell colSpan={7} className="py-10 text-center text-muted-foreground">Đang tải…</TableCell>
                  </TableRow>
                ) : projectsQuery.isError ? (
                  <TableRow>
                    <TableCell colSpan={7} className="py-10 text-center text-destructive">Không tải được danh sách đề tài.</TableCell>
                  </TableRow>
                ) : rows.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={7} className="py-10 text-center text-muted-foreground">Không có đề tài nào.</TableCell>
                  </TableRow>
                ) : (
                  rows.map((p, i) => (
                    <TableRow key={p.id}>
                      <TableCell>{i + 1}</TableCell>
                      <TableCell className="font-medium">{p.title || '(Chưa đặt tên)'}</TableCell>
                      <TableCell className="text-muted-foreground">{p.piName || '—'}</TableCell>
                      <TableCell className="text-muted-foreground">{p.level || '—'}</TableCell>
                      <TableCell className="text-muted-foreground">
                        {p.submittedAt ? formatIsoToDdMmYyyyHhMm(p.submittedAt) : '—'}
                      </TableCell>
                      <TableCell>{statusBadge(p.status)}</TableCell>
                      <TableCell className="text-center">
                        <Button size="sm" variant="outline" onClick={() => setReview(p)}>
                          {p.status === 'submitted' ? 'Xem & duyệt' : 'Xem'}
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      <ReviewDialog
        project={review}
        submitting={approveMut.isPending || rejectMut.isPending}
        onOpenChange={(o) => !o && setReview(null)}
        onApprove={(code, note) => review && approveMut.mutate({ id: review.id, code, note })}
        onReject={(note) => review && rejectMut.mutate({ id: review.id, note })}
      />
    </div>
  );
}

function ReviewDialog(props: {
  project: ResearchProject | null;
  submitting: boolean;
  onOpenChange: (open: boolean) => void;
  onApprove: (code?: string, note?: string) => void;
  onReject: (note?: string) => void;
}) {
  const { project, submitting, onOpenChange, onApprove, onReject } = props;
  const [code, setCode] = useState('');
  const [note, setNote] = useState('');
  const [syncedId, setSyncedId] = useState<string | null>(null);

  if (project && project.id !== syncedId) {
    setSyncedId(project.id);
    setCode(project.code ?? '');
    setNote(project.reviewNote ?? '');
  }

  const entries = project ? contentEntries(project.content) : [];
  const pending = project?.status === 'submitted';

  return (
    <Dialog open={project != null} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[88vh] overflow-y-auto sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle className="font-serif">{project?.title || 'Thuyết minh đề tài'}</DialogTitle>
        </DialogHeader>

        {project && (
          <div className="space-y-4 py-1 text-sm">
            <div className="grid grid-cols-2 gap-x-4 gap-y-1.5">
              <div><span className="text-muted-foreground">Chủ nhiệm:</span> {project.piName || '—'}</div>
              <div><span className="text-muted-foreground">Cấp:</span> {project.level || '—'}</div>
              <div><span className="text-muted-foreground">Thời gian:</span> {project.periodMonths ? `${project.periodMonths} tháng` : '—'}</div>
              <div><span className="text-muted-foreground">Kinh phí:</span> {project.budgetTotal != null ? `${project.budgetTotal} tr.đ` : '—'}</div>
              <div className="col-span-2"><span className="text-muted-foreground">Trạng thái:</span> {statusBadge(project.status)}</div>
            </div>

            <div>
              <Label className="mb-1 block">Nội dung thuyết minh</Label>
              <div className="max-h-64 space-y-1.5 overflow-y-auto rounded-md border bg-muted/30 p-3">
                {entries.length === 0 ? (
                  <p className="text-xs text-muted-foreground">Không có nội dung.</p>
                ) : (
                  entries.map((e) => (
                    <div key={e.key} className="grid grid-cols-[180px_1fr] gap-2">
                      <span className="truncate text-xs text-muted-foreground" title={e.label}>{e.label}</span>
                      <span className="whitespace-pre-wrap break-words">{e.value}</span>
                    </div>
                  ))
                )}
              </div>
            </div>

            {pending ? (
              <div className="space-y-3 border-t pt-3">
                <div className="space-y-1.5">
                  <Label htmlFor="rv-code">Mã số (cấp khi phê duyệt, tùy chọn)</Label>
                  <Input id="rv-code" value={code} onChange={(e) => setCode(e.target.value)} placeholder="VD: ĐTUD-2026-001" disabled={submitting} />
                </div>
                <div className="space-y-1.5">
                  <Label htmlFor="rv-note">Nhận xét / lý do</Label>
                  <Textarea id="rv-note" value={note} onChange={(e) => setNote(e.target.value)} placeholder="Nhận xét của hội đồng…" disabled={submitting} />
                </div>
              </div>
            ) : project.reviewNote ? (
              <div className="border-t pt-3">
                <Label className="mb-1 block">Nhận xét</Label>
                <p className="text-muted-foreground">{project.reviewNote}</p>
              </div>
            ) : null}
          </div>
        )}

        <DialogFooter>
          {pending ? (
            <>
              <Button variant="outline" onClick={() => onReject(note.trim() || undefined)} disabled={submitting} className="gap-1.5">
                <XCircle className="h-4 w-4" /> Từ chối
              </Button>
              <Button onClick={() => onApprove(code.trim() || undefined, note.trim() || undefined)} disabled={submitting} className="gap-1.5">
                <CheckCircle2 className="h-4 w-4" /> Phê duyệt
              </Button>
            </>
          ) : (
            <Button variant="outline" onClick={() => onOpenChange(false)}>Đóng</Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
