// @ts-nocheck
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Edit, Trash2, Eye, Download, Save, X } from 'lucide-react'
import Button from '@/components/common/Button'
import Input from '@/components/common/Input'
import Modal from '@/components/common/Modal'
import LoadingSpinner from '@/components/common/LoadingSpinner'
import { supabase } from '@/lib/supabase'
import { toast } from '@/lib/toast'
import TemplateEditor from '@/components/design/TemplateEditor'
import TemplatePreview from '@/components/design/TemplatePreview'

interface Template {
  id: string
  nome: string
  descricao: string
  tipo: 'capa' | 'indice' | 'divisora' | 'cabecalho' | 'rodape' | 'guia_estilo'
  config: Record<string, any>
  ativo: boolean
  criado_em: string
}

export default function DesignDatabook() {
  const queryClient = useQueryClient()
  const [modalOpen, setModalOpen] = useState(false)
  const [editingTemplate, setEditingTemplate] = useState<Template | null>(null)
  const [previewOpen, setPreviewOpen] = useState(false)
  const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(null)
  const [filterType, setFilterType] = useState<string>('all')

  const [formData, setFormData] = useState({
    nome: '',
    descricao: '',
    tipo: 'capa' as Template['tipo'],
    config: {} as Record<string, any>,
  })

  const { data: templates, isLoading } = useQuery({
    queryKey: ['design-templates'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('design_templates')
        .select('*')
        .order('criado_em', { ascending: false })

      if (error) throw error
      return data as Template[]
    },
  })

  const createMutation = useMutation({
    mutationFn: async (data: typeof formData) => {
      const { error } = await supabase
        .from('design_templates')
        .insert([data as any])

      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['design-templates'] })
      toast.success('Template criado com sucesso')
      setModalOpen(false)
      resetForm()
    },
  })

  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: string; data: typeof formData }) => {
      const { error } = await supabase
        .from('design_templates')
        .update(data as any)
        .eq('id', id)

      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['design-templates'] })
      toast.success('Template atualizado com sucesso')
      setModalOpen(false)
      setEditingTemplate(null)
      resetForm()
    },
  })

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase
        .from('design_templates')
        .delete()
        .eq('id', id)

      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['design-templates'] })
      toast.success('Template deletado com sucesso')
    },
  })

  const resetForm = () => {
    setFormData({
      nome: '',
      descricao: '',
      tipo: 'capa',
      config: {},
    })
  }

  const handleEdit = (template: Template) => {
    setEditingTemplate(template)
    setFormData({
      nome: template.nome,
      descricao: template.descricao,
      tipo: template.tipo,
      config: template.config,
    })
    setModalOpen(true)
  }

  const handleSave = () => {
    if (!formData.nome.trim()) {
      toast.error('Nome do template é obrigatório')
      return
    }

    if (editingTemplate) {
      updateMutation.mutate({ id: editingTemplate.id, data: formData })
    } else {
      createMutation.mutate(formData)
    }
  }

  const handlePreview = (template: Template) => {
    setSelectedTemplate(template)
    setPreviewOpen(true)
  }

  const filteredTemplates = templates?.filter(t => 
    filterType === 'all' ? true : t.tipo === filterType
  ) || []

  const typeLabels = {
    capa: '📄 Capa Frontal',
    indice: '📑 Índice Geral',
    divisora: '🔖 Divisora de Seção',
    cabecalho: '📋 Cabeçalho',
    rodape: '📋 Rodapé',
    guia_estilo: '🎨 Guia de Estilo',
  }

  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">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">Design do Databook</h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            Crie e personalize os templates visuais e estruturais do seu databook
          </p>
        </div>
        <Button onClick={() => {
          resetForm()
          setEditingTemplate(null)
          setModalOpen(true)
        }}>
          <Plus size={20} className="mr-2" />
          Novo Template
        </Button>
      </div>

      {/* Filtros */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
        <div className="flex gap-2 flex-wrap">
          <button
            onClick={() => setFilterType('all')}
            className={`px-4 py-2 rounded-lg transition-colors ${
              filterType === 'all'
                ? 'bg-primary dark:bg-blue-600 text-white'
                : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
            }`}
          >
            Todos
          </button>
          {Object.entries(typeLabels).map(([key, label]) => (
            <button
              key={key}
              onClick={() => setFilterType(key)}
              className={`px-4 py-2 rounded-lg transition-colors ${
                filterType === key
                  ? 'bg-primary dark:bg-blue-600 text-white'
                  : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
              }`}
            >
              {label}
            </button>
          ))}
        </div>
      </div>

      {/* Grid de Templates */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredTemplates.length > 0 ? (
          filteredTemplates.map((template) => (
            <div
              key={template.id}
              className="bg-white dark:bg-gray-800 rounded-lg shadow hover:shadow-lg transition-shadow overflow-hidden"
            >
              <div className="bg-gradient-to-r from-blue-500 via-blue-600 to-purple-600 dark:from-slate-700 dark:via-slate-800 dark:to-slate-900 h-32 flex items-center justify-center">
                <span className="text-6xl">
                  {typeLabels[template.tipo].split(' ')[0]}
                </span>
              </div>

              <div className="p-4">
                <h3 className="font-semibold text-gray-900 dark:text-gray-100 mb-1">{template.nome}</h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-3">{template.descricao}</p>
                <p className="text-xs text-gray-500 dark:text-gray-500 mb-4">
                  {typeLabels[template.tipo]}
                </p>

                <div className="flex gap-2">
                  <button
                    onClick={() => handlePreview(template)}
                    className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 rounded hover:bg-blue-100 dark:hover:bg-blue-900/50 transition-colors text-sm font-medium"
                  >
                    <Eye size={16} />
                    Preview
                  </button>
                  <button
                    onClick={() => handleEdit(template)}
                    className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-gray-50 dark:bg-gray-700 text-gray-600 dark:text-gray-300 rounded hover:bg-gray-100 dark:hover:bg-gray-600 transition-colors text-sm font-medium"
                  >
                    <Edit size={16} />
                    Editar
                  </button>
                  <button
                    onClick={() => deleteMutation.mutate(template.id)}
                    className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-red-50 dark:bg-red-900/30 text-red-600 dark:text-red-400 rounded hover:bg-red-100 dark:hover:bg-red-900/50 transition-colors text-sm font-medium"
                  >
                    <Trash2 size={16} />
                    Deletar
                  </button>
                </div>
              </div>
            </div>
          ))
        ) : (
          <div className="col-span-full text-center py-12">
            <p className="text-gray-500 text-lg">
              Nenhum template encontrado. Crie seu primeiro template!
            </p>
          </div>
        )}
      </div>

      {/* Modal de Criar/Editar */}
      <Modal
        isOpen={modalOpen}
        onClose={() => {
          setModalOpen(false)
          setEditingTemplate(null)
          resetForm()
        }}
        title={editingTemplate ? 'Editar Template' : 'Novo Template'}
      >
        <div className="space-y-4">
          <Input
            label="Nome do Template"
            value={formData.nome}
            onChange={(e) => setFormData(prev => ({ ...prev, nome: e.target.value }))}
            placeholder="Ex: Capa Frontal Padrão"
            required
          />

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Descrição
            </label>
            <textarea
              value={formData.descricao}
              onChange={(e) => setFormData(prev => ({ ...prev, descricao: e.target.value }))}
              placeholder="Descrição do template..."
              className="input-field"
              rows={3}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Tipo de Template
            </label>
            <select
              value={formData.tipo}
              onChange={(e) => setFormData(prev => ({ ...prev, tipo: e.target.value as Template['tipo'] }))}
              className="input-field"
            >
              <option value="capa">Capa Frontal</option>
              <option value="indice">Índice Geral</option>
              <option value="divisora">Divisora de Seção</option>
              <option value="cabecalho">Cabeçalho</option>
              <option value="rodape">Rodapé</option>
              <option value="guia_estilo">Guia de Estilo</option>
            </select>
          </div>

          <TemplateEditor
            tipo={formData.tipo}
            config={formData.config}
            onChange={(config) => setFormData(prev => ({ ...prev, config }))}
          />

          <div className="flex justify-end gap-3 pt-4">
            <Button
              variant="outline"
              onClick={() => {
                setModalOpen(false)
                setEditingTemplate(null)
                resetForm()
              }}
            >
              Cancelar
            </Button>
            <Button
              onClick={handleSave}
              isLoading={createMutation.isPending || updateMutation.isPending}
            >
              <Save size={18} className="mr-2" />
              {editingTemplate ? 'Atualizar' : 'Criar'}
            </Button>
          </div>
        </div>
      </Modal>

      {/* Modal de Preview */}
      <div className="fixed inset-0 z-50" style={{ display: previewOpen ? 'flex' : 'none', alignItems: 'center', justifyContent: 'center' }}>
        {/* Backdrop */}
        <div
          className="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
          onClick={() => setPreviewOpen(false)}
        />
        
        {/* Modal - 56% da tela (70% - 20%), 90% altura (85% + 20% ajustado) */}
        <div className="relative bg-white dark:bg-gray-900 rounded-lg shadow-xl w-full flex flex-col" style={{ maxWidth: '56vw', maxHeight: '90vh' }}>
          {/* Header com Botões */}
          <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
            <h3 className="text-lg font-semibold text-gray-900">{selectedTemplate?.nome || 'Preview'}</h3>
            <div className="flex items-center gap-3">
              <Button
                variant="outline"
                onClick={() => setPreviewOpen(false)}
                className="text-sm"
              >
                Fechar
              </Button>
              <Button className="text-sm">
                <Download size={16} className="mr-2" />
                Exportar
              </Button>
              <button
                onClick={() => setPreviewOpen(false)}
                className="text-gray-400 hover:text-gray-600 transition-colors"
              >
                <X size={20} />
              </button>
            </div>
          </div>
          
          {/* Content - Scroll apenas do preview */}
          <div className="flex-1 overflow-hidden p-4">
            {selectedTemplate && (
              <TemplatePreview
                tipo={selectedTemplate.tipo}
                config={selectedTemplate.config}
              />
            )}
          </div>
        </div>
      </div>
    </div>
  )
}


