'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { listApiKeys, revokeApiKey, getApiKeyUsage } from '@/lib/api/admin/api-keys';
import {
  PageContainer,
  PageHeader,
  PageFilter,
  PageTable,
  PageTableEmpty,
  PageTablePagination,
  RefreshButton,
  SearchButton,
} from '@/components/admin/common';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Trash2, Eye } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

export default function AdminApiKeysPage() {
  const [page, setPage] = useState(1);
  const [searchUserId, setSearchUserId] = useState('');
  const [searchProvider, setSearchProvider] = useState('');
  const [selectedKey, setSelectedKey] = useState<string | null>(null);
  const [usageDialogOpen, setUsageDialogOpen] = useState(false);
  const queryClient = useQueryClient();

  const { data, isLoading, refetch } = useQuery({
    queryKey: ['admin', 'api-keys', page, searchUserId, searchProvider],
    queryFn: () => listApiKeys({
      page,
      pageSize: 20,
      userId: searchUserId || undefined,
      provider: searchProvider || undefined,
    }),
  });

  const revokeMutation = useMutation({
    mutationFn: (keyId: string) => revokeApiKey(keyId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'api-keys'] });
    },
  });

  const handleRevoke = (keyId: string) => {
    if (confirm('确定要撤销此 API Key 吗？')) {
      revokeMutation.mutate(keyId);
    }
  };

  const handleViewUsage = async (keyId: string) => {
    setSelectedKey(keyId);
    setUsageDialogOpen(true);
  };

  const { data: usageData } = useQuery({
    queryKey: ['admin', 'api-keys', 'usage', selectedKey],
    queryFn: () => selectedKey ? getApiKeyUsage(selectedKey) : null,
    enabled: !!selectedKey && usageDialogOpen,
  });

  const handleSearch = () => {
    setPage(1);
    queryClient.invalidateQueries({ queryKey: ['admin', 'api-keys'] });
  };

  return (
    <PageContainer>
      <PageHeader
        title="密钥管理"
        description="管理所有用户的供应商密钥"
        actions={<RefreshButton onClick={() => refetch()} loading={isLoading} />}
      />

      <PageFilter variant="ghost">
        <div className="space-y-2">
          <Label htmlFor="search-user">用户 ID</Label>
          <Input
            id="search-user"
            placeholder="搜索用户 ID"
            value={searchUserId}
            onChange={(e) => setSearchUserId(e.target.value)}
            className="w-64"
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="search-provider">提供商</Label>
          <Input
            id="search-provider"
            placeholder="搜索提供商"
            value={searchProvider}
            onChange={(e) => setSearchProvider(e.target.value)}
            className="w-48"
          />
        </div>
        <SearchButton onClick={handleSearch} />
      </PageFilter>

      <PageTable>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>ID</TableHead>
              <TableHead>用户</TableHead>
              <TableHead>提供商</TableHead>
              <TableHead>名称</TableHead>
              <TableHead>Key (脱敏)</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>使用次数</TableHead>
              <TableHead>最后使用</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <PageTableEmpty colSpan={9} message="加载中..." />
            ) : data?.items.length === 0 ? (
              <PageTableEmpty colSpan={9} message="暂无数据" />
            ) : (
              data?.items.map((key) => (
                <TableRow key={key.id}>
                  <TableCell className="font-mono text-xs">{key.id.slice(0, 8)}...</TableCell>
                  <TableCell>
                    <div>
                      <div className="font-medium">{key.username}</div>
                      <div className="text-xs text-muted-foreground">{key.email}</div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">{key.provider}</Badge>
                  </TableCell>
                  <TableCell>{key.name}</TableCell>
                  <TableCell className="font-mono text-xs">{key.maskedKey}</TableCell>
                  <TableCell>
                    <Badge variant={key.isActive ? 'default' : 'secondary'}>
                      {key.isActive ? '活跃' : '已禁用'}
                    </Badge>
                  </TableCell>
                  <TableCell>{key.usageCount}</TableCell>
                  <TableCell>
                    {key.lastUsedAt ? (
                      new Date(key.lastUsedAt * 1000).toLocaleString('zh-CN')
                    ) : (
                      <span className="text-muted-foreground">从未</span>
                    )}
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewUsage(key.id)}
                      >
                        <Eye className="h-4 w-4" />
                      </Button>
                      {key.isActive && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleRevoke(key.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </PageTable>

      {data && (
        <PageTablePagination
          page={data.page}
          totalPages={data.totalPages}
          total={data.total}
          onPageChange={setPage}
        />
      )}

      <Dialog open={usageDialogOpen} onOpenChange={setUsageDialogOpen}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>密钥使用记录</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="text-sm text-muted-foreground">
              总使用次数：{usageData?.usageCount || 0}
            </div>
            <PageTable>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>任务 ID</TableHead>
                    <TableHead>类型</TableHead>
                    <TableHead>模型</TableHead>
                    <TableHead>时间</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {usageData?.records.length === 0 ? (
                    <PageTableEmpty colSpan={4} message="暂无使用记录" />
                  ) : (
                    usageData?.records.map((record, idx) => (
                      <TableRow key={idx}>
                        <TableCell className="font-mono text-xs">
                          {record.taskId?.slice(0, 8) || '-'}
                        </TableCell>
                        <TableCell>{record.taskType || '-'}</TableCell>
                        <TableCell>{record.model || '-'}</TableCell>
                        <TableCell>
                          {record.createdAt ? new Date(record.createdAt).toLocaleString('zh-CN') : '-'}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </PageTable>
          </div>
        </DialogContent>
      </Dialog>
    </PageContainer>
  );
}
