import { useEffect, useState } from 'react';
import { Bot, Check, LoaderCircle } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useAuth } from '@/hooks/useAuth';
import { LLM_PROVIDERS } from '@/lib/llmModels';
import { fetchActiveLlmConfig, saveLlmConfig } from '@/services/llmConfigService';

export function ModelConfigDialog({
  open,
  onOpenChange,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const { user } = useAuth();
  const [isLoading, setIsLoading] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const [provider, setProvider] = useState('');
  const [model, setModel] = useState('');
  const [baseUrl, setBaseUrl] = useState('');
  const [apiKey, setApiKey] = useState('');

  // 当前品牌下可选的模型列表
  const selectedProvider = LLM_PROVIDERS.find(p => p.value === provider);
  const availableModels = selectedProvider?.models ?? [];

  // 打开时加载当前活跃配置
  useEffect(() => {
    if (!open) return;

    setIsLoading(true);
    fetchActiveLlmConfig()
      .then(config => {
        if (config) {
          setProvider(config.provider);
          setModel(config.model);
          setBaseUrl(config.base_url);
          setApiKey(config.api_key);
        } else {
          setProvider('');
          setModel('');
          setBaseUrl('');
          setApiKey('');
        }
      })
      .catch(() => {
        toast.error('加载当前 LLM 配置失败');
      })
      .finally(() => setIsLoading(false));
  }, [open]);

  // 切换品牌时重置模型并填充默认 base_url
  function handleProviderChange(value: string) {
    setProvider(value);
    setModel('');
    const p = LLM_PROVIDERS.find(item => item.value === value);
    if (p) {
      setBaseUrl(p.defaultBaseUrl);
    }
  }

  async function handleSubmit() {
    if (!provider || !model || !baseUrl || !apiKey) {
      toast.error('请填写所有必填字段');
      return;
    }

    setIsSubmitting(true);
    try {
      await saveLlmConfig({
        provider,
        model,
        api_key: apiKey,
        base_url: baseUrl,
        configured_by: user?.displayName ?? user?.username,
      });
      toast.success('模型配置已保存并生效');
      onOpenChange(false);
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '保存配置失败');
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[480px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Bot className="h-5 w-5 text-blue-600" />
            模型管理
          </DialogTitle>
          <DialogDescription>
            选择 LLM 品牌和模型版本，配置 API 密钥后点击确认生效。
          </DialogDescription>
        </DialogHeader>

        {isLoading ? (
          <div className="flex items-center justify-center py-8">
            <LoaderCircle className="h-6 w-6 animate-spin text-muted-foreground" />
          </div>
        ) : (
          <div className="space-y-4 py-2">
            {/* 品牌选择 */}
            <div className="space-y-2">
              <Label>模型品牌</Label>
              <Select value={provider} onValueChange={handleProviderChange}>
                <SelectTrigger>
                  <SelectValue placeholder="选择模型品牌" />
                </SelectTrigger>
                <SelectContent>
                  {LLM_PROVIDERS.map(p => (
                    <SelectItem key={p.value} value={p.value}>
                      {p.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 模型版本选择 */}
            <div className="space-y-2">
              <Label>模型版本</Label>
              <Select
                value={model}
                onValueChange={setModel}
                disabled={!provider}
              >
                <SelectTrigger>
                  <SelectValue placeholder={provider ? '选择模型版本' : '请先选择品牌'} />
                </SelectTrigger>
                <SelectContent>
                  {availableModels.map(m => (
                    <SelectItem key={m.value} value={m.value}>
                      {m.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Base URL */}
            <div className="space-y-2">
              <Label>API Base URL</Label>
              <Input
                value={baseUrl}
                onChange={e => setBaseUrl(e.target.value)}
                placeholder="https://api.example.com/v1"
              />
              {provider === 'anthropic' && !baseUrl && (
                <p className="text-xs text-amber-600">
                  Claude 需要提供 OpenAI 兼容的代理地址（如 OpenRouter）
                </p>
              )}
            </div>

            {/* API Key */}
            <div className="space-y-2">
              <Label>API Key</Label>
              <Input
                type="password"
                value={apiKey}
                onChange={e => setApiKey(e.target.value)}
                placeholder="输入 API 密钥"
                autoComplete="off"
              />
            </div>
          </div>
        )}

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={isSubmitting || isLoading || !provider || !model || !baseUrl || !apiKey}
          >
            {isSubmitting ? (
              <LoaderCircle className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <Check className="mr-2 h-4 w-4" />
            )}
            确认生效
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
