/**
 * Kanban Service
 * Handles kanban-related API calls
 */

import { apiClient } from '../client'

export interface Column {
  id: number
  title: string
  taskIds: number[]
}

export interface AssignedUser {
  src: string
  name: string
}

export type TaskStatusType = 'pending' | 'in-progress' | 'completed'
export type TaskPriorityType = 'high' | 'medium' | 'low'

export interface KanbanTask {
  id: number
  title: string
  badgeText?: string[]
  attachments?: number
  comments?: number
  assigned?: AssignedUser[]
  image?: string
  dueDate?: string // ISO 8601
  routine: 0 | 1 | 2 | 3 | 4
  description?: string
  tags?: string[]
  priority?: TaskPriorityType
  status?: TaskStatusType
  source: 'kanban' | 'calendar' | 'todo'
}

export interface Board {
  columns: Column[]
  tasks: KanbanTask[]
}

export interface GetBoardResponse {
  columns: Column[]
  tasks: KanbanTask[]
}

export interface CreateColumnRequest {
  title: string
}

export interface CreateColumnResponse {
  column: Column
}

export interface UpdateColumnRequest {
  title?: string
  taskIds?: number[]
}

export interface UpdateColumnResponse {
  column: Column
}

export interface DeleteColumnResponse {
  success: boolean
}

export interface CreateKanbanTaskRequest {
  columnId: number
  title: string
  description?: string
  badgeText?: string[]
  attachments?: number
  comments?: number
  assigned?: AssignedUser[]
  image?: string
  dueDate?: string // ISO 8601
  routine?: 0 | 1 | 2 | 3 | 4
  tags?: string[]
  priority?: TaskPriorityType
  status?: TaskStatusType
}

export interface CreateKanbanTaskResponse {
  task: KanbanTask
}

export interface UpdateKanbanTaskRequest {
  title?: string
  description?: string
  badgeText?: string[]
  attachments?: number
  comments?: number
  assigned?: AssignedUser[]
  image?: string
  dueDate?: string
  routine?: number
  tags?: string[]
  priority?: TaskPriorityType
  status?: TaskStatusType
  columnId?: number
}

export interface UpdateKanbanTaskResponse {
  task: KanbanTask
}

export interface DeleteKanbanTaskResponse {
  success: boolean
}

export interface MoveKanbanTaskRequest {
  fromColumnId: number
  toColumnId: number
  position: number
}

export interface MoveKanbanTaskResponse {
  success: boolean
  columns: Column[]
}

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

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

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

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

// Convert backend Task response to frontend Task format
const convertBackendTaskToFrontend = (backendTask: any): KanbanTask => {
  return {
    id: backendTask.id,
    title: backendTask.title,
    badgeText: backendTask.badge_text || backendTask.badgeText,
    attachments: backendTask.attachments,
    comments: backendTask.comments,
    assigned: backendTask.assigned,
    image: backendTask.image,
    dueDate: backendTask.due_date || backendTask.dueDate,
    routine: (backendTask.routine ?? 0) as 0 | 1 | 2 | 3 | 4,
    description: backendTask.description,
    tags: backendTask.tags || [],
    priority: backendTask.priority !== undefined ? enumToPriority(backendTask.priority) : undefined,
    status: backendTask.status !== undefined ? enumToStatus(backendTask.status) : undefined,
    source: backendTask.source === 0 ? 'kanban' : backendTask.source === 1 ? 'calendar' : 'todo'
  }
}

export const kanbanService = {
  /**
   * دریافت Board Kanban
   */
  async getBoard(): Promise<Board> {
    const response = await apiClient.get<GetBoardResponse>('/api/kanban/board')
    return {
      columns: response.columns || [],
      tasks: (response.tasks || []).map(convertBackendTaskToFrontend)
    }
  },

  /**
   * ایجاد ستون جدید
   */
  async createColumn(title: string): Promise<Column> {
    const response = await apiClient.post<CreateColumnResponse>('/api/kanban/columns', { title })
    return response.column
  },

  /**
   * به‌روزرسانی ستون
   */
  async updateColumn(columnId: number, data: UpdateColumnRequest): Promise<Column> {
    const response = await apiClient.put<UpdateColumnResponse>(`/api/kanban/columns/${columnId}`, data)
    return response.column
  },

  /**
   * حذف ستون
   */
  async deleteColumn(columnId: number): Promise<boolean> {
    const response = await apiClient.delete<DeleteColumnResponse>(`/api/kanban/columns/${columnId}`)
    return response.success
  },

  /**
   * ایجاد تسک جدید
   */
  async createTask(data: CreateKanbanTaskRequest): Promise<KanbanTask> {
    // Convert frontend format to backend format
    const backendData: any = {
      column_id: data.columnId,
      title: data.title,
      description: data.description,
      badge_text: data.badgeText,
      attachments: data.attachments,
      comments: data.comments,
      assigned: data.assigned,
      image: data.image,
      due_date: data.dueDate,
      routine: data.routine ?? 0,
      tags: data.tags || []
    }
    if (data.priority !== undefined) backendData.priority = priorityToEnum(data.priority)
    if (data.status !== undefined) backendData.status = statusToEnum(data.status)
    
    const response = await apiClient.post<CreateKanbanTaskResponse>('/api/kanban/tasks', backendData)
    return convertBackendTaskToFrontend(response.task)
  },

  /**
   * به‌روزرسانی تسک
   */
  async updateTask(taskId: number, data: UpdateKanbanTaskRequest): Promise<KanbanTask> {
    // 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.badgeText !== undefined) backendData.badge_text = data.badgeText
    if (data.attachments !== undefined) backendData.attachments = data.attachments
    if (data.comments !== undefined) backendData.comments = data.comments
    if (data.assigned !== undefined) backendData.assigned = data.assigned
    if (data.image !== undefined) backendData.image = data.image
    if (data.dueDate !== undefined) backendData.due_date = data.dueDate
    if (data.routine !== undefined) backendData.routine = data.routine
    if (data.tags !== undefined) backendData.tags = data.tags
    if (data.priority !== undefined) backendData.priority = priorityToEnum(data.priority)
    if (data.status !== undefined) backendData.status = statusToEnum(data.status)
    if (data.columnId !== undefined) backendData.column_id = data.columnId
    
    const response = await apiClient.put<UpdateKanbanTaskResponse>(`/api/kanban/tasks/${taskId}`, backendData)
    return convertBackendTaskToFrontend(response.task)
  },

  /**
   * حذف تسک
   */
  async deleteTask(taskId: number): Promise<boolean> {
    const response = await apiClient.delete<DeleteKanbanTaskResponse>(`/api/kanban/tasks/${taskId}`)
    return response.success
  },

  /**
   * جابجایی تسک بین ستون‌ها
   */
  async moveTask(taskId: number, fromColumnId: number, toColumnId: number, position: number): Promise<Column[]> {
    const response = await apiClient.put<MoveKanbanTaskResponse>(`/api/kanban/tasks/${taskId}/move`, {
      fromColumnId,
      toColumnId,
      position
    })
    return response.columns || []
  }
}




