import { useEffect, useMemo, useState } from 'react';
import { Bot, Check, KeyRound, LoaderCircle, Route } 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 {
  fetchLlmProviderConfigs,
  fetchLlmStageRoutes,
  saveLlmProviderConfigs,
  saveLlmStageRoutes,
} from '@/services/llmConfigService';

type ProviderFormState = {
  provider_key: string;
  base_url: string;
  api_key: string;
  is_active: boolean;
};

type StageRouteFormState = {
  stage: string;
  provider_key: string;
  model: string;
};

const STAGE_OPTIONS = [
  { value: 'document_ocr', label: '文档 OCR', defaultProvider: 'mimo', defaultModel: 'mimo-v2.5' },
  { value: 'document_extraction', label: '文档提取', defaultProvider: 'mimo', defaultModel: 'mimo-v2.5' },
  { value: 'standardization', label: '标准化', defaultProvider: 'deepseek', defaultModel: 'deepseek-v4-pro' },
  { value: 'keyword_semantic', label: '关键词语义', defaultProvider: 'deepseek', defaultModel: 'deepseek-v4-flash' },
  { value: 'search_vision', label: '搜索视觉', defaultProvider: 'gemini', defaultModel: 'gemini-2.5-pro-preview-p' },
  { value: 'fixed_search_batch', label: '固定搜索 Batch', defaultProvider: 'glm', defaultModel: 'glm-4-plus' },
  { value: 'chatbot_intent', label: '客服意图', defaultProvider: 'deepseek', defaultModel: 'deepseek-v4-flash' },
];

const providerDefaults = Object.fromEntries(
  LLM_PROVIDERS.map((provider) => [provider.value, provider]),
);

function createEmptyProviderState(): ProviderFormState[] {
  return LLM_PROVIDERS.map((provider) => ({
    provider_key: provider.value,
    base_url: provider.defaultBaseUrl,
    api_key: '',
    is_active: true,
  }));
}

function createDefaultStageRoutes(): StageRouteFormState[] {
  return STAGE_OPTIONS.map((stage) => ({
    stage: stage.value,
    provider_key: stage.defaultProvider,
    model: stage.defaultModel,
  }));
}

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 [providerConfigs, setProviderConfigs] = useState<ProviderFormState[]>(createEmptyProviderState);
  const [stageRoutes, setStageRoutes] = useState<StageRouteFormState[]>(createDefaultStageRoutes);

  const providerByKey = useMemo(() => new Map(
    providerConfigs.map((provider) => [provider.provider_key, provider]),
  ), [providerConfigs]);

  useEffect(() => {
    if (!open) return;

    setIsLoading(true);
    Promise.all([fetchLlmProviderConfigs(), fetchLlmStageRoutes()])
      .then(([providers, routes]) => {
        const providerRows = createEmptyProviderState().map((provider) => {
          const saved = providers.find((item) => item.provider_key === provider.provider_key);
          return saved
            ? {
                provider_key: saved.provider_key,
                base_url: saved.base_url,
                api_key: saved.api_key,
                is_active: saved.is_active,
              }
            : provider;
        });
        const routeRows = createDefaultStageRoutes().map((stage) => {
          const saved = routes.find((item) => item.stage === stage.stage);
          return saved
            ? {
                stage: saved.stage,
                provider_key: saved.provider_key,
                model: saved.model,
              }
            : stage;
        });
        setProviderConfigs(providerRows);
        setStageRoutes(routeRows);
      })
      .catch(() => {
        toast.error('加载模型配置失败');
      })
      .finally(() => setIsLoading(false));
  }, [open]);

  function updateProvider(providerKey: string, patch: Partial<ProviderFormState>) {
    setProviderConfigs((current) => current.map((provider) => (
      provider.provider_key === providerKey ? { ...provider, ...patch } : provider
    )));
  }

  function updateStageRoute(stage: string, patch: Partial<StageRouteFormState>) {
    setStageRoutes((current) => current.map((route) => (
      route.stage === stage ? { ...route, ...patch } : route
    )));
  }

  function handleStageProviderChange(stage: string, providerKey: string) {
    const provider = providerDefaults[providerKey];
    updateStageRoute(stage, {
      provider_key: providerKey,
      model: provider?.models[0]?.value ?? '',
    });
  }

  async function handleSubmit() {
    const configuredProviders = providerConfigs.filter((provider) => (
      provider.base_url.trim() || provider.api_key.trim()
    ));
    const activeProviderKeys = new Set(
      configuredProviders
        .filter((provider) => provider.is_active && provider.base_url.trim() && provider.api_key.trim())
        .map((provider) => provider.provider_key),
    );
    const routesToSave = stageRoutes.filter((route) => route.provider_key && route.model);
    const invalidRoute = routesToSave.find((route) => !activeProviderKeys.has(route.provider_key));
    if (invalidRoute) {
      const stageLabel = STAGE_OPTIONS.find((stage) => stage.value === invalidRoute.stage)?.label ?? invalidRoute.stage;
      toast.error(`${stageLabel} 的 Provider 尚未配置 Base URL 和 API Key`);
      return;
    }

    setIsSubmitting(true);
    try {
      const operator = user?.displayName ?? user?.username;
      await saveLlmProviderConfigs(configuredProviders.map((provider) => ({
        ...provider,
        configured_by: operator,
      })));
      await saveLlmStageRoutes(routesToSave.map((route) => ({
        ...route,
        updated_by: operator,
      })));
      toast.success('多模型配置已保存并生效');
      onOpenChange(false);
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '保存配置失败');
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[88vh] overflow-y-auto sm:max-w-[760px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Bot className="h-5 w-5 text-blue-600" />
            模型管理
          </DialogTitle>
          <DialogDescription>
            配置多个 Provider 凭证，并为不同自动化阶段选择 Provider 和模型。
          </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-6 py-2">
            <section className="space-y-3">
              <div className="flex items-center gap-2 text-sm font-medium">
                <KeyRound className="h-4 w-4" />
                Provider 凭证
              </div>
              <div className="grid gap-3 md:grid-cols-2">
                {providerConfigs.map((provider) => {
                  const meta = providerDefaults[provider.provider_key];
                  return (
                    <div key={provider.provider_key} className="space-y-3 rounded-md border p-3">
                      <div className="flex items-center justify-between gap-3">
                        <Label className="text-sm">{meta?.label ?? provider.provider_key}</Label>
                        <Button
                          type="button"
                          size="sm"
                          variant={provider.is_active ? 'secondary' : 'outline'}
                          onClick={() => updateProvider(provider.provider_key, { is_active: !provider.is_active })}
                        >
                          {provider.is_active ? '启用' : '停用'}
                        </Button>
                      </div>
                      <Input
                        value={provider.base_url}
                        onChange={(event) => updateProvider(provider.provider_key, { base_url: event.target.value })}
                        placeholder="https://api.example.com/v1"
                      />
                      <Input
                        type="password"
                        value={provider.api_key}
                        onChange={(event) => updateProvider(provider.provider_key, { api_key: event.target.value })}
                        placeholder="API Key"
                        autoComplete="off"
                      />
                    </div>
                  );
                })}
              </div>
            </section>

            <section className="space-y-3">
              <div className="flex items-center gap-2 text-sm font-medium">
                <Route className="h-4 w-4" />
                阶段路由
              </div>
              <div className="space-y-2">
                {stageRoutes.map((route) => {
                  const stage = STAGE_OPTIONS.find((item) => item.value === route.stage);
                  const provider = providerDefaults[route.provider_key];
                  const models = provider?.models ?? [];
                  const providerConfig = providerByKey.get(route.provider_key);
                  return (
                    <div key={route.stage} className="grid gap-2 rounded-md border p-3 md:grid-cols-[150px_1fr_1fr] md:items-center">
                      <Label>{stage?.label ?? route.stage}</Label>
                      <Select value={route.provider_key || 'none'} onValueChange={(value) => {
                        if (value === 'none') {
                          updateStageRoute(route.stage, { provider_key: '', model: '' });
                        } else {
                          handleStageProviderChange(route.stage, value);
                        }
                      }}>
                        <SelectTrigger>
                          <SelectValue placeholder="选择 Provider" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">未配置</SelectItem>
                          {LLM_PROVIDERS.map((item) => (
                            <SelectItem key={item.value} value={item.value}>
                              {item.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <Select
                        value={route.model || 'none'}
                        onValueChange={(value) => updateStageRoute(route.stage, { model: value === 'none' ? '' : value })}
                        disabled={!route.provider_key}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="选择模型" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="none">未配置</SelectItem>
                          {models.map((model) => (
                            <SelectItem key={model.value} value={model.value}>
                              {model.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      {route.provider_key && (!providerConfig?.base_url || !providerConfig?.api_key) && (
                        <p className="text-xs text-amber-600 md:col-start-2 md:col-span-2">
                          该阶段的 Provider 尚未填写完整凭证。
                        </p>
                      )}
                    </div>
                  );
                })}
              </div>
            </section>
          </div>
        )}

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