// @ts-nocheck
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Edit, Trash2, Tag } from 'lucide-react'
import Button from '@/components/common/Button'
import Input from '@/components/common/Input'
import Modal from '@/components/common/Modal'
import { supabase } from '@/lib/supabase'
import { toast } from '@/lib/toast'

interface Categoria {
  id: string
  nome: string
  descricao: string
  cor: string
  ativo: boolean
}

export default function CategoriasTab() {
  const queryClient = useQueryClient()
  const [modalOpen, setModalOpen] = useState(false)
  const [editingCategoria, setEditingCategoria] = useState<Categoria | null>(null)
  const [formData, setFormData] = useState({
    nome: '',
    descricao: '',
    cor: '#3B82F6',
  })
  
  const { data: categorias } = useQuery({
    queryKey: ['categorias'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('categorias')
        .select('*')
        .eq('ativo', true)
        .order('nome', { ascending: true })
      
      if (error) throw error
      return data as Categoria[]
    },
  })
  
  const createMutation = useMutation({
    mutationFn: async (data: typeof formData) => {
      const { error } = await supabase
        .from('categorias')
        .insert([{ ...data, ativo: true } as any])
      
      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['categorias'] })
      toast.success('Categoria criada')
      setModalOpen(false)
      resetForm()
    },
  })
  
  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: string; data: typeof formData }) => {
      const { error } = await supabase
        .from('categorias')
        .update(data as any)
        .eq('id', id)
      
      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['categorias'] })
      toast.success('Categoria atualizada')
      setModalOpen(false)
      setEditingCategoria(null)
      resetForm()
    },
  })
  
  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase
        .from('categorias')
        .update({ ativo: false } as any)
        .eq('id', id)
      
      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['categorias'] })
      toast.success('Categoria removida')
    },
  })
  
  const resetForm = () => {
    setFormData({
      nome: '',
      descricao: '',
      cor: '#3B82F6',
    })
  }
  
  const handleEdit = (categoria: Categoria) => {
    setEditingCategoria(categoria)
    setFormData({
      nome: categoria.nome,
      descricao: categoria.descricao || '',
      cor: categoria.cor,
    })
    setModalOpen(true)
  }
  
  const handleSave = () => {
    if (editingCategoria) {
      updateMutation.mutate({ id: editingCategoria.id, data: formData })
    } else {
      createMutation.mutate(formData)
    }
  }
  
  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">Categorias</h2>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Gerencie as categorias para organizar tópicos e documentos
          </p>
        </div>
        <Button onClick={() => {
          resetForm()
          setEditingCategoria(null)
          setModalOpen(true)
        }}>
          <Plus size={20} className="mr-2" />
          Nova Categoria
        </Button>
      </div>
      
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {categorias && categorias.length > 0 ? (
          categorias.map((categoria) => (
            <div key={categoria.id} className="bg-white dark:bg-gray-800 rounded-lg shadow p-4 border-l-4" style={{ borderColor: categoria.cor }}>
              <div className="flex items-start justify-between mb-3">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-lg" style={{ backgroundColor: `${categoria.cor}20` }}>
                    <Tag size={20} style={{ color: categoria.cor }} />
                  </div>
                  <div>
                    <h3 className="font-semibold text-gray-900 dark:text-gray-100">{categoria.nome}</h3>
                    {categoria.descricao && (
                      <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">{categoria.descricao}</p>
                    )}
                  </div>
                </div>
              </div>
              <div className="flex gap-2 mt-4">
                <button
                  onClick={() => handleEdit(categoria)}
                  className="flex-1 text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900 py-2 rounded transition-colors text-sm"
                >
                  <Edit size={14} className="inline mr-1" />
                  Editar
                </button>
                <button
                  onClick={() => deleteMutation.mutate(categoria.id)}
                  className="flex-1 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900 py-2 rounded transition-colors text-sm"
                >
                  <Trash2 size={14} className="inline mr-1" />
                  Remover
                </button>
              </div>
            </div>
          ))
        ) : (
          <div className="col-span-3 text-center py-12 text-gray-500 dark:text-gray-400">
            Nenhuma categoria cadastrada
          </div>
        )}
      </div>
      
      <Modal
        isOpen={modalOpen}
        onClose={() => {
          setModalOpen(false)
          setEditingCategoria(null)
          resetForm()
        }}
        title={editingCategoria ? 'Editar Categoria' : 'Nova Categoria'}
      >
        <div className="space-y-4">
          <Input
            label="Nome"
            value={formData.nome}
            onChange={(e) => setFormData(prev => ({ ...prev, nome: e.target.value }))}
            placeholder="Ex: Certificados"
            required
          />
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Descrição
            </label>
            <textarea
              value={formData.descricao}
              onChange={(e) => setFormData(prev => ({ ...prev, descricao: e.target.value }))}
              placeholder="Descrição opcional..."
              className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100"
              rows={3}
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Cor
            </label>
            <div className="flex gap-2">
              <input
                type="color"
                value={formData.cor}
                onChange={(e) => setFormData(prev => ({ ...prev, cor: e.target.value }))}
                className="h-10 w-20 rounded cursor-pointer"
              />
              <input
                type="text"
                value={formData.cor}
                onChange={(e) => setFormData(prev => ({ ...prev, cor: e.target.value }))}
                className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100 flex-1"
                placeholder="#3B82F6"
              />
            </div>
          </div>
          
          <div className="flex justify-end gap-3 pt-4">
            <Button
              variant="outline"
              onClick={() => {
                setModalOpen(false)
                setEditingCategoria(null)
                resetForm()
              }}
            >
              Cancelar
            </Button>
            <Button
              onClick={handleSave}
              isLoading={createMutation.isPending || updateMutation.isPending}
            >
              {editingCategoria ? 'Atualizar' : 'Criar'}
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}


