'use client';

import Link from 'next/link';
import { use } from 'react';
import { ChevronLeft } from 'lucide-react';
import { Permission } from '@pac/types';
import { Can } from '@/components/can';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { useAiInvocationDetail } from '@/components/ai-invocations/use-ai-invocations';
import { AiInvocationDetailApp } from '@/components/ai-invocations/ai-invocation-detail-app';

export default function AiInvocationDetailRoutePage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = use(params);
  return (
    <Can
      perm={Permission.PLATFORM_MANAGE}
      fallback={
        <main className="container mx-auto max-w-3xl p-8">
          <Card>
            <CardContent className="py-10 text-center text-sm text-muted-foreground">
              需要 admin 权限。
            </CardContent>
          </Card>
        </main>
      }
    >
      <Loader id={id} />
    </Can>
  );
}

function Loader({ id }: { id: string }) {
  const { state, refresh } = useAiInvocationDetail(id);

  if (state.status === 'loading' || state.status === 'idle') {
    return (
      <div className="flex h-screen items-center justify-center text-sm text-muted-foreground">
        加载调用详情…
      </div>
    );
  }

  if (state.status === 'error') {
    return (
      <main className="container mx-auto max-w-3xl p-8 space-y-3">
        <Button asChild variant="ghost" size="sm">
          <Link href="/admin/ai-invocations">
            <ChevronLeft className="h-4 w-4" /> 返回列表
          </Link>
        </Button>
        <Card>
          <CardContent className="space-y-3 py-10 text-center">
            <div className="text-lg font-semibold text-rose-600">无法加载</div>
            <div className="text-sm text-muted-foreground">
              code={state.code ?? '?'} · {state.message}
            </div>
            <Button variant="outline" size="sm" onClick={refresh}>重试</Button>
          </CardContent>
        </Card>
      </main>
    );
  }

  return (
    <>
      <div className="border-b bg-background">
        <div className="container mx-auto max-w-5xl flex items-center gap-3 px-6 h-10">
          <Button asChild variant="ghost" size="sm" className="h-7 -ml-2">
            <Link href="/admin/ai-invocations">
              <ChevronLeft className="h-4 w-4" /> AI 调用列表
            </Link>
          </Button>
          <div className="text-xs text-muted-foreground font-mono">
            invocation {id.slice(0, 8)}…
          </div>
        </div>
      </div>
      <AiInvocationDetailApp data={state.data} />
    </>
  );
}
