import { invoke } from '@tauri-apps/api/core'
import { useAuthStore } from '../stores/useAuthStore'

// 扩展的资源分类接口，包含新字段
export interface ResourceCategoryV2 {
  id: string
  title: string
  ai_prompt: string
  color: string
  created_at: string
  updated_at: string
  is_active: boolean
  is_cloud: boolean
  user_id: string
}

// 新的响应格式
export interface ResourceCategoryResponse {
  success: boolean
  message: string
  data?: any
  output?: string
  error?: string
}

// 请求接口
export interface CategoryListRequest {
  user_id?: string
  include_cloud?: boolean
  limit?: number
  verbose?: boolean
  json_output?: boolean
}

export interface CategoryGetRequest {
  category_id: string
  user_id?: string
  verbose?: boolean
  json_output?: boolean
}

export interface CategoryCreateRequest {
  title: string
  ai_prompt?: string
  color?: string
  is_cloud?: boolean
  user_id?: string
  verbose?: boolean
  json_output?: boolean
}

export interface CategoryUpdateRequest {
  category_id: string
  title?: string
  ai_prompt?: string
  color?: string
  is_active?: boolean
  user_id?: string
  verbose?: boolean
  json_output?: boolean
}

export interface CategoryDeleteRequest {
  category_id: string
  hard_delete?: boolean
  user_id?: string
  verbose?: boolean
  json_output?: boolean
}

export interface CategorySearchRequest {
  query: string
  user_id?: string
  include_cloud?: boolean
  limit?: number
  verbose?: boolean
  json_output?: boolean
}

export interface CategoryColorRequest {
  color: string
  user_id?: string
  include_cloud?: boolean
  limit?: number
  verbose?: boolean
  json_output?: boolean
}

export interface CategoryBatchItem {
  title: string
  ai_prompt?: string
  color?: string
  is_cloud?: boolean
}

export interface CategoryBatchCreateRequest {
  categories: CategoryBatchItem[]
  user_id?: string
  verbose?: boolean
  json_output?: boolean
}

export interface BatchCreateResult {
  total: number
  success: number
  failed: number
  error?: string
}

export class ResourceCategoryServiceV2 {
  /**
   * 获取当前用户ID
   */
  private static getCurrentUserId(): string {
    const authState = useAuthStore.getState()

    if (!authState.isAuthenticated || !authState.user?.id) {
      throw new Error('用户未登录，请先登录后再进行操作')
    }

    return authState.user.id
  }

  /**
   * 获取所有分类（新版本）
   */
  static async getAllCategories(request?: Partial<CategoryListRequest>): Promise<ResourceCategoryV2[]> {
    try {
      const params: CategoryListRequest = {
        user_id: request?.user_id || this.getCurrentUserId(),
        include_cloud: true,
        limit: 100,
        verbose: false,
        json_output: true,
        ...request
      }

      const response = await invoke<ResourceCategoryResponse>('get_all_resource_categories_cli', { request: params })
      
      if (response.success && response.data) {
        return Array.isArray(response.data) ? response.data : []
      } else {
        console.error('Failed to get categories:', response.error || response.message)
        return []
      }
    } catch (error) {
      console.error('Failed to get all categories:', error)
      return []
    }
  }

  /**
   * 根据ID获取分类
   */
  static async getCategoryById(categoryId: string, userId?: string): Promise<ResourceCategoryV2 | null> {
    try {
      const params: CategoryGetRequest = {
        category_id: categoryId,
        user_id: userId || this.getCurrentUserId(),
        verbose: false,
        json_output: true
      }

      const response = await invoke<ResourceCategoryResponse>('get_resource_category_by_id_cli', { request: params })
      
      if (response.success && response.data) {
        return response.data
      } else {
        console.error('Failed to get category:', response.error || response.message)
        return null
      }
    } catch (error) {
      console.error('Failed to get category by id:', error)
      return null
    }
  }

  /**
   * 创建新分类
   */
  static async createCategory(
    title: string,
    aiPrompt?: string,
    color?: string,
    isCloud?: boolean,
    userId?: string
  ): Promise<ResourceCategoryV2 | null> {
    try {
      const params: CategoryCreateRequest = {
        title,
        ai_prompt: aiPrompt || '',
        color: color || '#FF5733',
        is_cloud: isCloud || false,
        user_id: userId || this.getCurrentUserId(),
        verbose: false,
        json_output: true
      }

      const response = await invoke<ResourceCategoryResponse>('create_resource_category_cli', { request: params })
      
      if (response.success && response.data) {
        return response.data
      } else {
        console.error('Failed to create category:', response.error || response.message)
        throw new Error(response.error || response.message || 'Failed to create category')
      }
    } catch (error) {
      console.error('Failed to create category:', error)
      throw error
    }
  }

  /**
   * 更新分类
   */
  static async updateCategory(
    categoryId: string,
    updates: {
      title?: string
      ai_prompt?: string
      color?: string
      is_active?: boolean
    },
    userId?: string
  ): Promise<ResourceCategoryV2 | null> {
    try {
      const params: CategoryUpdateRequest = {
        category_id: categoryId,
        title: updates.title,
        ai_prompt: updates.ai_prompt,
        color: updates.color,
        is_active: updates.is_active,
        user_id: userId || this.getCurrentUserId(),
        verbose: false,
        json_output: true
      }

      const response = await invoke<ResourceCategoryResponse>('update_resource_category_cli', { request: params })
      
      if (response.success && response.data) {
        return response.data
      } else {
        console.error('Failed to update category:', response.error || response.message)
        throw new Error(response.error || response.message || 'Failed to update category')
      }
    } catch (error) {
      console.error('Failed to update category:', error)
      throw error
    }
  }

  /**
   * 删除分类
   */
  static async deleteCategory(categoryId: string, hardDelete = true, userId?: string): Promise<boolean> {
    try {
      const params: CategoryDeleteRequest = {
        category_id: categoryId,
        hard_delete: hardDelete,
        user_id: userId || this.getCurrentUserId(),
        verbose: false,
        json_output: true
      }

      const response = await invoke<ResourceCategoryResponse>('delete_resource_category_cli', { request: params })
      
      if (response.success) {
        return true
      } else {
        console.error('Failed to delete category:', response.error || response.message)
        throw new Error(response.error || response.message || 'Failed to delete category')
      }
    } catch (error) {
      console.error('Failed to delete category:', error)
      throw error
    }
  }

  /**
   * 搜索分类
   */
  static async searchCategories(query: string, request?: Partial<CategorySearchRequest>): Promise<ResourceCategoryV2[]> {
    try {
      const params: CategorySearchRequest = {
        query,
        user_id: this.getCurrentUserId(),
        include_cloud: true,
        limit: 50,
        verbose: false,
        json_output: true,
        ...request
      }

      const response = await invoke<ResourceCategoryResponse>('search_resource_categories_cli', { request: params })
      
      if (response.success && response.data) {
        return Array.isArray(response.data) ? response.data : []
      } else {
        console.error('Failed to search categories:', response.error || response.message)
        return []
      }
    } catch (error) {
      console.error('Failed to search categories:', error)
      return []
    }
  }

  /**
   * 按颜色获取分类
   */
  static async getCategoriesByColor(color: string, request?: Partial<CategoryColorRequest>): Promise<ResourceCategoryV2[]> {
    try {
      const params: CategoryColorRequest = {
        color,
        user_id: this.getCurrentUserId(),
        include_cloud: true,
        limit: 50,
        verbose: false,
        json_output: true,
        ...request
      }

      const response = await invoke<ResourceCategoryResponse>('get_resource_categories_by_color_cli', { request: params })
      
      if (response.success && response.data) {
        return Array.isArray(response.data) ? response.data : []
      } else {
        console.error('Failed to get categories by color:', response.error || response.message)
        return []
      }
    } catch (error) {
      console.error('Failed to get categories by color:', error)
      return []
    }
  }

  /**
   * 获取云端分类
   */
  static async getCloudCategories(limit = 100): Promise<ResourceCategoryV2[]> {
    try {
      const params: CategoryListRequest = {
        limit,
        verbose: false,
        json_output: true
      }

      const response = await invoke<ResourceCategoryResponse>('get_cloud_resource_categories_cli', { request: params })
      
      if (response.success && response.data) {
        return Array.isArray(response.data) ? response.data : []
      } else {
        console.error('Failed to get cloud categories:', response.error || response.message)
        return []
      }
    } catch (error) {
      console.error('Failed to get cloud categories:', error)
      return []
    }
  }

  /**
   * 批量创建分类
   */
  static async batchCreateCategories(categories: CategoryBatchItem[], userId?: string): Promise<BatchCreateResult> {
    try {
      const params: CategoryBatchCreateRequest = {
        categories,
        user_id: userId || this.getCurrentUserId(),
        verbose: false,
        json_output: true
      }

      const response = await invoke<ResourceCategoryResponse>('batch_create_resource_categories_cli', { request: params })
      
      if (response.success && response.data) {
        return response.data
      } else {
        console.error('Failed to batch create categories:', response.error || response.message)
        throw new Error(response.error || response.message || 'Failed to batch create categories')
      }
    } catch (error) {
      console.error('Failed to batch create categories:', error)
      throw error
    }
  }

  /**
   * 获取分类数量
   */
  static async getCategoryCount(includeCloud = true, userId?: string): Promise<number> {
    try {
      const params: CategoryListRequest = {
        user_id: userId || this.getCurrentUserId(),
        include_cloud: includeCloud,
        verbose: false,
        json_output: true
      }

      const response = await invoke<ResourceCategoryResponse>('get_resource_category_count_cli', { request: params })
      
      if (response.success && response.data && typeof response.data.count === 'number') {
        return response.data.count
      } else {
        console.error('Failed to get category count:', response.error || response.message)
        return 0
      }
    } catch (error) {
      console.error('Failed to get category count:', error)
      return 0
    }
  }

  /**
   * 激活分类
   */
  static async activateCategory(categoryId: string, userId?: string): Promise<boolean> {
    try {
      const params: CategoryGetRequest = {
        category_id: categoryId,
        user_id: userId || this.getCurrentUserId(),
        verbose: false,
        json_output: true
      }

      const response = await invoke<ResourceCategoryResponse>('activate_resource_category_cli', { request: params })
      
      if (response.success) {
        return true
      } else {
        console.error('Failed to activate category:', response.error || response.message)
        throw new Error(response.error || response.message || 'Failed to activate category')
      }
    } catch (error) {
      console.error('Failed to activate category:', error)
      throw error
    }
  }

  /**
   * 停用分类
   */
  static async deactivateCategory(categoryId: string, userId?: string): Promise<boolean> {
    try {
      const params: CategoryGetRequest = {
        category_id: categoryId,
        user_id: userId || this.getCurrentUserId(),
        verbose: false,
        json_output: true
      }

      const response = await invoke<ResourceCategoryResponse>('deactivate_resource_category_cli', { request: params })
      
      if (response.success) {
        return true
      } else {
        console.error('Failed to deactivate category:', response.error || response.message)
        throw new Error(response.error || response.message || 'Failed to deactivate category')
      }
    } catch (error) {
      console.error('Failed to deactivate category:', error)
      throw error
    }
  }

}
