/**
 * Todo Service
 * Handles todo-related API calls
 */

import { apiClient } from '../client'

export type TodoStatusType = 'pending' | 'in-progress' | 'completed'
export type TodoPriorityType = 'high' | 'medium' | 'low'

export interface Todo {
  id: number
  title: string
  description: string
  status: TodoStatusType
  priority: TodoPriorityType
  startDate?: string // ISO 8601
  dueDate?: string // ISO 8601
  createdDate: string // ISO 8601
  labels: string[]
  tags: string[]
  isStarred: boolean
  isImportant: boolean
  isTrashed: boolean
  isKanban: boolean
  routine: 0 | 1 | 2 | 3 | 4
  source: 'todo' | 'calendar' | 'kanban'
}

export interface GetTodosParams {
  status?: TodoStatusType
  priority?: TodoPriorityType
  label?: string
  filter?: 'all' | 'starred' | 'important' | 'completed' | 'trashed'
  search?: string
}

export interface GetTodosResponse {
  todos: Todo[]
  total: number
}

export interface CreateTodoRequest {
  title: string
  description?: string
  status?: TodoStatusType
  priority?: TodoPriorityType
  startDate?: string // ISO 8601
  dueDate?: string // ISO 8601
  labels?: string[]
  tags?: string[]
  isStarred?: boolean
  isImportant?: boolean
  isKanban?: boolean
  routine?: 0 | 1 | 2 | 3 | 4
}

export interface CreateTodoResponse {
  todo: Todo
}

export interface UpdateTodoRequest {
  title?: string
  description?: string
  status?: TodoStatusType
  priority?: TodoPriorityType
  startDate?: string
  dueDate?: string
  labels?: string[]
  tags?: string[]
  isStarred?: boolean
  isImportant?: boolean
  isTrashed?: boolean
  isKanban?: boolean
  routine?: number
}

export interface UpdateTodoResponse {
  todo: Todo
}

export interface DeleteTodoResponse {
  success: boolean
}

export interface GetLabelsResponse {
  labels: string[]
}

// Helper functions for converting between frontend strings and backend enums
const statusToEnum = (status: TodoStatusType): number => {
  const statusMap: Record<TodoStatusType, number> = {
    'pending': 0,
    'in-progress': 1,
    'completed': 2
  }
  return statusMap[status] ?? 0
}

const enumToStatus = (enumValue: number): TodoStatusType => {
  const statusMap: Record<number, TodoStatusType> = {
    0: 'pending',
    1: 'in-progress',
    2: 'completed'
  }
  return statusMap[enumValue] ?? 'pending'
}

const priorityToEnum = (priority: TodoPriorityType): number => {
  const priorityMap: Record<TodoPriorityType, number> = {
    'high': 0,
    'medium': 1,
    'low': 2
  }
  return priorityMap[priority] ?? 1
}

const enumToPriority = (enumValue: number): TodoPriorityType => {
  const priorityMap: Record<number, TodoPriorityType> = {
    0: 'high',
    1: 'medium',
    2: 'low'
  }
  return priorityMap[enumValue] ?? 'medium'
}

// Convert backend Todo response to frontend Todo format
const convertBackendTodoToFrontend = (backendTodo: any): Todo => {
  return {
    id: backendTodo.id,
    title: backendTodo.title,
    description: backendTodo.description || '',
    status: enumToStatus(backendTodo.status),
    priority: enumToPriority(backendTodo.priority),
    startDate: backendTodo.start_date || backendTodo.startDate,
    dueDate: backendTodo.due_date || backendTodo.dueDate,
    createdDate: backendTodo.created_date || backendTodo.createdDate,
    labels: backendTodo.labels || [],
    tags: backendTodo.tags || [],
    isStarred: backendTodo.is_starred ?? backendTodo.isStarred ?? false,
    isImportant: backendTodo.is_important ?? backendTodo.isImportant ?? false,
    isTrashed: backendTodo.is_trashed ?? backendTodo.isTrashed ?? false,
    isKanban: backendTodo.is_kanban ?? backendTodo.isKanban ?? false,
    routine: (backendTodo.routine ?? 0) as 0 | 1 | 2 | 3 | 4,
    source: backendTodo.source === 0 ? 'todo' : backendTodo.source === 1 ? 'calendar' : 'kanban'
  }
}

export const todoService = {
  /**
   * دریافت لیست Todo با فیلترها
   */
  async getTodos(params?: GetTodosParams): Promise<{ todos: Todo[]; total: number }> {
    const queryParams = new URLSearchParams()
    if (params?.status) queryParams.append('status', params.status)
    if (params?.priority) queryParams.append('priority', params.priority)
    if (params?.label) queryParams.append('label', params.label)
    if (params?.filter) queryParams.append('filter', params.filter)
    if (params?.search) queryParams.append('search', params.search)

    const queryString = queryParams.toString()
    const endpoint = `/api/todos${queryString ? `?${queryString}` : ''}`

    const response = await apiClient.get<GetTodosResponse>(endpoint)
    const todos = (response.todos || []).map(convertBackendTodoToFrontend)
    return {
      todos,
      total: response.total || 0
    }
  },

  /**
   * ایجاد Todo جدید
   */
  async createTodo(data: CreateTodoRequest): Promise<Todo> {
    // Convert frontend format to backend format
    const backendData = {
      title: data.title,
      description: data.description || '',
      status: data.status ? statusToEnum(data.status) : 0, // Default to PENDING
      priority: data.priority ? priorityToEnum(data.priority) : 1, // Default to MEDIUM
      start_date: data.startDate || '',
      due_date: data.dueDate || '',
      labels: data.labels || [],
      tags: data.tags || [],
      is_starred: data.isStarred ?? false,
      is_important: data.isImportant ?? false,
      is_kanban: data.isKanban ?? false,
      routine: data.routine ?? 0 // Default to NONE
    }
    
    const response = await apiClient.post<CreateTodoResponse>('/api/todos', backendData)
    return convertBackendTodoToFrontend(response.todo)
  },

  /**
   * به‌روزرسانی Todo
   */
  async updateTodo(todoId: number, data: UpdateTodoRequest): Promise<Todo> {
    // Convert frontend format to backend format
    const backendData: any = {}
    if (data.title !== undefined) backendData.title = data.title
    if (data.description !== undefined) backendData.description = data.description
    if (data.status !== undefined) backendData.status = statusToEnum(data.status)
    if (data.priority !== undefined) backendData.priority = priorityToEnum(data.priority)
    if (data.startDate !== undefined) backendData.start_date = data.startDate
    if (data.dueDate !== undefined) backendData.due_date = data.dueDate
    if (data.labels !== undefined) backendData.labels = data.labels
    if (data.tags !== undefined) backendData.tags = data.tags
    if (data.isStarred !== undefined) backendData.is_starred = data.isStarred
    if (data.isImportant !== undefined) backendData.is_important = data.isImportant
    if (data.isTrashed !== undefined) backendData.is_trashed = data.isTrashed
    if (data.isKanban !== undefined) backendData.is_kanban = data.isKanban
    if (data.routine !== undefined) backendData.routine = data.routine
    
    const response = await apiClient.put<UpdateTodoResponse>(`/api/todos/${todoId}`, backendData)
    return convertBackendTodoToFrontend(response.todo)
  },

  /**
   * حذف Todo
   */
  async deleteTodo(todoId: number): Promise<boolean> {
    const response = await apiClient.delete<DeleteTodoResponse>(`/api/todos/${todoId}`)
    return response.success
  },

  /**
   * دریافت لیست برچسب‌های موجود
   */
  async getLabels(): Promise<string[]> {
    const response = await apiClient.get<GetLabelsResponse>('/api/todos/labels')
    return response.labels || []
  }
}




