import { useState, useEffect, useRef, useCallback } from 'react';
import {
  useLlmProviders,
  updateLlmProviders,
  discoverProviderModels
} from '@/hooks/useApi';
import { LlmProvidersConfig, LlmModel } from '@/types';

export function useAiConfig() {
  const { data: llmProviders, mutate: mutateLlmProviders } = useLlmProviders();
  const [localLlmProviders, setLocalLlmProviders] = useState<LlmProvidersConfig>({});
  
  const [isSavingLlm, setIsSavingLlm] = useState(false);
  const [llmSaveMessage, setLlmSaveMessage] = useState('');
  
  // New Provider Form
  const [newProviderId, setNewProviderId] = useState('');
  const [newProviderBaseUrl, setNewProviderBaseUrl] = useState('');
  const [newProviderApiKey, setNewProviderApiKey] = useState('');

  // Provider states
  const [pendingApiKeys, setPendingApiKeys] = useState<Record<string, string>>({});
  const [editingApiKey, setEditingApiKey] = useState<Record<string, boolean>>({});
  const [discoverMessages, setDiscoverMessages] = useState<Record<string, string>>({});
  
  // Model management states
  const [modelPickerOpen, setModelPickerOpen] = useState<Record<string, boolean>>({});
  const [candidateModels, setCandidateModels] = useState<Record<string, string[]>>({});
  const [modelSearch, setModelSearch] = useState<Record<string, string>>({});
  const [selectedCandidates, setSelectedCandidates] = useState<Record<string, Record<string, boolean>>>({});
  
  // New model manual input states
  const [newModelInputs, setNewModelInputs] = useState<Record<string, string>>({});
  const [newModelNameInputs, setNewModelNameInputs] = useState<Record<string, string>>({});
  const [newModelMenuOpen, setNewModelMenuOpen] = useState<Record<string, boolean>>({});
  const [newModelHighlightIndex, setNewModelHighlightIndex] = useState<Record<string, number>>({});

  // Auto-save refs
  const hasInitializedLlmRef = useRef(false);
  const autoSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const savingStartedAtRef = useRef<number>(0);
  const llmDirtyRef = useRef(false);
  const latestServerPayloadRef = useRef<string>('');
  const lastSavedPayloadRef = useRef<string>('');

  const markLlmDirty = useCallback(() => {
    llmDirtyRef.current = true;
  }, []);

  const normalizeProviders = useCallback((obj: LlmProvidersConfig) => {
    const cloned: LlmProvidersConfig = JSON.parse(JSON.stringify(obj || {}));
    Object.keys(cloned).forEach(pid => {
      if (!cloned[pid].name || cloned[pid].name.trim().length === 0) {
        cloned[pid].name = pid;
      }
    });
    return cloned;
  }, []);

  const buildMergedLlmPayload = useCallback(() => {
    const merged: LlmProvidersConfig = normalizeProviders(localLlmProviders || {});
    // 待更新的 API Key 覆盖
    Object.entries(pendingApiKeys || {}).forEach(([pid, key]) => {
      if (merged[pid]) merged[pid].api_key = key;
    });
    return merged;
  }, [localLlmProviders, pendingApiKeys, normalizeProviders]);

  const flushSaveLlmImmediate = useCallback(async () => {
    const payload = buildMergedLlmPayload();
    const payloadStr = JSON.stringify(payload);
    if (payloadStr === latestServerPayloadRef.current || payloadStr === lastSavedPayloadRef.current) {
      return;
    }
    savingStartedAtRef.current = Date.now();
    setIsSavingLlm(true);
    setLlmSaveMessage('自动保存中...');
    try {
      const updated = await updateLlmProviders(payload);
      await mutateLlmProviders(updated, false);
      lastSavedPayloadRef.current = payloadStr;
      llmDirtyRef.current = false;
      setPendingApiKeys({});
      setEditingApiKey({});
      setLlmSaveMessage('已自动保存');
    } catch (e: any) {
      setLlmSaveMessage(`保存失败: ${e?.message || '未知错误'}`);
    } finally {
      const elapsed = Date.now() - (savingStartedAtRef.current || 0);
      const minMs = 1000;
      const waitMs = elapsed >= minMs ? 0 : (minMs - elapsed);
      if (waitMs > 0) {
        await new Promise((resolve) => setTimeout(resolve, waitMs));
      }
      setIsSavingLlm(false);
      setTimeout(() => setLlmSaveMessage(''), 3000);
    }
  }, [buildMergedLlmPayload, mutateLlmProviders, setPendingApiKeys, setEditingApiKey]);

  // Sync with server data initially
  useEffect(() => {
    if (llmProviders) {
      setLocalLlmProviders(llmProviders);
      const normalized = normalizeProviders(llmProviders);
      latestServerPayloadRef.current = JSON.stringify(normalized);
      llmDirtyRef.current = false;
    }
  }, [llmProviders, normalizeProviders]);

  // Auto-save effect
  useEffect(() => {
    if (!hasInitializedLlmRef.current) {
      hasInitializedLlmRef.current = true;
      return;
    }
    if (!llmDirtyRef.current) {
      return;
    }
    if (autoSaveTimerRef.current) {
      clearTimeout(autoSaveTimerRef.current);
    }
    autoSaveTimerRef.current = setTimeout(() => {
      void flushSaveLlmImmediate();
    }, 500);
    return () => {
      if (autoSaveTimerRef.current) {
        clearTimeout(autoSaveTimerRef.current);
      }
    };
  }, [localLlmProviders, pendingApiKeys, flushSaveLlmImmediate]);

  // Actions
  const handleAddProvider = () => {
      if (!newProviderId || !newProviderBaseUrl || !newProviderApiKey) {
        setLlmSaveMessage('请完整填写 Provider 信息');
        setTimeout(() => setLlmSaveMessage(''), 5000);
        return;
      }
      if (localLlmProviders[newProviderId]) {
        setLlmSaveMessage('Provider ID 已存在');
        setTimeout(() => setLlmSaveMessage(''), 5000);
        return;
      }
      markLlmDirty();
      setLocalLlmProviders(prev => ({
        ...prev,
        [newProviderId]: {
          name: newProviderId, 
          api_base_url: newProviderBaseUrl,
          api_key: newProviderApiKey,
          models: [],
        },
      }));
      setNewProviderId('');
      setNewProviderBaseUrl('');
      setNewProviderApiKey('');
  };

  const handleDiscoverModels = async (providerId: string) => {
        try {
            // 刷新前强制保存，确保后端使用最新配置
            if (llmDirtyRef.current) {
            await flushSaveLlmImmediate();
            }
            const resp = await discoverProviderModels(providerId);
            const data = Array.isArray(resp?.data) ? resp.data : null;
            if (!data) {
            setDiscoverMessages(prev => ({ ...prev, [providerId]: '候选加载失败：不支持的响应结构' }));
            setTimeout(() => setDiscoverMessages(prev => ({ ...prev, [providerId]: '' })), 5000);
            return;
            }
            const discovered: string[] = data
            .map((x: any) => (typeof x?.id === 'string' ? x.id : null))
            .filter((x: any) => typeof x === 'string');
            setCandidateModels(prev => ({ ...prev, [providerId]: discovered }));
            setDiscoverMessages(prev => ({ ...prev, [providerId]: `已加载候选模型 ${discovered.length} 个` }));
            setTimeout(() => setDiscoverMessages(prev => ({ ...prev, [providerId]: '' })), 5000);
        } catch (e: any) {
            setDiscoverMessages(prev => ({ ...prev, [providerId]: `加载失败：${e?.message || '未知错误'}` }));
            setTimeout(() => setDiscoverMessages(prev => ({ ...prev, [providerId]: '' })), 5000);
        }
  };

  return {
      localLlmProviders, setLocalLlmProviders,
      isSavingLlm, llmSaveMessage, setLlmSaveMessage,
      newProviderId, setNewProviderId,
      newProviderBaseUrl, setNewProviderBaseUrl,
      newProviderApiKey, setNewProviderApiKey,
      pendingApiKeys, setPendingApiKeys,
      editingApiKey, setEditingApiKey,
      discoverMessages,
      modelPickerOpen, setModelPickerOpen,
      candidateModels, setCandidateModels,
      modelSearch, setModelSearch,
      selectedCandidates, setSelectedCandidates,
      newModelInputs, setNewModelInputs,
      newModelNameInputs, setNewModelNameInputs,
      newModelMenuOpen, setNewModelMenuOpen,
      newModelHighlightIndex, setNewModelHighlightIndex,
      markLlmDirty,
      handleAddProvider,
      handleDiscoverModels,
      flushSaveLlmImmediate,
      llmDirtyRef
  };
}

