import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { OllamaService } from '../utils/ollama';
import { storage } from '../utils/indexedDB';
import { SystemConfig } from '../types';

interface OllamaStatus {
  isConnected: boolean;
  modelCount: number;
  currentModel: string;
  availableModels: any[];
  isLoading: boolean;
  error: string | null;
  config: SystemConfig | null;
}

interface OllamaContextType {
  status: OllamaStatus;
  checkStatus: () => Promise<void>;
  refreshModels: () => Promise<void>;
  chat: (message: string, context: string) => Promise<string>;
  isReady: boolean;
}

const OllamaContext = createContext<OllamaContextType | undefined>(undefined);

export const OllamaProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [status, setStatus] = useState<OllamaStatus>({
    isConnected: false,
    modelCount: 0,
    currentModel: '',
    availableModels: [],
    isLoading: true,
    error: null,
    config: null
  });

  const getService = async (): Promise<OllamaService | null> => {
    try {
      // 优先从 localStorage 读取配置，如果没有则从 IndexedDB 读取
      let config: SystemConfig;
      const localConfigData = localStorage.getItem('ai_system_config');
      if (localConfigData) {
        config = JSON.parse(localConfigData) as SystemConfig;
      } else {
        config = await storage.getSystemConfig();
      }

      if (!config.model || !config.ollamaUrl) {
        setStatus(prev => ({
          ...prev,
          error: '请先在设置中配置AI模型'
        }));
        return null;
      }

      return new OllamaService(config);
    } catch (error) {
      console.error('获取AI服务失败:', error);
      return null;
    }
  };

  const checkStatus = async () => {
    setStatus(prev => ({ ...prev, isLoading: true, error: null }));

    try {
      // 优先从 localStorage 读取配置，如果没有则从 IndexedDB 读取
      let config: SystemConfig;
      const localConfigData = localStorage.getItem('ai_system_config');
      if (localConfigData) {
        config = JSON.parse(localConfigData) as SystemConfig;
      } else {
        config = await storage.getSystemConfig();
      }

      // 如果没有配置模型，设置为空字符串
      if (!config.model) {
        config.model = '';
      }

      setStatus(prev => ({ ...prev, config }));

      const ollamaService = new OllamaService(config);

      // 检查连接状态
      const isConnected = await ollamaService.testConnection();

      if (!isConnected) {
        setStatus({
          isConnected: false,
          modelCount: 0,
          currentModel: config.model || '',
          availableModels: [],
          isLoading: false,
          error: 'Ollama 服务未连接',
          config
        });
        return;
      }

      // 获取模型列表
      const models = await ollamaService.getAvailableModelsWithInfo();

      // 验证当前配置的模型是否可用
      const currentModel = config.model || '';
      const isCurrentModelValid = currentModel && models.some(m => m.name === currentModel);

      setStatus({
        isConnected: true,
        modelCount: models.length,
        currentModel: currentModel,
        availableModels: models,
        isLoading: false,
        error: !isCurrentModelValid && currentModel ? '当前配置的模型未安装' : null,
        config
      });
    } catch (error) {
      setStatus({
        isConnected: false,
        modelCount: 0,
        currentModel: '',
        availableModels: [],
        isLoading: false,
        error: '状态检查失败',
        config: null
      });
    }
  };

  const refreshModels = async () => {
    await checkStatus();
  };

  const chat = async (message: string, context: string): Promise<string> => {
    const service = await getService();
    if (!service) {
      throw new Error('AI服务未配置或连接失败');
    }

    if (!status.config) {
      throw new Error('请先配置AI模型');
    }

    return await service.chat(message, context);
  };


  const isReady: boolean = status.isConnected && !!status.config && !!status.config.model;

  useEffect(() => {
    checkStatus();

    // 每 30 秒自动检查一次状态
    const interval = setInterval(checkStatus, 30000);

    return () => clearInterval(interval);
  }, []);

  return (
    <OllamaContext.Provider value={{ status, checkStatus, refreshModels, chat, isReady }}>
      {children}
    </OllamaContext.Provider>
  );
};

export const useOllama = () => {
  const context = useContext(OllamaContext);
  if (context === undefined) {
    throw new Error('useOllama must be used within an OllamaProvider');
  }
  return context;
};