import { useQuery } from '@tanstack/react-query';
import {
  Bot,
  Brain,
  CheckCircle2,
  FileSearch,
  ShieldAlert,
  UserCheck,
  type LucideIcon,
} from 'lucide-react';

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

import { listPublishableProjects } from '@/features/papers/api/papersApi';
import {
  HUMAN_ROLE_NOTE,
  OPERATING_PRINCIPLES,
  humanApprovalIntact,
  statusFromProjects,
  type GovernancePrinciple,
} from '@/features/papers/domain/governance';

const ICONS: Record<GovernancePrinciple['icon'], LucideIcon> = {
  human: UserCheck,
  bot: Bot,
  sourced: FileSearch,
  gate: ShieldAlert,
};

function PrincipleCard({ principle }: { principle: GovernancePrinciple }) {
  const Icon = ICONS[principle.icon];
  const danger = principle.tone === 'danger';
  return (
    <Card className="border-blue-100">
      <CardContent className="flex gap-3 p-4">
        <div
          className={cn(
            'flex h-9 w-9 shrink-0 items-center justify-center rounded-lg',
            danger ? 'bg-rose-50 text-rose-600' : 'bg-blue-50 text-blue-700',
          )}
        >
          <Icon className="h-5 w-5" />
        </div>
        <div className="space-y-1">
          <h3 className="font-serif text-sm font-semibold text-foreground">{principle.title}</h3>
          <p className="text-sm text-muted-foreground">{principle.description}</p>
          <p className="text-xs text-blue-700">
            <span className="font-medium">Trong hệ thống: </span>
            {principle.enforcement}
          </p>
        </div>
      </CardContent>
    </Card>
  );
}

function StatTile({ label, value, tone }: { label: string; value: number; tone?: 'danger' | 'ok' }) {
  return (
    <div className="rounded-lg border border-border p-3 text-center">
      <div
        className={cn(
          'text-2xl font-semibold tabular-nums',
          tone === 'danger' ? 'text-rose-600' : tone === 'ok' ? 'text-emerald-600' : 'text-foreground',
        )}
      >
        {value}
      </div>
      <div className="text-xs text-muted-foreground">{label}</div>
    </div>
  );
}

/**
 * Governance module — the publisher's operating philosophy ("Triết lý vận hành") plus a live
 * compliance snapshot computed from the investigator's papers.
 */
export function GovernancePage() {
  const { data: projects } = useQuery({
    queryKey: ['publisher', 'publishable-projects'],
    queryFn: listPublishableProjects,
  });

  const status = statusFromProjects(projects ?? []);
  const inv1Ok = humanApprovalIntact(status);

  return (
    <div className="mx-auto max-w-3xl space-y-5">
      {/* Header band — mirrors the diagram's blue "TRIẾT LÝ VẬN HÀNH" header. */}
      <div className="flex items-center gap-3 rounded-xl bg-blue-800 px-5 py-4 text-white">
        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-white/15">
          <Brain className="h-6 w-6" />
        </div>
        <div>
          <h1 className="font-serif text-lg font-bold uppercase tracking-wide">Triết lý vận hành</h1>
          <p className="text-sm text-blue-100">Nguyên tắc quản trị quy trình công bố</p>
        </div>
      </div>

      {/* Principles */}
      <div className="space-y-3">
        {OPERATING_PRINCIPLES.map((p) => (
          <PrincipleCard key={p.id} principle={p} />
        ))}

        {/* Human-role footer — the diagram's dashed note. */}
        <div className="flex items-start gap-3 rounded-xl border-2 border-dashed border-blue-200 bg-blue-50/40 p-4">
          <UserCheck className="mt-0.5 h-5 w-5 shrink-0 text-blue-700" />
          <p className="text-sm italic text-blue-900">{HUMAN_ROLE_NOTE}</p>
        </div>
      </div>

      {/* Live compliance snapshot — ties the philosophy to the actual papers. */}
      <Card>
        <CardContent className="space-y-4 p-5">
          <div className="flex items-center justify-between">
            <h2 className="font-serif text-base font-semibold text-foreground">Tình trạng tuân thủ</h2>
            {inv1Ok ? (
              <Badge className="bg-emerald-100 text-emerald-700">
                <CheckCircle2 className="mr-1 h-3.5 w-3.5" /> Human-in-the-loop đảm bảo
              </Badge>
            ) : (
              <Badge className="bg-rose-100 text-rose-700">
                <ShieldAlert className="mr-1 h-3.5 w-3.5" /> Có bài xuất bản thiếu phê duyệt
              </Badge>
            )}
          </div>

          <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
            <StatTile label="Tổng số bài báo" value={status.totalPapers} />
            <StatTile label="Đã xuất bản" value={status.published} tone="ok" />
            <StatTile
              label="Bản thảo bị chặn (thiếu nguồn)"
              value={status.draftsBlockedByIntegrity}
              tone={status.draftsBlockedByIntegrity > 0 ? 'danger' : undefined}
            />
            <StatTile label="Sẵn sàng phê duyệt" value={status.draftsReadyToPublish} />
          </div>

          <p className="text-xs text-muted-foreground">
            {status.published === status.publishedWithApproval
              ? `Tất cả ${status.published} bài báo đã xuất bản đều có hồ sơ phê duyệt của con người (INV-1).`
              : `Cảnh báo: ${status.published - status.publishedWithApproval} bài xuất bản thiếu hồ sơ phê duyệt.`}
          </p>
        </CardContent>
      </Card>
    </div>
  );
}
