'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 { PlanDetailApp } from '@/components/plan-detail/plan-detail-app';
import { adaptData } from '@/components/plan-detail/adapt-data';
import { usePlanAggregate } from '@/components/plans/use-plan-aggregate';
import { useAuthStore } from '@/stores/auth-store';
import { TaskDrawer } from '@/components/plan-detail/task-drawer';

/**
 * /plans/[planId] — Plan 详情(生产版)。
 *
 * 跟 (demo)/plan-detail/:externalId 区别:
 *   - 走 (app) 布局(AuthGate);
 *   - 调 /pac/v1/plans/:id/full(强 zod 不走 demo 路径);
 *   - 同样复用 <PlanDetailApp> + adapt-data(响应 shape 一致)。
 */
export default function PlanDetailRoutePage({ params }: { params: Promise<{ planId: string }> }) {
  const { planId } = use(params);
  return (
    <Can
      perm={Permission.PLAN_VIEW_OWN}
      fallback={
        <main className="container mx-auto max-w-3xl p-8">
          <Card>
            <CardContent className="py-10 text-center text-sm text-muted-foreground">
              需要 PLAN_VIEW_OWN 权限。
            </CardContent>
          </Card>
        </main>
      }
    >
      <PlanDetailLoader planId={planId} />
    </Can>
  );
}

function PlanDetailLoader({ planId }: { planId: string }) {
  const { state, refresh } = usePlanAggregate(planId);
  const dictionary = useAuthStore((s) => s.user?.dictionary);

  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="/plans">
            <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">无法加载 plan</div>
            <div className="text-sm text-muted-foreground">
              planId={planId.slice(0, 8)}… · code={state.code ?? '?'} · {state.message}
            </div>
            <Button variant="outline" size="sm" onClick={refresh}>
              重试
            </Button>
          </CardContent>
        </Card>
      </main>
    );
  }

  // 直接渲染详情;返回按钮挂在 PlanDetailApp 内部 TopBar(后续如需再加)
  // 左侧"我的任务"沉浸抽屉(hover 滑出 + 触底分页 + 跨任务跳转)
  return (
    <div className="bg-slate-50">
      <TaskDrawer currentPlanId={planId} />
      <PlanDetailApp data={adaptData(state.data, dictionary)} />
    </div>
  );
}
