'use client';

import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { listAuditLogs, exportAuditLogs, getAuditLog } from '@/lib/api/admin/audit-logs';
import {
  PageContainer,
  PageHeader,
  PageFilter,
  PageTable,
  PageTableEmpty,
  PageTablePagination,
  ExportButton,
  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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Eye, FileText } from 'lucide-react';

export default function AdminAuditLogsPage() {
  const [page, setPage] = useState(1);
  const [filters, setFilters] = useState({
    userId: '',
    action: '',
    resourceType: '',
    resourceId: '',
    startDate: '',
    endDate: '',
  });
  const [selectedLog, setSelectedLog] = useState<string | null>(null);
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ['admin', 'audit-logs', page, filters],
    queryFn: () => listAuditLogs({
      page,
      pageSize: 20,
      ...filters,
    }),
  });

  const handleExport = async () => {
    try {
      const result = await exportAuditLogs(filters);
      const blob = new Blob([result.content], { type: 'text/csv' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = result.filename;
      a.click();
      URL.revokeObjectURL(url);
    } catch (error) {
      console.error('导出失败:', error);
    }
  };

  const handleViewDetail = (logId: string) => {
    setSelectedLog(logId);
    setDetailDialogOpen(true);
  };

  const { data: logDetail } = useQuery({
    queryKey: ['admin', 'audit-logs', 'detail', selectedLog],
    queryFn: () => selectedLog ? getAuditLog(selectedLog) : null,
    enabled: !!selectedLog && detailDialogOpen,
  });

  const handleFilterChange = (key: string, value: string) => {
    setFilters(prev => ({
      ...prev,
      [key]: key === 'resourceType' && value === 'all' ? '' : value
    }));
  };

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

  const resourceTypeOptions = [
    { value: 'user', label: '用户' },
    { value: 'project', label: '项目' },
    { value: 'task', label: '任务' },
    { value: 'api_key', label: '密钥' },
    { value: 'model', label: '模型' },
    { value: 'provider', label: 'Provider' },
  ];

  return (
    <PageContainer>
      <PageHeader
        title="审计日志"
        description="查看系统操作审计日志"
        actions={<ExportButton onClick={handleExport} />}
      />

      <PageFilter className="grid-cols-3">
        <div className="space-y-2">
          <Label htmlFor="filter-user">用户 ID</Label>
          <Input
            id="filter-user"
            placeholder="用户 ID"
            value={filters.userId}
            onChange={(e) => handleFilterChange('userId', e.target.value)}
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="filter-action">操作类型</Label>
          <Input
            id="filter-action"
            placeholder="如 create, delete"
            value={filters.action}
            onChange={(e) => handleFilterChange('action', e.target.value)}
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="filter-resource">资源类型</Label>
          <Select
            value={filters.resourceType}
            onValueChange={(value) => handleFilterChange('resourceType', value)}
          >
            <SelectTrigger>
              <SelectValue placeholder="全部" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部</SelectItem>
              {resourceTypeOptions.map((opt) => (
                <SelectItem key={opt.value} value={opt.value}>
                  {opt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="space-y-2">
          <Label htmlFor="filter-resource-id">资源 ID</Label>
          <Input
            id="filter-resource-id"
            placeholder="资源 ID"
            value={filters.resourceId}
            onChange={(e) => handleFilterChange('resourceId', e.target.value)}
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="filter-start">开始日期</Label>
          <Input
            id="filter-start"
            type="date"
            value={filters.startDate}
            onChange={(e) => handleFilterChange('startDate', e.target.value)}
          />
        </div>
        <div className="space-y-2">
          <Label htmlFor="filter-end">结束日期</Label>
          <Input
            id="filter-end"
            type="date"
            value={filters.endDate}
            onChange={(e) => handleFilterChange('endDate', e.target.value)}
          />
        </div>
        <div className="col-span-3 flex justify-end">
          <SearchButton onClick={handleSearch} />
        </div>
      </PageFilter>

      <PageTable>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>ID</TableHead>
              <TableHead>用户</TableHead>
              <TableHead>操作</TableHead>
              <TableHead>资源类型</TableHead>
              <TableHead>资源 ID</TableHead>
              <TableHead>IP 地址</TableHead>
              <TableHead>时间</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <PageTableEmpty colSpan={8} message="加载中..." />
            ) : data?.items.length === 0 ? (
              <PageTableEmpty colSpan={8} message="暂无数据" />
            ) : (
              data?.items.map((log) => (
                <TableRow key={log.id}>
                  <TableCell className="font-mono text-xs">
                    {log.id.slice(0, 8)}...
                  </TableCell>
                  <TableCell>
                    {log.username || log.userId || '-'}
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline" className="font-mono">
                      {log.action}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {log.resourceType ? (
                      <Badge variant="secondary">{log.resourceType}</Badge>
                    ) : (
                      '-'
                    )}
                  </TableCell>
                  <TableCell className="font-mono text-xs">
                    {log.resourceId?.slice(0, 8) || '-'}
                  </TableCell>
                  <TableCell className="font-mono text-xs">
                    {log.ipAddress || '-'}
                  </TableCell>
                  <TableCell>
                    {new Date(log.createdAt).toLocaleString('zh-CN')}
                  </TableCell>
                  <TableCell>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleViewDetail(log.id)}
                    >
                      <Eye className="h-4 w-4" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </PageTable>

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

      <Dialog open={detailDialogOpen} onOpenChange={setDetailDialogOpen}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5" />
              审计日志详情
            </DialogTitle>
          </DialogHeader>
          {logDetail && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <Label className="text-muted-foreground">日志 ID</Label>
                  <div className="font-mono">{logDetail.id}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">用户</Label>
                  <div>{logDetail.username || logDetail.userId || '-'}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">操作</Label>
                  <div className="font-mono">{logDetail.action}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">资源类型</Label>
                  <div>{logDetail.resourceType || '-'}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">资源 ID</Label>
                  <div className="font-mono">{logDetail.resourceId || '-'}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">IP 地址</Label>
                  <div className="font-mono">{logDetail.ipAddress || '-'}</div>
                </div>
                <div className="col-span-2">
                  <Label className="text-muted-foreground">User Agent</Label>
                  <div className="text-xs">{logDetail.userAgent || '-'}</div>
                </div>
                <div>
                  <Label className="text-muted-foreground">时间</Label>
                  <div>{new Date(logDetail.createdAt).toLocaleString('zh-CN')}</div>
                </div>
              </div>
              {logDetail.details && (
                <div className="space-y-2">
                  <Label className="text-muted-foreground">详细信息</Label>
                  <pre className="bg-muted p-4 rounded-md text-xs overflow-auto max-h-64">
                    {JSON.stringify(logDetail.details, null, 2)}
                  </pre>
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>
    </PageContainer>
  );
}
