'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { listModels, toggleModel, setDefaultModel, testModel, listProviders, toggleProvider, deleteProvider } from '@/lib/api/admin/models';
import {
  PageContainer,
  PageHeader,
  PageFilter,
  PageTable,
  PageTableEmpty,
} from '@/components/admin/common';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Zap,
  Star,
  Trash2,
  RefreshCw,
  Activity,
} from 'lucide-react';

export default function AdminModelsPage() {
  const [activeTab, setActiveTab] = useState<'models' | 'providers'>('models');
  const [selectedModelType, setSelectedModelType] = useState<string>('all');
  const [testDialogOpen, setTestDialogOpen] = useState(false);
  const [selectedModelId, setSelectedModelId] = useState<string | null>(null);
  const queryClient = useQueryClient();

  // Models
  const { data: modelsData, isLoading: modelsLoading } = useQuery({
    queryKey: ['admin', 'models'],
    queryFn: listModels,
  });

  // Providers
  const { data: providersData } = useQuery({
    queryKey: ['admin', 'providers'],
    queryFn: listProviders,
  });

  // Toggle model mutation
  const toggleModelMutation = useMutation({
    mutationFn: ({ modelId, enabled }: { modelId: string; enabled: boolean }) =>
      toggleModel(modelId, enabled),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'models'] });
    },
  });

  // Set default model mutation
  const setDefaultModelMutation = useMutation({
    mutationFn: (modelId: string) => setDefaultModel(modelId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'models'] });
    },
  });

  // Test model mutation
  const testModelMutation = useMutation({
    mutationFn: (modelId: string) => testModel(modelId),
    onSuccess: () => {
      setTestDialogOpen(false);
    },
  });

  // Toggle provider mutation
  const toggleProviderMutation = useMutation({
    mutationFn: ({ providerId, enabled }: { providerId: string; enabled: boolean }) =>
      toggleProvider(providerId, enabled),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'providers'] });
    },
  });

  // Delete provider mutation
  const deleteProviderMutation = useMutation({
    mutationFn: (providerId: string) => deleteProvider(providerId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'providers'] });
    },
  });

  const handleTestModel = (modelId: string) => {
    setSelectedModelId(modelId);
    setTestDialogOpen(true);
  };

  const runTest = () => {
    if (selectedModelId) {
      testModelMutation.mutate(selectedModelId);
    }
  };

  // Flatten models for display
  const allModels = Object.entries(modelsData || {}).flatMap(([type, models]: [string, any]) =>
    Object.values(models).map((m: any) => ({ ...m, modelType: type }))
  );

  const filteredModels = selectedModelType === 'all'
    ? allModels
    : allModels.filter((m: any) => m.modelType === selectedModelType);

  const modelTypeOptions = [
    { value: 'all', label: '全部类型' },
    { value: 'image', label: '图片生成' },
    { value: 'video', label: '视频生成' },
    { value: 'audio', label: '音频生成' },
    { value: 'lyrics', label: '歌词生成' },
    { value: 'music', label: '音乐生成' },
    { value: 'llm', label: 'LLM' },
  ];

  const formatModelId = (id: string) => {
    const parts = id.split('/');
    return parts.length > 1 ? parts[1] : id;
  };

  return (
    <PageContainer>
      <PageHeader
        title="模型配置"
        description="管理 AI 模型和 Provider 配置"
      />

      <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as any)}>
        <TabsList>
          <TabsTrigger value="models">模型管理</TabsTrigger>
          <TabsTrigger value="providers">Provider 管理</TabsTrigger>
        </TabsList>

        {/* Models Tab */}
        <TabsContent value="models" className="space-y-4">
          <PageFilter variant="ghost">
            <div className="space-y-2">
              <Label>模型类型</Label>
              <Select value={selectedModelType} onValueChange={setSelectedModelType}>
                <SelectTrigger className="w-48">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {modelTypeOptions.map((opt) => (
                    <SelectItem key={opt.value} value={opt.value}>
                      {opt.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </PageFilter>

          <PageTable>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>名称</TableHead>
                  <TableHead>提供商</TableHead>
                  <TableHead>类型</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>默认</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {modelsLoading ? (
                  <PageTableEmpty colSpan={7} message="加载中..." />
                ) : filteredModels.length === 0 ? (
                  <PageTableEmpty colSpan={7} message="暂无数据" />
                ) : (
                  filteredModels.map((model: any) => (
                    <TableRow key={model.id}>
                      <TableCell className="font-mono text-xs max-w-xs truncate">
                        {formatModelId(model.id)}
                      </TableCell>
                      <TableCell className="font-medium">{model.name}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{model.provider}</Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant="secondary">{model.modelType}</Badge>
                      </TableCell>
                      <TableCell>
                        <Switch
                          checked={model.enabled !== false}
                          onCheckedChange={(checked) =>
                            toggleModelMutation.mutate({
                              modelId: model.id,
                              enabled: checked,
                            })
                          }
                        />
                      </TableCell>
                      <TableCell>
                        {model.isDefault && (
                          <Star className="h-4 w-4 text-yellow-500 fill-yellow-500" />
                        )}
                      </TableCell>
                      <TableCell>
                        <div className="flex gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleTestModel(model.id)}
                          >
                            <Activity className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() =>
                              setDefaultModelMutation.mutate(model.id)
                            }
                          >
                            <Star className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </PageTable>
        </TabsContent>

        {/* Providers Tab */}
        <TabsContent value="providers" className="space-y-4">
          <PageTable>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>名称</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>模型数量</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {providersData?.providers.map((provider: any) => (
                  <TableRow key={provider.id}>
                    <TableCell className="font-medium">{provider.id}</TableCell>
                    <TableCell>{provider.name || provider.id}</TableCell>
                    <TableCell>
                      <Switch
                        checked={provider.enabled !== false}
                        onCheckedChange={(checked) =>
                          toggleProviderMutation.mutate({
                            providerId: provider.id,
                            enabled: checked,
                          })
                        }
                      />
                    </TableCell>
                    <TableCell>{provider.models?.length || 0}</TableCell>
                    <TableCell>
                      <div className="flex gap-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() =>
                            deleteProviderMutation.mutate(provider.id)
                          }
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </PageTable>
        </TabsContent>
      </Tabs>

      {/* Test Dialog */}
      <Dialog open={testDialogOpen} onOpenChange={setTestDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Activity className="h-5 w-5" />
              测试模型连接
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="text-sm">
              <Label>模型 ID:</Label>
              <div className="font-mono text-xs mt-1">{selectedModelId}</div>
            </div>
            {testModelMutation.data && (
              <div className="space-y-2">
                <div className="flex items-center gap-2">
                  {testModelMutation.data.success ? (
                    <Zap className="h-5 w-5 text-green-500" />
                  ) : (
                    <Zap className="h-5 w-5 text-red-500" />
                  )}
                  <span className="font-medium">
                    {testModelMutation.data.success ? '测试成功' : '测试失败'}
                  </span>
                </div>
                <div className="text-sm">
                  <Label>状态:</Label>
                  <div>{testModelMutation.data.status}</div>
                </div>
                {testModelMutation.data.latencyMs && (
                  <div className="text-sm">
                    <Label>延迟:</Label>
                    <div>{testModelMutation.data.latencyMs.toFixed(2)} ms</div>
                  </div>
                )}
                {(testModelMutation.data as any).error && (
                  <div className="text-sm">
                    <Label>错误:</Label>
                    <div className="text-red-500">{(testModelMutation.data as any).error}</div>
                  </div>
                )}
              </div>
            )}
            <Button
              onClick={runTest}
              disabled={testModelMutation.isPending}
              className="w-full gap-2"
            >
              <RefreshCw className={`h-4 w-4 ${testModelMutation.isPending ? 'animate-spin' : ''}`} />
              {testModelMutation.isPending ? '测试中...' : '运行测试'}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </PageContainer>
  );
}
