export interface DatabaseTemplate {
  id: string
  type: string
  title: string
  description: string
  icon: string | null
  category: string
  gradient: string | null
  border: string | null
  text: string | null
  subtext: string | null
  is_active: boolean
  created_at: string
  updated_at: string
  feature_count?: number
  avg_rating?: number
}

export interface TemplateFeature {
  id: string
  template_id: string
  feature_id: string
  name: string
  description: string
  feature_type: 'essential' | 'suggested' | 'custom'
  complexity: 'low' | 'medium' | 'high'
  display_order: number
  usage_count: number
  user_rating: number
  is_default: boolean
  created_by_user: boolean
  created_at: string
  updated_at: string
}

export interface TemplateWithFeatures extends DatabaseTemplate {
  features: TemplateFeature[]
}

export interface TemplatesByCategory {
  [category: string]: DatabaseTemplate[]
}

const API_BASE_URL = 'http://localhost:8009'

class TemplateService {
  private async makeRequest<T>(endpoint: string): Promise<T> {
    try {
      const response = await fetch(`${API_BASE_URL}${endpoint}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      
      if (!data.success) {
        throw new Error(data.message || 'API request failed')
      }

      return data.data
    } catch (error) {
      console.error('Template service error:', error)
      throw error
    }
  }

  async getTemplatesByCategory(): Promise<TemplatesByCategory> {
    return this.makeRequest<TemplatesByCategory>('/api/templates')
  }

  async getTemplateById(id: string): Promise<TemplateWithFeatures> {
    return this.makeRequest<TemplateWithFeatures>(`/api/templates/${id}`)
  }

  async getTemplateByType(type: string): Promise<TemplateWithFeatures> {
    return this.makeRequest<TemplateWithFeatures>(`/api/templates/type/${type}`)
  }

  async createTemplate(templateData: Partial<DatabaseTemplate>): Promise<DatabaseTemplate> {
    try {
      const response = await fetch(`${API_BASE_URL}/api/templates`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(templateData),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      
      if (!data.success) {
        throw new Error(data.message || 'Failed to create template')
      }

      return data.data
    } catch (error) {
      console.error('Create template error:', error)
      throw error
    }
  }

  // Features API
  async getFeaturesForTemplate(templateId: string): Promise<TemplateFeature[]> {
    // Use merged endpoint to include custom features
    try {
      return await this.makeRequest<TemplateFeature[]>(`/api/features/templates/${templateId}/merged`)
    } catch {
      // Fallback to default-only if merged endpoint unsupported
      return this.makeRequest<TemplateFeature[]>(`/api/templates/${templateId}/features`)
    }
  }

  async searchFeatures(searchTerm: string, templateId?: string): Promise<TemplateFeature[]> {
    const q = encodeURIComponent(searchTerm)
    const extra = templateId ? `&template_id=${encodeURIComponent(templateId)}` : ''
    return this.makeRequest<TemplateFeature[]>(`/api/features/search?q=${q}${extra}`)
  }

  async createFeature(featureData: Partial<TemplateFeature>): Promise<TemplateFeature> {
    if (
      featureData &&
      (featureData.feature_type === 'custom' || (featureData as any).feature_type === 'custom')
    ) {
      const response = await fetch(`${API_BASE_URL}/api/features/custom`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(featureData),
      })
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
      const data = await response.json()
      if (!data.success) throw new Error(data.message || 'Failed to create custom feature')
      return data.data
    }
    const response = await fetch(`${API_BASE_URL}/api/features`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(featureData),
    })
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
    const data = await response.json()
    if (!data.success) throw new Error(data.message || 'Failed to create feature')
    return data.data
  }

  async updateFeature(id: string, featureData: Partial<TemplateFeature> & { isCustom?: boolean }): Promise<TemplateFeature> {
    const isCustom = (featureData as any).isCustom || featureData.feature_type === 'custom'
    const url = isCustom ? `${API_BASE_URL}/api/features/custom/${id}` : `${API_BASE_URL}/api/features/${id}`
    const response = await fetch(url, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(featureData),
    })
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
    const data = await response.json()
    if (!data.success) throw new Error(data.message || 'Failed to update feature')
    return data.data
  }

  async deleteFeature(id: string, opts?: { isCustom?: boolean }): Promise<void> {
    const url = opts?.isCustom ? `${API_BASE_URL}/api/features/custom/${id}` : `${API_BASE_URL}/api/features/${id}`
    const response = await fetch(url, {
      method: 'DELETE',
      headers: { 'Content-Type': 'application/json' },
    })
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
    const data = await response.json()
    if (!data.success) throw new Error(data.message || 'Failed to delete feature')
  }

  async updateTemplate(id: string, templateData: Partial<DatabaseTemplate>): Promise<DatabaseTemplate> {
    try {
      const response = await fetch(`${API_BASE_URL}/api/templates/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(templateData),
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      
      if (!data.success) {
        throw new Error(data.message || 'Failed to update template')
      }

      return data.data
    } catch (error) {
      console.error('Update template error:', error)
      throw error
    }
  }

  async deleteTemplate(id: string): Promise<void> {
    try {
      const response = await fetch(`${API_BASE_URL}/api/templates/${id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
        },
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      
      if (!data.success) {
        throw new Error(data.message || 'Failed to delete template')
      }
    } catch (error) {
      console.error('Delete template error:', error)
      throw error
    }
  }
}

export const templateService = new TemplateService()
