// @ts-nocheck
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { Palette, Check } from 'lucide-react'
import Button from '@/components/common/Button'
import Modal from '@/components/common/Modal'
import { supabase } from '@/lib/supabase'
import { toast } from '@/lib/toast'
import { useDesignTemplates } from '@/hooks/useDesignConfig'

interface DesignSelectorProps {
  databookId: string
  currentDesignConfig?: any
}

export default function DesignSelector({ databookId, currentDesignConfig }: DesignSelectorProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [selectedTemplates, setSelectedTemplates] = useState<{
    capa?: string
    indice?: string
    divisora?: string
    cabecalho?: string
    rodape?: string
    guia_estilo?: string
  }>({})
  
  const queryClient = useQueryClient()
  
  const { data: templatesCapa } = useDesignTemplates('capa')
  const { data: templatesIndice } = useDesignTemplates('indice')
  const { data: templatesDivisora } = useDesignTemplates('divisora')
  const { data: templatesCabecalho } = useDesignTemplates('cabecalho')
  const { data: templatesRodape } = useDesignTemplates('rodape')
  
  const applyDesignMutation = useMutation({
    mutationFn: async () => {
      // Verificar se já existe uma aplicação
      const { data: existing } = await supabase
        .from('databook_design_aplicacoes')
        .select('id')
        .eq('databook_id', databookId)
        .single()
      
      const aplicacao: any = {
        databook_id: databookId,
        template_capa_id: selectedTemplates.capa || null,
        template_indice_id: selectedTemplates.indice || null,
        template_divisora_id: selectedTemplates.divisora || null,
        template_cabecalho_id: selectedTemplates.cabecalho || null,
        template_rodape_id: selectedTemplates.rodape || null,
        template_guia_estilo_id: selectedTemplates.guia_estilo || null,
      }
      
      if (existing) {
        // Atualizar
        const { error } = await supabase
          .from('databook_design_aplicacoes')
          .update(aplicacao as any)
          .eq('id', (existing as any).id)
        
        if (error) throw error
      } else {
        // Inserir
        const { error } = await supabase
          .from('databook_design_aplicacoes')
          .insert(aplicacao)
        
        if (error) throw error
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['design-config', databookId] })
      toast.success('Design aplicado com sucesso!')
      setIsOpen(false)
    },
    onError: (error: any) => {
      toast.error(error.message || 'Erro ao aplicar design')
    },
  })
  
  const renderTemplateSelector = (
    title: string,
    tipo: string,
    templates: any[] | undefined
  ) => {
    return (
      <div className="mb-6">
        <h3 className="text-sm font-semibold text-gray-700 mb-3">{title}</h3>
        <div className="grid grid-cols-2 gap-3">
          {templates?.map((template) => {
            const isSelected = selectedTemplates[tipo as keyof typeof selectedTemplates] === template.id
            
            return (
              <button
                key={template.id}
                onClick={() => setSelectedTemplates(prev => ({ ...prev, [tipo]: template.id }))}
                className={`p-4 border-2 rounded-lg text-left transition-all ${
                  isSelected
                    ? 'border-primary bg-primary/5'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
              >
                <div className="flex items-start justify-between mb-2">
                  <h4 className="font-medium text-gray-900">{template.nome}</h4>
                  {isSelected && <Check size={20} className="text-primary" />}
                </div>
                {template.descricao && (
                  <p className="text-xs text-gray-600">{template.descricao}</p>
                )}
                
                {/* Preview de cores */}
                {template.config?.corPrimaria && (
                  <div className="flex gap-2 mt-3">
                    <div
                      className="w-6 h-6 rounded border border-gray-300"
                      style={{ backgroundColor: template.config.corPrimaria }}
                      title="Cor Primária"
                    />
                    {template.config?.corSecundaria && (
                      <div
                        className="w-6 h-6 rounded border border-gray-300"
                        style={{ backgroundColor: template.config.corSecundaria }}
                        title="Cor Secundária"
                      />
                    )}
                  </div>
                )}
              </button>
            )
          })}
          
          {(!templates || templates.length === 0) && (
            <div className="col-span-2 text-center py-8 text-gray-500">
              Nenhum template disponível
            </div>
          )}
        </div>
      </div>
    )
  }
  
  return (
    <>
      <Button
        variant="outline"
        onClick={() => setIsOpen(true)}
        size="sm"
      >
        <Palette size={16} className="mr-2" />
        {currentDesignConfig ? 'Alterar Design' : 'Aplicar Design'}
      </Button>
      
      <Modal
        isOpen={isOpen}
        onClose={() => setIsOpen(false)}
        title="Selecionar Templates de Design"
      >
        <div className="space-y-6 max-h-[70vh] overflow-y-auto">
          <p className="text-sm text-gray-600">
            Escolha os templates de design que serão aplicados ao gerar o PDF deste databook.
          </p>
          
          {renderTemplateSelector('Capa Frontal', 'capa', templatesCapa)}
          {renderTemplateSelector('Índice', 'indice', templatesIndice)}
          {renderTemplateSelector('Divisoras de Seção', 'divisora', templatesDivisora)}
          {renderTemplateSelector('Cabeçalho', 'cabecalho', templatesCabecalho)}
          {renderTemplateSelector('Rodapé', 'rodape', templatesRodape)}
          
          <div className="flex justify-end gap-3 pt-4 border-t">
            <Button
              variant="outline"
              onClick={() => setIsOpen(false)}
            >
              Cancelar
            </Button>
            <Button
              onClick={() => applyDesignMutation.mutate()}
              isLoading={applyDesignMutation.isPending}
              disabled={Object.keys(selectedTemplates).length === 0}
            >
              Aplicar Design
            </Button>
          </div>
        </div>
      </Modal>
    </>
  )
}

