'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getStorageStats, listStorageFiles, getStorageUserRanking, cleanupOrphanFiles } from '@/lib/api/admin/storage';
import {
  PageContainer,
  PageHeader,
  PageStats,
  PageStatCard,
  PageCard,
  PageFilter,
  PageTable,
  PageTableEmpty,
  PageTablePagination,
  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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { HardDrive, FileBox, Users, Trash2 } from 'lucide-react';

export default function AdminStoragePage() {
  const [page, setPage] = useState(1);
  const [activeTab, setActiveTab] = useState<'overview' | 'ranking' | 'files'>('overview');
  const [searchUserId, setSearchUserId] = useState('');
  const [searchProjectId, setSearchProjectId] = useState('');
  const queryClient = useQueryClient();

  const { data: stats, isLoading: statsLoading } = useQuery({
    queryKey: ['admin', 'storage', 'stats'],
    queryFn: getStorageStats,
  });

  const { data: fileList, isLoading: filesLoading } = useQuery({
    queryKey: ['admin', 'storage', 'files', page, searchUserId, searchProjectId],
    queryFn: () => listStorageFiles({
      page,
      pageSize: 20,
      userId: searchUserId || undefined,
      projectId: searchProjectId || undefined,
    }),
    enabled: activeTab === 'files',
  });

  const { data: ranking, isLoading: rankingLoading } = useQuery({
    queryKey: ['admin', 'storage', 'ranking'],
    queryFn: () => getStorageUserRanking({ page: 1, pageSize: 10 }),
    enabled: activeTab === 'ranking',
  });

  const cleanupMutation = useMutation({
    mutationFn: (dryRun: boolean) => cleanupOrphanFiles({ dryRun }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'storage'] });
    },
  });

  const handleCleanup = () => {
    if (confirm('确定要清理孤立文件吗？此操作不可恢复。')) {
      cleanupMutation.mutate(false);
    }
  };

  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
  };

  return (
    <PageContainer>
      <PageHeader
        title="存储管理"
        description="管理系统存储资源和文件"
      />

      <PageStats columns={4}>
        <PageStatCard
          title="总容量"
          value={formatBytes(stats?.totalCapacity || 0)}
          icon={<HardDrive className="h-4 w-4" />}
          loading={statsLoading}
        />
        <PageStatCard
          title="已用空间"
          value={formatBytes(stats?.usedSpace || 0)}
          icon={<HardDrive className="h-4 w-4" />}
          description={`${stats?.usagePercent?.toFixed(1) || 0}% 使用率`}
          loading={statsLoading}
        />
        <PageStatCard
          title="文件数量"
          value={stats?.fileCount || 0}
          icon={<FileBox className="h-4 w-4" />}
          loading={statsLoading}
        />
        <PageStatCard
          title="用户排行"
          value={`${ranking?.items.length || 0} 用户`}
          icon={<Users className="h-4 w-4" />}
          loading={rankingLoading}
        />
      </PageStats>

      <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as any)}>
        <TabsList>
          <TabsTrigger value="overview">概览</TabsTrigger>
          <TabsTrigger value="ranking">用户排行</TabsTrigger>
          <TabsTrigger value="files">文件列表</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-4">
          <PageCard title="存储使用趋势">
            <div className="h-64 flex items-center justify-center bg-muted/50 rounded-md">
              <p className="text-muted-foreground">图表功能待实现</p>
            </div>
          </PageCard>
        </TabsContent>

        <TabsContent value="ranking" className="space-y-4">
          <PageTable>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>排名</TableHead>
                  <TableHead>用户</TableHead>
                  <TableHead>存储空间</TableHead>
                  <TableHead>文件数量</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {rankingLoading ? (
                  <PageTableEmpty colSpan={4} message="加载中..." />
                ) : ranking?.items.length === 0 ? (
                  <PageTableEmpty colSpan={4} message="暂无数据" />
                ) : (
                  ranking?.items.map((user: { userId: string; rank: number; username: string; storageUsed: number; fileCount: number }) => (
                    <TableRow key={user.userId}>
                      <TableCell>
                        <Badge variant={user.rank <= 3 ? 'default' : 'secondary'}>
                          #{user.rank}
                        </Badge>
                      </TableCell>
                      <TableCell className="font-medium">{user.username}</TableCell>
                      <TableCell>{formatBytes(user.storageUsed)}</TableCell>
                      <TableCell>{user.fileCount}</TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </PageTable>
        </TabsContent>

        <TabsContent value="files" className="space-y-4">
          <PageFilter variant="ghost">
            <div className="space-y-2">
              <Label htmlFor="search-user-file">用户 ID</Label>
              <Input
                id="search-user-file"
                placeholder="搜索用户 ID"
                value={searchUserId}
                onChange={(e) => setSearchUserId(e.target.value)}
                className="w-64"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="search-project-file">项目 ID</Label>
              <Input
                id="search-project-file"
                placeholder="搜索项目 ID"
                value={searchProjectId}
                onChange={(e) => setSearchProjectId(e.target.value)}
                className="w-64"
              />
            </div>
            <SearchButton onClick={() => setPage(1)} />
          </PageFilter>

          <PageTable>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>路径</TableHead>
                  <TableHead>大小</TableHead>
                  <TableHead>用户</TableHead>
                  <TableHead>项目</TableHead>
                  <TableHead>创建时间</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filesLoading ? (
                  <PageTableEmpty colSpan={6} message="加载中..." />
                ) : fileList?.items.length === 0 ? (
                  <PageTableEmpty colSpan={6} message="暂无数据" />
                ) : (
                  fileList?.items.map((file: { id: string; path: string; size: number; username?: string; userId: string; projectName?: string; projectId?: string; createdAt: number }) => (
                    <TableRow key={file.id}>
                      <TableCell className="font-mono text-xs">
                        {file.id.slice(0, 8)}...
                      </TableCell>
                      <TableCell className="max-w-xs truncate font-mono text-xs">
                        {file.path}
                      </TableCell>
                      <TableCell>{formatBytes(file.size)}</TableCell>
                      <TableCell>{file.username || file.userId}</TableCell>
                      <TableCell>{file.projectName || file.projectId || '-'}</TableCell>
                      <TableCell>
                        {new Date(file.createdAt * 1000).toLocaleString('zh-CN')}
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </PageTable>

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

      <PageCard
        title="孤立文件清理"
        icon={<Trash2 className="h-5 w-5" />}
        description="清理没有关联项目的孤立文件，释放存储空间。"
      >
        <Button
          onClick={handleCleanup}
          disabled={cleanupMutation.isPending}
          className="gap-2"
        >
          <Trash2 className="h-4 w-4" />
          {cleanupMutation.isPending ? '清理中...' : '清理孤立文件'}
        </Button>
      </PageCard>
    </PageContainer>
  );
}
