import { apiClient } from '../client'
import type { ConversationSummary, FarmContext } from '@views/dashboards/farm/farmAiAssistant/farmAiAssistantTypes'

const PREFIX = '/api/farm-ai-assistant'

export interface FarmContextResponse {
  soilType: string
  waterEC: string
  selectedCrop: string
  growthStage: string
  lastIrrigationStatus: string
}

export interface ChatSection {
  type: 'text' | 'list' | 'recommendation' | 'warning'
  title?: string
  content?: string
  items?: string[]
  icon?: 'droplet' | 'leaf' | 'warning' | 'fertilizer' | 'calendar'
  frequency?: string
  amount?: string
  timing?: string
  expandableExplanation?: string
}

export interface ChatPayload {
  content?: string
  images?: string[]
  conversation_id?: string
  title?: string
  farm_context?: Partial<FarmContext>
}

export interface ChatTaskInitResponse {
  task_id: string
  status: 'PENDING' | 'STARTED' | 'SUCCESS' | 'FAILURE'
  status_url?: string
  conversation_id: string
  message_id: string
}

export interface ChatTaskStatusResponse {
  task_id: string
  status: 'PENDING' | 'STARTED' | 'SUCCESS' | 'FAILURE'
  conversation_id: string
  progress?: {
    message?: string
  }
  result?: ChatMessageResponse
  error?: string
}

export interface ChatMessageResponse {
  message_id: string
  conversation_id: string
  role: 'user' | 'assistant'
  content: string
  sections: ChatSection[]
  images?: string[]
  created_at?: string
}

export interface ConversationMessagesResponse {
  conversation_id: string
  messages: ChatMessageResponse[]
}

export interface CreateConversationPayload {
  title?: string
  farm_context?: Partial<FarmContext>
}

export interface CreateConversationResponse {
  id: string
  message_count: number
  title?: string
  updated_at?: string
}

interface ApiResponse<T> {
  status: string
  data: T
}

function unwrap<T>(res: ApiResponse<T>): T {
  return res.data
}

export const farmAiAssistantService = {
  getContext(): Promise<FarmContextResponse> {
    return apiClient.get<ApiResponse<FarmContextResponse>>(`${PREFIX}/context/`).then(unwrap)
  },

  createChatTask(payload: ChatPayload): Promise<ChatTaskInitResponse> {
    return apiClient.post<ApiResponse<ChatTaskInitResponse>>(`${PREFIX}/chat/task/`, payload).then(unwrap)
  },

  getChatTaskStatus(taskId: string): Promise<ChatTaskStatusResponse> {
    return apiClient.get<ApiResponse<ChatTaskStatusResponse>>(`${PREFIX}/chat/task/${taskId}/status/`).then(unwrap)
  },

  getConversations(): Promise<ConversationSummary[]> {
    return apiClient.get<ApiResponse<ConversationSummary[]>>(`${PREFIX}/chats/`).then(unwrap)
  },

  createConversation(payload?: CreateConversationPayload): Promise<CreateConversationResponse> {
    return apiClient.post<ApiResponse<CreateConversationResponse>>(`${PREFIX}/chats/`, payload).then(unwrap)
  },

  deleteConversation(conversationId: string): Promise<{ conversation_id: string }> {
    return apiClient.delete<ApiResponse<{ conversation_id: string }>>(`${PREFIX}/chats/${conversationId}/`).then(unwrap)
  },

  getConversationMessages(conversationId: string): Promise<ConversationMessagesResponse> {
    return apiClient
      .get<ApiResponse<ConversationMessagesResponse>>(`${PREFIX}/chats/${conversationId}/messages/`)
      .then(unwrap)
  }
}
