import { useQuery } from '@tanstack/react-query'
import { supabase } from '@/lib/supabase'

interface DesignTemplate {
  id: string
  nome: string
  tipo: string
  config: any
}

export function useDesignConfig(databookId: string | undefined) {
  return useQuery({
    queryKey: ['design-config', databookId],
    queryFn: async () => {
      if (!databookId) return null
      
      // Buscar aplicação de design para este databook
      const { data: aplicacao, error: aplicacaoError } = await supabase
        .from('databook_design_aplicacoes')
        .select('*')
        .eq('databook_id', databookId)
        .single()
      
      if (aplicacaoError && aplicacaoError.code !== 'PGRST116') {
        throw aplicacaoError
      }
      
      if (!aplicacao) {
        return null
      }
      
      // Buscar todos os templates aplicados
      const templateIds = [
        (aplicacao as any).template_capa_id,
        (aplicacao as any).template_indice_id,
        (aplicacao as any).template_divisora_id,
        (aplicacao as any).template_cabecalho_id,
        (aplicacao as any).template_rodape_id,
        (aplicacao as any).template_guia_estilo_id
      ].filter(Boolean)
      
      if (templateIds.length === 0) {
        return null
      }
      
      const { data: templates, error: templatesError } = await supabase
        .from('design_templates')
        .select('*')
        .in('id', templateIds)
      
      if (templatesError) throw templatesError
      
      // Organizar templates por tipo
      const designConfig: any = {}
      
      templates?.forEach((template: DesignTemplate) => {
        designConfig[template.tipo] = template.config
      })
      
      return designConfig
    },
    enabled: !!databookId,
  })
}

export function useDesignTemplates(tipo?: string) {
  return useQuery({
    queryKey: ['design-templates', tipo],
    queryFn: async () => {
      let query = supabase
        .from('design_templates')
        .select('*')
        .eq('ativo', true)
        .order('criado_em', { ascending: false })
      
      if (tipo) {
        query = query.eq('tipo', tipo)
      }
      
      const { data, error } = await query
      
      if (error) throw error
      return data as DesignTemplate[]
    },
  })
}
