import { create } from 'zustand'
import { AIModel, ModelTraining, PredictionResult, Recommendation } from '@api/modules/ai-model'
import { aiModelApi } from '@api'
import { QueryRequest } from '@api/types'

interface AIModelState {
  // 模型数据
  modelList: AIModel[]
  selectedModel: AIModel | null
  modelLoading: boolean
  modelPagination: {
    page: number
    pageSize: number
    total: number
  }

  // 训练数据
  trainingList: ModelTraining[]
  selectedTraining: ModelTraining | null
  trainingLoading: boolean
  trainingPagination: {
    page: number
    pageSize: number
    total: number
  }

  // 预测数据
  predictionList: PredictionResult[]
  selectedPrediction: PredictionResult | null
  predictionLoading: boolean
  predictionPagination: {
    page: number
    pageSize: number
    total: number
  }

  // 推荐数据
  recommendationList: Recommendation[]
  selectedRecommendation: Recommendation | null
  recommendationLoading: boolean
  recommendationPagination: {
    page: number
    pageSize: number
    total: number
  }
}

interface AIModelActions {
  // 模型操作
  fetchModelList: (params?: QueryRequest) => Promise<void>
  fetchModelDetail: (id: string) => Promise<void>
  createModel: (data: Omit<AIModel, 'id' | 'createdAt' | 'updatedAt' | 'accuracy' | 'status' | 'trainingDate'>) => Promise<void>
  updateModel: (id: string, data: Partial<AIModel>) => Promise<void>
  deleteModel: (id: string) => Promise<void>
  deployModel: (id: string) => Promise<void>
  setSelectedModel: (model: AIModel | null) => void

  // 训练操作
  startTraining: (data: Omit<ModelTraining, 'id' | 'status' | 'progress' | 'createdAt' | 'updatedAt'>) => Promise<void>
  fetchTrainingDetail: (id: string) => Promise<void>
  fetchTrainingList: (params?: QueryRequest) => Promise<void>
  stopTraining: (id: string) => Promise<void>
  setSelectedTraining: (training: ModelTraining | null) => void

  // 预测操作
  makePrediction: (data: { modelId: string; inputData: Record<string, any>; options?: any }) => Promise<void>
  fetchPredictionHistory: (params?: QueryRequest) => Promise<void>
  fetchPredictionDetail: (id: string) => Promise<void>
  setSelectedPrediction: (prediction: PredictionResult | null) => void

  // 推荐操作
  fetchRecommendations: (params?: QueryRequest & { type?: string; landParcelId?: string }) => Promise<void>
  applyRecommendation: (id: string) => Promise<void>
  dismissRecommendation: (id: string, reason: string) => Promise<void>
  setSelectedRecommendation: (recommendation: Recommendation | null) => void
}

export const useAIModelStore = create<AIModelState & AIModelActions>((set, get) => ({
  // 初始状态
  modelList: [],
  selectedModel: null,
  modelLoading: false,
  modelPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  trainingList: [],
  selectedTraining: null,
  trainingLoading: false,
  trainingPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  predictionList: [],
  selectedPrediction: null,
  predictionLoading: false,
  predictionPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  recommendationList: [],
  selectedRecommendation: null,
  recommendationLoading: false,
  recommendationPagination: {
    page: 1,
    pageSize: 10,
    total: 0
  },

  // 模型操作
  fetchModelList: async (params) => {
    try {
      set({ modelLoading: true })
      const response = await aiModelApi.getModelList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })
      set({
        modelList: response.data.items,
        modelPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        modelLoading: false
      })
    } catch (error) {
      console.error('获取模型列表失败:', error)
      set({ modelLoading: false })
    }
  },

  fetchModelDetail: async (id) => {
    try {
      set({ modelLoading: true })
      const response = await aiModelApi.getModelDetail(id)
      set({
        selectedModel: response.data,
        modelLoading: false
      })
    } catch (error) {
      console.error('获取模型详情失败:', error)
      set({ modelLoading: false })
    }
  },

  createModel: async (data) => {
    try {
      const response = await aiModelApi.createModel(data)
      const currentList = get().modelList
      set({
        modelList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('创建模型失败:', error)
    }
  },

  updateModel: async (id, data) => {
    try {
      const response = await aiModelApi.updateModel(id, data)
      const currentList = get().modelList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        modelList: updatedList,
        selectedModel: response.data
      })
    } catch (error) {
      console.error('更新模型失败:', error)
    }
  },

  deleteModel: async (id) => {
    try {
      await aiModelApi.deleteModel(id)
      const currentList = get().modelList
      const updatedList = currentList.filter(item => item.id !== id)
      set({
        modelList: updatedList,
        selectedModel: null
      })
    } catch (error) {
      console.error('删除模型失败:', error)
    }
  },

  deployModel: async (id) => {
    try {
      const response = await aiModelApi.deployModel(id)
      const currentList = get().modelList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        modelList: updatedList,
        selectedModel: response.data
      })
    } catch (error) {
      console.error('部署模型失败:', error)
    }
  },

  setSelectedModel: (model) => set({ selectedModel: model }),

  // 训练操作
  startTraining: async (data) => {
    try {
      const response = await aiModelApi.startTraining(data)
      const currentList = get().trainingList
      set({
        trainingList: [response.data, ...currentList]
      })
    } catch (error) {
      console.error('开始训练失败:', error)
    }
  },

  fetchTrainingDetail: async (id) => {
    try {
      set({ trainingLoading: true })
      const response = await aiModelApi.getTrainingDetail(id)
      set({
        selectedTraining: response.data,
        trainingLoading: false
      })
    } catch (error) {
      console.error('获取训练详情失败:', error)
      set({ trainingLoading: false })
    }
  },

  fetchTrainingList: async (params) => {
    try {
      set({ trainingLoading: true })
      const response = await aiModelApi.getTrainingList({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })
      set({
        trainingList: response.data.items,
        trainingPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        trainingLoading: false
      })
    } catch (error) {
      console.error('获取训练列表失败:', error)
      set({ trainingLoading: false })
    }
  },

  stopTraining: async (id) => {
    try {
      await aiModelApi.stopTraining(id)
      const currentList = get().trainingList
      const updatedList = currentList.map(item =>
        item.id === id ? { ...item, status: 'completed' as const } : item
      )
      set({
        trainingList: updatedList,
        selectedTraining: get().selectedTraining?.id === id
          ? { ...get().selectedTraining, status: 'completed' as const }
          : get().selectedTraining
      })
    } catch (error) {
      console.error('停止训练失败:', error)
    }
  },

  setSelectedTraining: (training) => set({ selectedTraining: training }),

  // 预测操作
  makePrediction: async (data) => {
    try {
      set({ predictionLoading: true })
      const response = await aiModelApi.makePrediction(data)
      const currentList = get().predictionList
      set({
        predictionList: [response.data, ...currentList],
        predictionLoading: false
      })
    } catch (error) {
      console.error('预测失败:', error)
      set({ predictionLoading: false })
    }
  },

  fetchPredictionHistory: async (params) => {
    try {
      set({ predictionLoading: true })
      const response = await aiModelApi.getPredictionHistory({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })
      set({
        predictionList: response.data.items,
        predictionPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        predictionLoading: false
      })
    } catch (error) {
      console.error('获取预测历史失败:', error)
      set({ predictionLoading: false })
    }
  },

  fetchPredictionDetail: async (id) => {
    try {
      set({ predictionLoading: true })
      const response = await aiModelApi.getPredictionDetail(id)
      set({
        selectedPrediction: response.data,
        predictionLoading: false
      })
    } catch (error) {
      console.error('获取预测详情失败:', error)
      set({ predictionLoading: false })
    }
  },

  setSelectedPrediction: (prediction) => set({ selectedPrediction: prediction }),

  // 推荐操作
  fetchRecommendations: async (params) => {
    try {
      set({ recommendationLoading: true })
      const response = await aiModelApi.getRecommendations({
        page: params?.page || 1,
        pageSize: params?.pageSize || 10,
        ...params
      })
      set({
        recommendationList: response.data.items,
        recommendationPagination: {
          page: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total
        },
        recommendationLoading: false
      })
    } catch (error) {
      console.error('获取推荐列表失败:', error)
      set({ recommendationLoading: false })
    }
  },

  applyRecommendation: async (id) => {
    try {
      const response = await aiModelApi.applyRecommendation(id)
      const currentList = get().recommendationList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        recommendationList: updatedList,
        selectedRecommendation: response.data
      })
    } catch (error) {
      console.error('应用推荐失败:', error)
    }
  },

  dismissRecommendation: async (id, reason) => {
    try {
      const response = await aiModelApi.dismissRecommendation(id, reason)
      const currentList = get().recommendationList
      const updatedList = currentList.map(item =>
        item.id === id ? response.data : item
      )
      set({
        recommendationList: updatedList,
        selectedRecommendation: response.data
      })
    } catch (error) {
      console.error('忽略推荐失败:', error)
    }
  },

  setSelectedRecommendation: (recommendation) => set({ selectedRecommendation: recommendation })
}))