'use client';

import { Permission } from '@pac/types';
import { Can } from '@/components/can';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { useHostAdmin } from '@/components/host-admin/use-host-admin';
import { HostAdminApp } from '@/components/host-admin/host-admin-app';

/**
 * /admin/host — 宿主自己的 admin 配置页(单 host,自动 scope)。
 *
 * 鉴权:
 *   - 走 (app) 布局的 AuthGate(?code= 换 token,localStorage 持久化)
 *   - PLATFORM_MANAGE 权限(仅 admin 角色),其他用户看"无权"
 */
export default function HostAdminPage() {
  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>
      }
    >
      <HostAdminLoader />
    </Can>
  );
}

function HostAdminLoader() {
  const { state, refresh } = useHostAdmin();

  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">
        <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 <HostAdminApp data={state.data} onRefresh={refresh} />;
}
