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

export interface TemplateInfo {
  id: string
  name: string
  description: string
  thumbnail_path: string
  draft_content_path: string
  resources_path: string
  created_at: string
  updated_at: string
  canvas_config: any
  duration: number
  material_count: number
  track_count: number
  tags: string[]
}

export interface BatchImportRequest {
  source_folder: string
}

export interface BatchImportResult {
  status: boolean
  msg: string
  imported_count: number
  failed_count: number
  imported_templates: TemplateInfo[]
  failed_templates: Array<{
    name: string
    error: string
  }>
}

export interface TemplateResult {
  status: boolean
  msg?: string
  template?: TemplateInfo
  templates?: TemplateInfo[]
}

export class TemplateService {
  /**
   * Batch import templates from a folder
   */
  static async batchImportTemplates(sourceFolder: string): Promise<BatchImportResult> {
    try {
      const request: BatchImportRequest = {
        source_folder: sourceFolder
      }

      const response = await invoke<string>('batch_import_templates', { request })
      const result = JSON.parse(response)
      
      if (!result.status) {
        throw new Error(result.error || result.msg || 'Import failed')
      }

      return result
    } catch (error) {
      console.error('Batch import templates failed:', error)
      throw error
    }
  }

  /**
   * Get all templates
   */
  static async getTemplates(): Promise<TemplateResult> {
    try {
      const response = await invoke<string>('get_templates')
      const result = JSON.parse(response)
      
      if (!result.status) {
        throw new Error(result.error || result.msg || 'Failed to get templates')
      }

      return result
    } catch (error) {
      console.error('Get templates failed:', error)
      throw error
    }
  }

  /**
   * Get a specific template
   */
  static async getTemplate(templateId: string): Promise<TemplateResult> {
    try {
      const response = await invoke<string>('get_template', { templateId })
      const result = JSON.parse(response)
      
      if (!result.status) {
        throw new Error(result.error || result.msg || 'Failed to get template')
      }

      return result
    } catch (error) {
      console.error('Get template failed:', error)
      throw error
    }
  }

  /**
   * Delete a template
   */
  static async deleteTemplate(templateId: string): Promise<TemplateResult> {
    try {
      const response = await invoke<string>('delete_template', { templateId })
      const result = JSON.parse(response)
      
      if (!result.status) {
        throw new Error(result.error || result.msg || 'Failed to delete template')
      }

      return result
    } catch (error) {
      console.error('Delete template failed:', error)
      throw error
    }
  }

  /**
   * Validate template folder structure
   */
  static validateTemplateFolder(folderPath: string): boolean {
    // This would be implemented to check if the folder contains valid template structure
    // For now, we'll rely on the backend validation
    return true
  }

  /**
   * Generate template thumbnail
   */
  static async generateThumbnail(templateId: string): Promise<string> {
    // This would be implemented to generate a thumbnail from the template
    // For now, return empty string
    return ''
  }

  /**
   * Export template
   */
  static async exportTemplate(templateId: string, targetPath: string): Promise<boolean> {
    try {
      // This would be implemented to export a template to a specific location
      // For now, just return true
      return true
    } catch (error) {
      console.error('Export template failed:', error)
      return false
    }
  }

  /**
   * Duplicate template
   */
  static async duplicateTemplate(templateId: string, newName: string): Promise<TemplateResult> {
    try {
      // This would be implemented to create a copy of an existing template
      // For now, just return a placeholder result
      return {
        status: false,
        msg: 'Duplicate functionality not implemented yet'
      }
    } catch (error) {
      console.error('Duplicate template failed:', error)
      throw error
    }
  }

  /**
   * Update template metadata
   */
  static async updateTemplate(templateId: string, updates: Partial<TemplateInfo>): Promise<TemplateResult> {
    try {
      // This would be implemented to update template metadata
      // For now, just return a placeholder result
      return {
        status: false,
        msg: 'Update functionality not implemented yet'
      }
    } catch (error) {
      console.error('Update template failed:', error)
      throw error
    }
  }

  /**
   * Search templates
   */
  static async searchTemplates(query: string, filters?: {
    tags?: string[]
    duration_min?: number
    duration_max?: number
    material_count_min?: number
    material_count_max?: number
  }): Promise<TemplateResult> {
    try {
      // This would be implemented to search templates with filters
      // For now, just get all templates and filter on frontend
      const result = await this.getTemplates()
      
      if (result.status && result.templates) {
        const filteredTemplates = result.templates.filter(template => 
          template.name.toLowerCase().includes(query.toLowerCase()) ||
          template.description.toLowerCase().includes(query.toLowerCase())
        )
        
        return {
          status: true,
          templates: filteredTemplates
        }
      }
      
      return result
    } catch (error) {
      console.error('Search templates failed:', error)
      throw error
    }
  }

  /**
   * Get template statistics
   */
  static async getTemplateStats(): Promise<{
    total_templates: number
    total_materials: number
    total_size: number
    most_used_tags: string[]
  }> {
    try {
      const result = await this.getTemplates()
      
      if (result.status && result.templates) {
        const templates = result.templates
        const totalTemplates = templates.length
        const totalMaterials = templates.reduce((sum, t) => sum + t.material_count, 0)
        
        // Extract all tags and count frequency
        const tagCounts: { [key: string]: number } = {}
        templates.forEach(template => {
          template.tags.forEach(tag => {
            tagCounts[tag] = (tagCounts[tag] || 0) + 1
          })
        })
        
        const mostUsedTags = Object.entries(tagCounts)
          .sort(([, a], [, b]) => b - a)
          .slice(0, 10)
          .map(([tag]) => tag)
        
        return {
          total_templates: totalTemplates,
          total_materials: totalMaterials,
          total_size: 0, // Would need to calculate from file sizes
          most_used_tags: mostUsedTags
        }
      }
      
      return {
        total_templates: 0,
        total_materials: 0,
        total_size: 0,
        most_used_tags: []
      }
    } catch (error) {
      console.error('Get template stats failed:', error)
      return {
        total_templates: 0,
        total_materials: 0,
        total_size: 0,
        most_used_tags: []
      }
    }
  }
}
