import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { FileText, Plus, Edit, Copy, Trash2 } from 'lucide-react'
import { useState } from 'react'
import Button from '@/components/common/Button'
import LoadingSpinner from '@/components/common/LoadingSpinner'
import Modal from '@/components/common/Modal'
import { supabase } from '@/lib/supabase'
import { deleteTemplate, createTemplate } from '@/lib/mutations'
import { toast } from '@/lib/toast'

export default function Templates() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [deleteModalOpen, setDeleteModalOpen] = useState(false)
  const [templateToDelete, setTemplateToDelete] = useState<any>(null)
  
  const { data: allTemplates, isLoading } = useQuery({
    queryKey: ['templates'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('templates_customizados')
        .select('*')
        .eq('ativo', true)
        .order('created_at', { ascending: false })
      
      if (error) throw error
      return data as any[]
    },
  })
  
  // Separar templates pré-definidos (tipo 'padrao') dos customizados
  const templatesPadrao = allTemplates?.filter(t => t.tipo === 'padrao') || []
  const templates = allTemplates?.filter(t => t.tipo !== 'padrao') || []
  
  const deleteMutation = useMutation({
    mutationFn: deleteTemplate,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['templates'] })
      toast.success('Template deletado com sucesso')
      setDeleteModalOpen(false)
      setTemplateToDelete(null)
    },
    onError: () => {
      toast.error('Erro ao deletar template')
    },
  })
  
  const cloneMutation = useMutation({
    mutationFn: createTemplate,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['templates'] })
      toast.success('Template clonado com sucesso')
    },
    onError: () => {
      toast.error('Erro ao clonar template')
    },
  })
  
  const handleDelete = (template: any) => {
    setTemplateToDelete(template)
    setDeleteModalOpen(true)
  }
  
  const confirmDelete = () => {
    if (templateToDelete) {
      deleteMutation.mutate(templateToDelete.id)
    }
  }
  
  const handleClone = async (template: any) => {
    await cloneMutation.mutateAsync({
      nome: `${template.nome} (Cópia)`,
      tipo: template.tipo,
      template_pai_id: template.id,
      topicos_selecionados: template.topicos_selecionados,
      descricao: template.descricao,
    })
  }
  
  const handleEdit = (template: any) => {
    navigate(`/templates/${template.id}/editar`)
  }
  
  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-full">
        <LoadingSpinner size="lg" />
      </div>
    )
  }
  
  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">Templates</h1>
        <Button onClick={() => navigate('/templates/criar')}>
          <Plus size={20} className="mr-2" />
          Novo Template
        </Button>
      </div>
      
      {/* Templates Pré-definidos */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">Templates Pré-definidos</h2>
          <Button 
            size="sm" 
            variant="outline"
            onClick={() => navigate('/templates/criar')}
          >
            <Plus size={16} className="mr-1" />
            Adicionar Template Padrão
          </Button>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {templatesPadrao.length > 0 ? (
            templatesPadrao.map((template) => (
              <div key={template.id} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:border-primary transition-colors bg-white dark:bg-gray-900">
                <div className="flex items-start justify-between mb-3">
                  <div className="bg-primary-100 dark:bg-blue-900/30 p-2 rounded-lg">
                    <FileText className="text-primary dark:text-blue-400" size={24} />
                  </div>
                  <div className="flex gap-1">
                    <button
                      onClick={() => handleEdit(template)}
                      className="text-blue-600 hover:text-blue-800 p-1 hover:bg-blue-50 rounded transition-colors"
                      title="Editar"
                    >
                      <Edit size={16} />
                    </button>
                    <button
                      onClick={() => handleClone(template)}
                      className="text-green-600 hover:text-green-800 p-1 hover:bg-green-50 rounded transition-colors"
                      title="Clonar"
                    >
                      <Copy size={16} />
                    </button>
                    <button
                      onClick={() => handleDelete(template)}
                      className="text-red-600 hover:text-red-800 p-1 hover:bg-red-50 rounded transition-colors"
                      title="Deletar"
                    >
                      <Trash2 size={16} />
                    </button>
                  </div>
                </div>
                <h3 className="font-semibold text-gray-900 dark:text-gray-100 mb-1">{template.nome}</h3>
                {template.descricao && (
                  <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">{template.descricao}</p>
                )}
                <p className="text-xs text-gray-500 dark:text-gray-500">
                  {template.total_topicos || template.topicos_selecionados?.length || 0} seções
                </p>
              </div>
            ))
          ) : (
            <div className="col-span-3 text-center py-8 text-gray-500 dark:text-gray-400">
              Nenhum template padrão cadastrado. Crie templates padrão para facilitar a criação de novos projetos.
            </div>
          )}
        </div>
      </div>
      
      {/* Meus Templates */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow">
        <div className="p-6 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">Meus Templates</h2>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 dark:bg-gray-900">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Nome
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Tipo
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Seções
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Criado em
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Ações
                </th>
              </tr>
            </thead>
            <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              {templates && templates.length > 0 ? (
                templates.map((template) => (
                  <tr key={template.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm font-medium text-gray-900 dark:text-gray-100">{template.nome}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className="px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800">
                        {template.tipo}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                      {template.total_topicos} / 28
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                      {new Date(template.created_at).toLocaleDateString('pt-BR')}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm">
                      <div className="flex items-center gap-2">
                        <button 
                          onClick={() => handleEdit(template)}
                          className="text-blue-600 hover:text-blue-800 p-1 hover:bg-blue-50 rounded transition-colors"
                          title="Editar"
                        >
                          <Edit size={18} />
                        </button>
                        <button 
                          onClick={() => handleClone(template)}
                          className="text-green-600 hover:text-green-800 p-1 hover:bg-green-50 rounded transition-colors"
                          title="Clonar"
                          disabled={cloneMutation.isPending}
                        >
                          <Copy size={18} />
                        </button>
                        <button 
                          onClick={() => handleDelete(template)}
                          className="text-red-600 hover:text-red-800 p-1 hover:bg-red-50 rounded transition-colors"
                          title="Deletar"
                        >
                          <Trash2 size={18} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={5} className="px-6 py-12 text-center text-gray-500 dark:text-gray-400">
                    Nenhum template customizado. Crie seu primeiro template!
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
      
      {/* Modal de Confirmação de Inativação */}
      <Modal
        isOpen={deleteModalOpen}
        onClose={() => setDeleteModalOpen(false)}
        title="Inativar Template"
      >
        <div className="space-y-4">
          <p className="text-gray-600 dark:text-gray-400">
            Tem certeza que deseja inativar o template <strong>{templateToDelete?.nome}</strong>?
          </p>
          <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
            <p className="text-sm text-blue-800 dark:text-blue-200">
              <strong>Importante:</strong> O template será ocultado e não aparecerá mais na criação de novos databooks, 
              mas continuará disponível para todos os databooks existentes que já o utilizam.
            </p>
          </div>
          <p className="text-sm text-gray-500 dark:text-gray-500">
            Você poderá reativar este template posteriormente se necessário.
          </p>
          <div className="flex justify-end gap-3">
            <Button
              variant="outline"
              onClick={() => setDeleteModalOpen(false)}
            >
              Cancelar
            </Button>
            <Button
              variant="primary"
              onClick={confirmDelete}
              isLoading={deleteMutation.isPending}
              className="bg-orange-600 hover:bg-orange-700"
            >
              Inativar
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}
