import apiClient from './client';
import type { Task, CreateTaskDto, UpdateTaskDto, ApiResponse } from '../types/task';
import LocalStorageService from '../services/localStorageService';
import { normalizeTask, normalizeTasks } from '../services/taskNormalizer';

export const taskApi = {
  /**
   * 获取任务列表
   * @param completed 可选，过滤已完成或未完成的任务
   * @returns 包含任务数组的响应对象
   */
  async getTasks(completed?: boolean): Promise<ApiResponse<Task[]>> {
    if (!LocalStorageService.isOnline()) {
      const localTasks = LocalStorageService.loadTasks();
      return {
        success: true,
        data: completed !== undefined 
          ? localTasks.filter(t => t.isCompleted === completed)
          : localTasks,
        message: '从本地加载任务'
      };
    }

    const endpoint = completed === true 
      ? '/task/completed'
      : completed === false
      ? '/task/active'
      : '/task';

    const response = await apiClient.get<Task[] | ApiResponse<Task[]>>(endpoint);
    
    let apiResponse: ApiResponse<Task[]>;
    if (Array.isArray(response.data)) {
      // 后端直接返回任务数组
      apiResponse = {
        success: true,
        data: response.data,
        message: '获取任务成功'
      };
    } else {
      // 后端返回包装的响应对象
      apiResponse = response.data as ApiResponse<Task[]>;
    }
    
    if (apiResponse.success && apiResponse.data) {
      apiResponse.data = normalizeTasks(apiResponse.data);
      LocalStorageService.saveTasks(apiResponse.data);
      const syncStatus = LocalStorageService.loadSyncStatus();
      syncStatus.lastSyncTime = Date.now();
      syncStatus.isOnline = true;
      syncStatus.pendingChanges = 0;
      LocalStorageService.saveSyncStatus(syncStatus);
    }
    
    return apiResponse;
  },

  /**
   * 根据 ID 获取任务详情
   * @param id 任务 ID
   * @returns 包含任务对象或 null 的响应对象
   */
  async getTask(id: number): Promise<ApiResponse<Task | null>> {
    if (!LocalStorageService.isOnline()) {
      const localTasks = LocalStorageService.loadTasks();
      const task = localTasks.find(t => t.id === id);
      return {
        success: true,
        data: task || null,
        message: task ? '从本地加载任务' : '任务不存在'
      };
    }

    const response = await apiClient.get<Task | ApiResponse<Task>>(`/task/${id}`);
    
    let apiResponse: ApiResponse<Task>;
    if (response.data && 'id' in response.data) {
      // 后端直接返回任务对象
      apiResponse = {
        success: true,
        data: response.data,
        message: '获取任务成功'
      };
    } else {
      // 后端返回包装的响应对象
      apiResponse = response.data as ApiResponse<Task>;
    }

    if (apiResponse.success && apiResponse.data) {
      apiResponse.data = normalizeTask(apiResponse.data);
    }
    
    return apiResponse;
  },

  /**
   * 创建新任务
   * @param dto 创建任务的数据传输对象
   * @returns 包含新创建任务的响应对象
   */
  async createTask(dto: CreateTaskDto): Promise<ApiResponse<Task>> {
    const newTask: Task = {
      id: Date.now(),
      title: dto.title,
      priority: dto.priority,
      isCompleted: false,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      parentTaskId: dto.parentTaskId,
      subTasks: []
    };

    if (!LocalStorageService.isOnline()) {
      const localTasks = LocalStorageService.loadTasks();
      localTasks.unshift(newTask);
      LocalStorageService.saveTasks(localTasks);
      
      const syncStatus = LocalStorageService.loadSyncStatus();
      syncStatus.pendingChanges++;
      LocalStorageService.saveSyncStatus(syncStatus);
      
      return {
        success: true,
        data: newTask,
        message: '离线创建任务成功'
      };
    }

    const response = await apiClient.post<Task | ApiResponse<Task>>('/task', dto);
    
    let apiResponse: ApiResponse<Task>;
    if (response.data && 'id' in response.data) {
      // 后端直接返回任务对象
      apiResponse = {
        success: true,
        data: response.data,
        message: '创建任务成功'
      };
    } else {
      // 后端返回包装的响应对象
      apiResponse = response.data as ApiResponse<Task>;
    }
    
    if (apiResponse.success && apiResponse.data) {
      apiResponse.data = normalizeTask(apiResponse.data);
      const localTasks = LocalStorageService.loadTasks();
      const existingIndex = localTasks.findIndex(t => t.id === newTask.id);
      if (existingIndex !== -1) {
        localTasks[existingIndex] = apiResponse.data;
      } else {
        localTasks.unshift(apiResponse.data);
      }
      LocalStorageService.saveTasks(localTasks);
    }
    
    return apiResponse;
  },

  /**
   * 更新任务信息
   * @param id 任务 ID
   * @param dto 更新任务的数据传输对象
   * @returns 包含更新后任务的响应对象
   */
  async updateTask(id: number, dto: UpdateTaskDto): Promise<ApiResponse<Task>> {
    const updateDto = dto;
    
    if (!LocalStorageService.isOnline()) {
      const localTasks = LocalStorageService.loadTasks();
      const taskIndex = localTasks.findIndex(t => t.id === id);
      
      if (taskIndex !== -1) {
        if (dto.title) {
          localTasks[taskIndex].title = dto.title;
        }
        if (dto.priority !== undefined) {
          localTasks[taskIndex].priority = dto.priority;
        }
        localTasks[taskIndex].updatedAt = new Date().toISOString();
        LocalStorageService.saveTasks(localTasks);
        
        const syncStatus = LocalStorageService.loadSyncStatus();
        syncStatus.pendingChanges++;
        LocalStorageService.saveSyncStatus(syncStatus);
        
        return {
          success: true,
          data: localTasks[taskIndex],
          message: '离线更新任务成功'
        };
      }
      
      return {
        success: false,
        message: '任务不存在'
      };
    }

    const response = await apiClient.put<Task | ApiResponse<Task>>('/task', updateDto);
    
    let apiResponse: ApiResponse<Task>;
    if (response.data && 'id' in response.data) {
      // 后端直接返回任务对象
      apiResponse = {
        success: true,
        data: response.data,
        message: '更新任务成功'
      };
    } else {
      // 后端返回包装的响应对象
      apiResponse = response.data as ApiResponse<Task>;
    }
    
    if (apiResponse.success && apiResponse.data) {
      apiResponse.data = normalizeTask(apiResponse.data);
      const localTasks = LocalStorageService.loadTasks();
      const taskIndex = localTasks.findIndex(t => t.id === id);
      if (taskIndex !== -1) {
        localTasks[taskIndex] = apiResponse.data;
        LocalStorageService.saveTasks(localTasks);
      }
    }
    
    return apiResponse;
  },

  /**
   * 切换任务完成状态
   * @param id 任务 ID
   * @returns 包含更新后任务的响应对象
   */
  async toggleComplete(id: number): Promise<ApiResponse<Task>> {
    if (!LocalStorageService.isOnline()) {
      const localTasks = LocalStorageService.loadTasks();
      const taskIndex = localTasks.findIndex(t => t.id === id);
      
      if (taskIndex !== -1) {
        localTasks[taskIndex].isCompleted = !localTasks[taskIndex].isCompleted;
        localTasks[taskIndex].updatedAt = new Date().toISOString();
        LocalStorageService.saveTasks(localTasks);
        
        const syncStatus = LocalStorageService.loadSyncStatus();
        syncStatus.pendingChanges++;
        LocalStorageService.saveSyncStatus(syncStatus);
        
        return {
          success: true,
          data: localTasks[taskIndex],
          message: '离线切换任务状态成功'
        };
      }
      
      return {
        success: false,
        message: '任务不存在'
      };
    }

    const response = await apiClient.patch<Task | ApiResponse<Task>>(`/task/${id}/toggle`);
    
    let apiResponse: ApiResponse<Task>;
    if (response.data && 'id' in response.data) {
      // 后端直接返回任务对象
      apiResponse = {
        success: true,
        data: response.data,
        message: '切换任务状态成功'
      };
    } else {
      // 后端返回包装的响应对象
      apiResponse = response.data as ApiResponse<Task>;
    }
    
    if (apiResponse.success && apiResponse.data) {
      apiResponse.data = normalizeTask(apiResponse.data);
      const localTasks = LocalStorageService.loadTasks();
      const taskIndex = localTasks.findIndex(t => t.id === id);
      if (taskIndex !== -1) {
        localTasks[taskIndex] = apiResponse.data;
        LocalStorageService.saveTasks(localTasks);
      }
    }
    
    return apiResponse;
  },

  /**
   * 删除任务
   * @param id 任务 ID
   * @returns 包含操作结果的响应对象
   */
  async deleteTask(id: number): Promise<ApiResponse<object>> {
    if (!LocalStorageService.isOnline()) {
      const localTasks = LocalStorageService.loadTasks();
      const taskIndex = localTasks.findIndex(t => t.id === id);
      
      if (taskIndex !== -1) {
        localTasks.splice(taskIndex, 1);
        LocalStorageService.saveTasks(localTasks);
        
        const syncStatus = LocalStorageService.loadSyncStatus();
        syncStatus.pendingChanges++;
        LocalStorageService.saveSyncStatus(syncStatus);
        
        return {
          success: true,
          message: '离线删除任务成功'
        };
      }
      
      return {
        success: false,
        message: '任务不存在'
      };
    }

    const response = await apiClient.delete<any | ApiResponse<object>>(`/task/${id}`);
    
    let apiResponse: ApiResponse<object>;
    if (response.data && typeof response.data === 'object' && 'success' in response.data) {
      // 后端返回包装的响应对象
      apiResponse = response.data as ApiResponse<object>;
    } else {
      // 后端返回其他格式
      apiResponse = {
        success: true,
        message: '删除任务成功'
      };
    }
    
    if (apiResponse.success) {
      const localTasks = LocalStorageService.loadTasks();
      const taskIndex = localTasks.findIndex(t => t.id === id);
      if (taskIndex !== -1) {
        localTasks.splice(taskIndex, 1);
        LocalStorageService.saveTasks(localTasks);
      }
    }
    
    return apiResponse;
  },

  /**
   * 同步本地更改到服务器
   * @returns 包含最新任务列表的响应对象
   */
  async syncToServer(): Promise<ApiResponse<Task[]>> {
    if (!LocalStorageService.isOnline()) {
      return {
        success: false,
        message: '当前离线，无法同步'
      };
    }

    const localTasks = LocalStorageService.loadTasks();
    const syncStatus = LocalStorageService.loadSyncStatus();
    
    if (syncStatus.pendingChanges === 0) {
      return {
        success: true,
        data: localTasks,
        message: '没有待同步的更改'
      };
    }

    try {
      const response = await apiClient.get<Task[] | ApiResponse<Task[]>>('/task');
      
      let apiResponse: ApiResponse<Task[]>;
      if (Array.isArray(response.data)) {
        // 后端直接返回任务数组
        apiResponse = {
          success: true,
          data: response.data,
          message: '获取任务成功'
        };
      } else {
        // 后端返回包装的响应对象
        apiResponse = response.data as ApiResponse<Task[]>;
      }
      
      if (apiResponse.success && apiResponse.data) {
        apiResponse.data = normalizeTasks(apiResponse.data);
        LocalStorageService.saveTasks(apiResponse.data);
        syncStatus.lastSyncTime = Date.now();
        syncStatus.isOnline = true;
        syncStatus.pendingChanges = 0;
        LocalStorageService.saveSyncStatus(syncStatus);
        
        return {
          success: true,
          data: apiResponse.data,
          message: '同步成功'
        };
      }
      
      return {
        success: false,
        message: '同步失败'
      };
    } catch (error) {
      console.error('Sync failed:', error);
      return {
        success: false,
        message: '同步失败'
      };
    }
  },
};
