'use client';

import { useState, useEffect, useMemo } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { useLlmProviders, updateLlmProviders, discoverProviderModels } from '@/hooks/useApi';
import type { LlmProvider, LlmModel } from '@/types';
import { Badge } from '@/components/ui/badge';
import { useLlmConfigStore } from '@/stores/useLlmConfigStore';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Checkbox } from '@/components/ui/checkbox';
import { ScrollArea } from '@/components/ui/scroll-area';

// Main Page Component
export default function LlmConfigPage() {
  const { data: initialProviders, error, isLoading, mutate } = useLlmProviders();
  const { 
    providers, 
    setInitialProviders, 
    openModal, 
    modal,
    deleteProvider,
  } = useLlmConfigStore();
  
  const [isSaving, setIsSaving] = useState(false);
  const [saveMessage, setSaveMessage] = useState('');

  useEffect(() => {
    if (initialProviders) {
      setInitialProviders(initialProviders);
    }
  }, [initialProviders, setInitialProviders]);

  const handleSaveAll = async () => {
    setIsSaving(true);
    setSaveMessage('保存中...');
    try {
      const updated = await updateLlmProviders(providers);
      setInitialProviders(updated);
      await mutate(updated, false); // revalidate SWR
      setSaveMessage('保存成功!');
    } catch (e: any) {
      setSaveMessage(`保存失败: ${e.message}`);
    } finally {
      setIsSaving(false);
      setTimeout(() => setSaveMessage(''), 5000);
    }
  };

  if (isLoading) return <div className="text-center p-8">加载中...</div>;
  if (error) return <div className="text-center p-8 text-red-500">加载配置失败: {error.message}</div>;

  return (
    <div className="container mx-auto py-6 space-y-6">
      <header className="space-y-2">
        <h1 className="text-3xl font-bold">LLM Provider 配置</h1>
        <p className="text-muted-foreground">
          在这里管理所有可用的大语言模型（LLM）供应商及其模型。
        </p>
      </header>

      <div className="flex justify-end">
        <Button onClick={() => openModal({ type: 'addProvider' })}>新增 Provider</Button>
      </div>

      <div className="space-y-8">
        {Object.entries(providers).map(([providerId, provider]) => (
          <Card key={providerId}>
            <CardHeader>
              <div className="flex justify-between items-start">
                <div>
                  <CardTitle>{provider.name}</CardTitle>
                  <CardDescription>ID: {providerId}</CardDescription>
                </div>
                <div className="flex gap-2">
                  <Button variant="outline" size="sm" onClick={() => openModal({ type: 'editProvider', providerId })}>编辑</Button>
                  <Button variant="destructive" size="sm" onClick={() => deleteProvider(providerId)}>删除</Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <p className="text-sm text-muted-foreground mb-4">
                API Base URL: <code className="font-mono">{provider.api_base_url}</code>
              </p>
              <div className="border rounded-lg p-4">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="text-lg font-semibold">模型管理</h3>
                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" onClick={() => openModal({ type: 'addModel', providerId })}>新增模型</Button>
                    <Button variant="outline" onClick={() => openModal({ type: 'discoverModels', providerId })}>发现模型</Button>
                  </div>
                </div>
                
                <div className="space-y-2">
                  {provider.models.map((model, index) => (
                    <div key={index} className="flex items-center justify-between p-2 border-b last:border-b-0">
                      <div>
                        <p className="font-medium">{model.model_id}</p>
                        {model.name && <p className="text-sm text-muted-foreground">{model.name}</p>}
                      </div>
                      <div className="flex items-center gap-4">
                         <Badge variant={model.is_active ? 'default' : 'secondary'}>
                           {model.is_active ? '已激活' : '未激活'}
                         </Badge>
                         <Button variant="ghost" size="sm" onClick={() => openModal({ type: 'editModel', providerId, modelIndex: index })}>编辑</Button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

       <div className="flex items-center justify-between pt-6 border-t">
        <div className="text-sm text-muted-foreground">
            {saveMessage}
        </div>
        <div className="flex items-center gap-4">
          <Button size="lg" onClick={handleSaveAll} disabled={isSaving}>
            {isSaving ? '保存中...' : '保存所有更改'}
          </Button>
        </div>
      </div>

      {modal.type !== 'closed' && <ConfigModal />}
    </div>
  );
}

// --- Modal Components ---

function ConfigModal() {
    const { modal } = useLlmConfigStore();

    if (modal.type === 'addProvider' || modal.type === 'editProvider') {
        return <ProviderEditModal />;
    }
    if (modal.type === 'addModel' || modal.type === 'editModel') {
        return <ModelEditModal />;
    }
    if (modal.type === 'discoverModels') {
        return <DiscoverModelsModal />;
    }
    return null;
}

type ProviderFormData = {
    id?: string;
    name?: string;
    api_base_url?: string;
    api_key?: string;
};

function ProviderEditModal() {
    const { modal, closeModal, providers, addProvider, updateProvider } = useLlmConfigStore();
    const [formData, setFormData] = useState<ProviderFormData>({});
    
    const isAdd = modal.type === 'addProvider';

    useEffect(() => {
        if (modal.type === 'editProvider') {
            const provider = providers[modal.providerId];
            setFormData({ ...provider, id: modal.providerId });
        } else {
            setFormData({});
        }
    }, [modal, providers]);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData((prev) => ({ ...prev, [name]: value }));
    };

    const handleSubmit = () => {
        if (isAdd) {
            const { id, ...providerData } = formData;
            const providerId = (id || '').trim();
            if (!providerId) return;
            const providerObj: LlmProvider = {
                name: providerData.name || '',
                api_base_url: providerData.api_base_url || '',
                api_key: providerData.api_key || '',
                models: [],
            };
            addProvider(providerId, providerObj);
        } else if (modal.type === 'editProvider') {
            const { id, ...providerData } = formData;
            const providerId = (id || '').trim();
            if (!providerId) return;
            const existing = providers[providerId] as LlmProvider | undefined;
            const providerObj: LlmProvider = {
                name: providerData.name ?? existing?.name ?? '',
                api_base_url: providerData.api_base_url ?? existing?.api_base_url ?? '',
                api_key: providerData.api_key ?? existing?.api_key ?? '',
                models: existing?.models ?? [],
            };
            updateProvider(providerId, providerObj);
        }
        closeModal();
    };

    return (
        <Dialog open onOpenChange={closeModal}>
            <DialogContent>
                <DialogHeader><DialogTitle>{isAdd ? '新增 Provider' : '编辑 Provider'}</DialogTitle></DialogHeader>
                <div className="space-y-4 py-4">
                   {isAdd && <div className="space-y-2">
                        <Label htmlFor="id">Provider ID</Label>
                        <Input id="id" name="id" value={formData.id || ''} onChange={handleChange} placeholder="e.g., openai_official"/>
                    </div>}
                    <div className="space-y-2">
                        <Label htmlFor="name">名称</Label>
                        <Input id="name" name="name" value={formData.name || ''} onChange={handleChange} placeholder="e.g., OpenAI 官方"/>
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="api_base_url">API Base URL</Label>
                        <Input id="api_base_url" name="api_base_url" value={formData.api_base_url || ''} onChange={handleChange} placeholder="https://api.openai.com/v1"/>
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="api_key">API Key</Label>
                        <Input id="api_key" name="api_key" type="password" value={formData.api_key || ''} onChange={handleChange} />
                    </div>
                </div>
                <DialogFooter>
                    <Button variant="outline" onClick={closeModal}>取消</Button>
                    <Button onClick={handleSubmit}>保存</Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}

type ModelFormData = {
    model_id?: string;
    name?: string | null;
    is_active: boolean;
};

function ModelEditModal() {
    const { modal, closeModal, providers, addModel, updateModel } = useLlmConfigStore();
    const [formData, setFormData] = useState<ModelFormData>({ is_active: true });

    const isAdd = modal.type === 'addModel';

     useEffect(() => {
        if (modal.type === 'editModel') {
            const model = providers[modal.providerId].models[modal.modelIndex];
            setFormData(model);
        } else {
            setFormData({ is_active: true });
        }
    }, [modal, providers]);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData((prev) => ({ ...prev, [name]: value }));
    };

    const handleSubmit = () => {
        if (isAdd && modal.type === 'addModel') {
            if (!formData.model_id) return;
            const modelObj: LlmModel = {
                model_id: formData.model_id,
                name: formData.name ?? null,
                is_active: !!formData.is_active,
            };
            addModel(modal.providerId, modelObj);
        } else if (modal.type === 'editModel') {
            if (!formData.model_id) return;
            const modelObj: LlmModel = {
                model_id: formData.model_id,
                name: formData.name ?? null,
                is_active: !!formData.is_active,
            };
            updateModel(modal.providerId, modal.modelIndex, modelObj);
        }
        closeModal();
    };

    return (
        <Dialog open onOpenChange={closeModal}>
            <DialogContent>
                <DialogHeader><DialogTitle>{isAdd ? '新增 Model' : '编辑 Model'}</DialogTitle></DialogHeader>
                <div className="space-y-4 py-4">
                    <div className="space-y-2">
                        <Label htmlFor="model_id">Model ID</Label>
                        <Input id="model_id" name="model_id" value={formData.model_id || ''} onChange={handleChange} placeholder="e.g., gpt-4o"/>
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="name">别名 (可选)</Label>
                        <Input id="name" name="name" value={formData.name || ''} onChange={handleChange} placeholder="e.g., GPT-4o"/>
                    </div>
                     <div className="flex items-center space-x-2">
                        <Switch id="is_active" name="is_active" checked={!!formData.is_active} onCheckedChange={(checked) => setFormData((prev) => ({ ...prev, is_active: checked }))}/>
                        <Label htmlFor="is_active">在UI中激活</Label>
                    </div>
                </div>
                <DialogFooter>
                    <Button variant="outline" onClick={closeModal}>取消</Button>
                    <Button onClick={handleSubmit}>保存</Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}

type DiscoveredModel = { id: string; name?: string };

function DiscoverModelsModal() {
    const { modal, closeModal, providers, addModel } = useLlmConfigStore();
    const [discoveredModels, setDiscoveredModels] = useState<DiscoveredModel[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [selectedModels, setSelectedModels] = useState<Record<string, boolean>>({});
    
    const providerId = modal.type === 'discoverModels' ? modal.providerId : '';
    const existingModelIds = useMemo(() => {
        if (!providerId) return new Set();
        return new Set(providers[providerId].models.map(m => m.model_id));
    }, [providerId, providers]);

    useEffect(() => {
        if (!providerId) return;
        
        const fetchModels = async () => {
            setIsLoading(true);
            setError(null);
            try {
                const result = await discoverProviderModels(providerId);
                if (result.error) {
                    throw new Error(result.provider_error || result.error);
                }
                // OpenAI format is { data: [...] }, others might be [...]
                const models = (result.data || result) as DiscoveredModel[] | unknown;
                if (Array.isArray(models)) {
                    setDiscoveredModels(models as DiscoveredModel[]);
                } else {
                    throw new Error("Invalid response format from provider");
                }
            } catch (e: any) {
                setError(e.message);
            } finally {
                setIsLoading(false);
            }
        };
        fetchModels();
    }, [providerId]);

    const handleToggleModel = (modelId: string, checked: boolean) => {
        setSelectedModels(prev => ({ ...prev, [modelId]: checked }));
    };
    
    const handleImport = () => {
        if (!providerId) return;
        Object.entries(selectedModels).forEach(([modelId, isSelected]) => {
            if (isSelected && !existingModelIds.has(modelId)) {
                addModel(providerId, { model_id: modelId, name: null, is_active: true });
            }
        });
        closeModal();
    };

    return (
        <Dialog open onOpenChange={closeModal}>
            <DialogContent className="max-w-2xl">
                <DialogHeader><DialogTitle>从 {providerId} 发现并导入模型</DialogTitle></DialogHeader>
                <div className="py-4">
                    {isLoading && <p>正在从供应商API加载模型列表...</p>}
                    {error && <p className="text-red-500">加载失败: {error}</p>}
                    {!isLoading && !error && (
                        <ScrollArea className="h-72">
                            <div className="space-y-2 pr-4">
                                {discoveredModels.map(model => (
                                    <div key={model.id} className="flex items-center space-x-2">
                                        <Checkbox 
                                            id={model.id}
                                            onCheckedChange={(checked) => handleToggleModel(model.id, !!checked)}
                                            disabled={existingModelIds.has(model.id)}
                                        />
                                        <label
                                            htmlFor={model.id}
                                            className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                                        >
                                            {model.id} {existingModelIds.has(model.id) && "(已存在)"}
                                        </label>
                                    </div>
                                ))}
                            </div>
                        </ScrollArea>
                    )}
                </div>
                <DialogFooter>
                    <Button variant="outline" onClick={closeModal}>取消</Button>
                    <Button onClick={handleImport}>导入选中模型</Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
