import { Loader2 } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';

import type { AuditListItem } from '@/audit/types';
import { fetchAuditEventDetail } from '@/audit/adminAuditApi';
import { formatAuditLocal } from '@/audit/formatAuditTime';
import { describeJsonMicrodiff } from '@/audit/jsonMicrodiffLines';
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { auditActionLabel } from '@/applicant/audit/actionLabels';

interface AuditEventDetailSheetProps {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  summary: AuditListItem | null;
}

export function AuditEventDetailSheet({
  open,
  onOpenChange,
  summary,
}: AuditEventDetailSheetProps) {
  const q = useQuery({
    queryKey: ['admin-audit-detail', summary?.id],
    queryFn: () => fetchAuditEventDetail(summary!.id),
    enabled: open && !!summary?.id,
  });

  const diffLines =
    q.data?.before !== undefined || q.data?.after !== undefined
      ? describeJsonMicrodiff(q.data?.before ?? null, q.data?.after ?? null)
      : [];

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="flex w-full flex-col gap-4 sm:max-w-2xl md:max-w-4xl overflow-hidden">
        <SheetHeader className="pr-12">
          <SheetTitle>Chi tiết sự kiện #{summary?.id ?? '…'}</SheetTitle>
          <SheetDescription>
            {summary
              ? `${formatAuditLocal(summary.occurred_at)} · ${auditActionLabel(summary.action)} · ${summary.entity_type}${summary.entity_id ? ` (${summary.entity_id})` : ''}`
              : 'Chọn một dòng trong bảng'}
          </SheetDescription>
        </SheetHeader>

        {q.isLoading && (
          <div className="flex items-center gap-2 text-muted-foreground text-sm">
            <Loader2 className="h-4 w-4 animate-spin" />
            Đang tải payload…
          </div>
        )}

        {q.data && (
          <ScrollArea className="flex-1 -mx-4 px-4">
            <div className="space-y-4 pb-6">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
                <div>
                  <div className="text-muted-foreground text-xs mb-1">Actor</div>
                  <div className="font-medium">{q.data.actor_email}</div>
                  <div className="text-muted-foreground text-xs">{q.data.actor_role}</div>
                </div>
                <div>
                  <div className="text-muted-foreground text-xs mb-1">Request ID</div>
                  <div className="font-mono text-xs break-all">{q.data.request_id ?? '—'}</div>
                </div>
              </div>

              <div>
                <div className="text-muted-foreground text-xs mb-1">Metadata</div>
                <pre className="text-xs bg-muted rounded-md p-3 overflow-x-auto max-h-40">
                  {JSON.stringify(q.data.metadata, null, 2)}
                </pre>
              </div>

              <Separator />

              <div>
                <div className="text-sm font-medium mb-2">Chênh lệch (client-side microdiff)</div>
                {diffLines.length === 0 ? (
                  <p className="text-sm text-muted-foreground">Không có before/after hoặc không đổi.</p>
                ) : (
                  <ul className="text-xs font-mono space-y-1 list-disc pl-4 max-h-40 overflow-y-auto">
                    {diffLines.map((line) => (
                      <li key={line}>{line}</li>
                    ))}
                  </ul>
                )}
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div>
                  <div className="text-xs text-muted-foreground mb-1">before</div>
                  <pre className="text-xs bg-muted rounded-md p-3 overflow-x-auto max-h-72">
                    {q.data.before != null ? JSON.stringify(q.data.before, null, 2) : '—'}
                  </pre>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground mb-1">after</div>
                  <pre className="text-xs bg-muted rounded-md p-3 overflow-x-auto max-h-72">
                    {q.data.after != null ? JSON.stringify(q.data.after, null, 2) : '—'}
                  </pre>
                </div>
              </div>
            </div>
          </ScrollArea>
        )}
      </SheetContent>
    </Sheet>
  );
}
