import { useState, useEffect } from 'react'
import { templateService, DatabaseTemplate, TemplatesByCategory, TemplateFeature } from '@/lib/template-service'

export function useTemplates() {
  const [templates, setTemplates] = useState<TemplatesByCategory>({})
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const fetchTemplates = async () => {
    try {
      setLoading(true)
      setError(null)
      const data = await templateService.getTemplatesByCategory()
      setTemplates(data)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch templates')
      console.error('Error fetching templates:', err)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchTemplates()
  }, [])

  const createTemplate = async (templateData: Partial<DatabaseTemplate>) => {
    try {
      const newTemplate = await templateService.createTemplate(templateData)
      // Refresh templates after creating a new one
      await fetchTemplates()
      return newTemplate
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create template')
      throw err
    }
  }

  const updateTemplate = async (id: string, templateData: Partial<DatabaseTemplate>) => {
    try {
      const updatedTemplate = await templateService.updateTemplate(id, templateData)
      // Refresh templates after updating
      await fetchTemplates()
      return updatedTemplate
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update template')
      throw err
    }
  }

  const deleteTemplate = async (id: string) => {
    try {
      await templateService.deleteTemplate(id)
      // Refresh templates after deleting
      await fetchTemplates()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to delete template')
      throw err
    }
  }

  // Convert database templates to the format expected by the UI
  const getTemplatesForUI = () => {
    const allTemplates: Array<DatabaseTemplate & {
      features: string[]
      complexity: number
      timeEstimate: string
      techStack: string[]
      popularity?: number
      lastUpdated?: string
    }> = []

    Object.entries(templates).forEach(([category, categoryTemplates]) => {
      categoryTemplates.forEach((template) => {
        // Convert database template to UI format
        const uiTemplate = {
          ...template,
          features: [], // Will be populated when template is selected
          complexity: 3, // Default complexity
          timeEstimate: "2-4 weeks", // Default time estimate
          techStack: ["Next.js", "PostgreSQL", "Tailwind CSS"], // Default tech stack
          popularity: template.avg_rating ? Math.round(template.avg_rating * 20) : 75, // Convert rating to popularity
          lastUpdated: template.updated_at ? new Date(template.updated_at).toISOString().split('T')[0] : undefined,
          featureCount: (template as any).feature_count ?? 0
        }
        allTemplates.push(uiTemplate)
      })
    })

    return allTemplates
  }

  // Get template features when a template is selected
  const getTemplateFeatures = async (templateId: string): Promise<string[]> => {
    try {
      const features = await templateService.getFeaturesForTemplate(templateId)
      return features.map(feature => feature.name)
    } catch (error) {
      console.error('Error fetching template features:', error)
      return []
    }
  }

  // Feature CRUD for a template
  const fetchFeatures = async (templateId: string): Promise<TemplateFeature[]> => {
    return templateService.getFeaturesForTemplate(templateId)
  }

  const createFeature = async (templateId: string, feature: Partial<TemplateFeature>) => {
    const payload = { ...feature, template_id: templateId }
    return templateService.createFeature(payload)
  }

  const updateFeature = async (featureId: string, updates: Partial<TemplateFeature>) => {
    // If updates indicate custom, route accordingly
    return templateService.updateFeature(featureId, updates)
  }

  const deleteFeature = async (featureId: string, opts?: { isCustom?: boolean }) => {
    return templateService.deleteFeature(featureId, opts)
  }

  return {
    templates,
    loading,
    error,
    fetchTemplates,
    createTemplate,
    updateTemplate,
    deleteTemplate,
    getTemplatesForUI,
    getTemplateFeatures,
    fetchFeatures,
    createFeature,
    updateFeature,
    deleteFeature
  }
}
