// @ts-nocheck
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { FolderOpen, FileText, Clock, CheckCircle, Edit, Copy, Trash2 } from 'lucide-react'
import { useState } from 'react'
import LoadingSpinner from '@/components/common/LoadingSpinner'
import Button from '@/components/common/Button'
import Modal from '@/components/common/Modal'
import { useNavigate } from 'react-router-dom'
import { supabase } from '@/lib/supabase'
import { deleteDatabook } from '@/lib/mutations'
import { toast } from '@/lib/toast'
import { motion, AnimatePresence } from 'framer-motion'

// Função para obter cores do status
const getStatusColor = (status: string) => {
  switch (status) {
    case 'finalizado':
      return 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-400'
    case 'revisao':
      return 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-400'
    case 'arquivado':
      return 'bg-purple-100 dark:bg-purple-900/30 text-purple-800 dark:text-purple-400'
    case 'em_andamento':
      return 'bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-400'
    case 'cancelado':
      return 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-400'
    case 'rascunho':
    default:
      return 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-400'
  }
}

const getStatusLabel = (status: string) => {
  switch (status) {
    case 'rascunho': return 'Rascunho'
    case 'em_andamento': return 'Em Andamento'
    case 'finalizado': return 'Concluído'
    case 'revisao': return 'Em Revisão'
    case 'arquivado': return 'Arquivado'
    case 'cancelado': return 'Cancelado'
    default: return status
  }
}

export default function Dashboard() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [deleteModalOpen, setDeleteModalOpen] = useState(false)
  const [projetoToDelete, setProjetoToDelete] = useState<any>(null)
  
  const { data: projetos, isLoading } = useQuery({
    queryKey: ['projetos'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('projetos')
        .select('*, clientes(nome)')
        .order('created_at', { ascending: false })
        .limit(10)
      
      if (error) throw error
      
      const projetosComProgresso = await Promise.all(
        ((data as any) || []).map(async (projeto: any) => {
          const { count: totalTopicos } = await supabase
            .from('templates_topicos')
            .select('*', { count: 'exact' })
          
          const { data: documentos } = await supabase
            .from('documentos_auto_indexados')
            .select('secao_numero')
            .eq('databook_id',projeto.id)
          
          const secoesUnicas = new Set((documentos as any)?.map((d: any) => d.secao_numero).filter(Boolean))
          const secoesComDocs = secoesUnicas.size
          
          const progresso = (totalTopicos && totalTopicos > 0)
            ? Math.round((secoesComDocs / totalTopicos) * 100)
            : 0
          
          if (progresso !== projeto.progresso_percentual) {
            await (supabase.from('projetos') as any)
              .update({ progresso_percentual: progresso } as any)
              .eq('id', projeto.id)
          }
          
          return {
            ...projeto,
            progresso_percentual: progresso
          }
        })
      )
      
      return projetosComProgresso
    },
  })
  
  const { data: templates } = useQuery({
    queryKey: ['templates-count'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('templates_customizados')
        .select('id', { count: 'exact' })
        .eq('ativo', true)
      
      if (error) throw error
      return data
    },
  })
  
  const deleteMutation = useMutation({
    mutationFn: deleteDatabook,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['projetos'] })
      toast.success('Projeto deletado com sucesso')
      setDeleteModalOpen(false)
      setProjetoToDelete(null)
    },
    onError: () => {
      toast.error('Erro ao deletar projeto')
    },
  })
  
  const handleDelete = (projeto: any) => {
    setProjetoToDelete(projeto)
    setDeleteModalOpen(true)
  }
  
  const confirmDelete = () => {
    if (projetoToDelete) {
      deleteMutation.mutate(projetoToDelete.id)
    }
  }
  
  const handleEdit = (projeto: any) => {
    navigate(`/databook/${projeto.id}/editar`)
  }
  
  const handleClone = async (projeto: any) => {
    try {
      const { data: projetoCompleto } = await supabase
        .from('projetos')
        .select('*, databooks_mestres(*)')
        .eq('id', projeto.id)
        .single()
      
      if (!projetoCompleto) {
        toast.error('Projeto não encontrado')
        return
      }
      
      const { data: novoProjeto } = await (supabase.from('projetos') as any)
        .insert([{
          numero_projeto: `${projeto.numero_projeto}-COPIA`,
          nome_projeto: `${projeto.nome_projeto} (Cópia)`,
          cliente_id: projeto.cliente_id,
          template_id: projeto.template_id,
          status: 'rascunho',
          progresso_percentual: 0,
        } as any])
        .select()
        .single()
      
      if (novoProjeto && (projetoCompleto as any).databooks_mestres) {
        const databookMestre = (projetoCompleto as any).databooks_mestres
        await (supabase.from('databooks_mestres') as any)
          .insert([{
            projeto_id: novoProjeto.id,
            cliente_nome: databookMestre.cliente_nome,
            cliente_contato: databookMestre.cliente_contato,
            cliente_email: databookMestre.cliente_email,
            cliente_telefone: databookMestre.cliente_telefone,
            produto_nome: databookMestre.produto_nome,
            produto_tipo: databookMestre.produto_tipo,
            produto_descricao: databookMestre.produto_descricao,
            produto_normas: databookMestre.produto_normas,
            numero_projeto: `${databookMestre.numero_projeto}-COPIA`,
            ordem_compra: databookMestre.ordem_compra,
            cor_primaria: databookMestre.cor_primaria,
            cor_secundaria: databookMestre.cor_secundaria,
            titulo_principal: databookMestre.titulo_principal,
            subtitulo: databookMestre.subtitulo,
            tamanho_pagina: databookMestre.tamanho_pagina,
            orientacao: databookMestre.orientacao,
          } as any])
      }
      
      queryClient.invalidateQueries({ queryKey: ['projetos'] })
      toast.success('Projeto clonado com sucesso!')
    } catch (error) {
      toast.error('Erro ao clonar projeto')
    }
  }
  
  const stats = [
    {
      name: 'Total Projetos',
      value: projetos?.length || 0,
      icon: FolderOpen,
      color: 'bg-blue-600',
    },
    {
      name: 'Em Andamento',
      value: projetos?.filter((p: any) => p.status === 'em_andamento').length || 0,
      icon: Clock,
      color: 'bg-amber-500',
    },
    {
      name: 'Finalizados',
      value: projetos?.filter((p: any) => p.status === 'finalizado').length || 0,
      icon: CheckCircle,
      color: 'bg-emerald-500',
    },
    {
      name: 'Templates',
      value: (templates as any)?.length || 0,
      icon: FileText,
      color: 'bg-violet-600',
    },
  ]
  
  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">Dashboard</h1>
        <Button onClick={() => navigate('/databook/novo')} className="shadow-lg shadow-primary/20">
          Novo Databook
        </Button>
      </div>
      
      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {stats.map((stat, i) => (
          <motion.div 
            key={stat.name} 
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: i * 0.1 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 p-6 hover:shadow-md transition-shadow"
          >
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-500 dark:text-gray-400">{stat.name}</p>
                <p className="text-3xl font-bold text-gray-900 dark:text-gray-100 mt-2">{stat.value}</p>
              </div>
              <div className={`${stat.color} p-3 rounded-xl shadow-inner`}>
                <stat.icon className="text-white" size={24} />
              </div>
            </div>
          </motion.div>
        ))}
      </div>
      
      {/* Recent Projects */}
      <motion.div 
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.4 }}
        className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden"
      >
        <div className="p-6 border-b border-gray-100 dark:border-gray-700">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">Projetos Recentes</h2>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50/50 dark:bg-gray-900/50">
              <tr>
                <th className="px-6 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Projeto</th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Cliente</th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Status</th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Progresso</th>
                <th className="px-6 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Ações</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100 dark:divide-gray-700">
              <AnimatePresence>
                {projetos && projetos.length > 0 ? (
                  projetos.map((projeto: any, i) => (
                    <motion.tr 
                      key={projeto.id}
                      initial={{ opacity: 0, x: -10 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: 0.5 + (i * 0.05) }}
                      className="hover:bg-gray-50/50 dark:hover:bg-gray-700/50 transition-colors"
                    >
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm font-semibold text-gray-900 dark:text-gray-100">{projeto.nome_projeto}</div>
                        <div className="text-xs text-gray-500 dark:text-gray-400 font-mono mt-0.5">{projeto.numero_projeto}</div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                        {projeto.clientes?.nome || '-'}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`px-2.5 py-1 text-xs font-bold rounded-full uppercase tracking-wider ${getStatusColor(projeto.status)}`}>
                          {getStatusLabel(projeto.status)}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="flex items-center gap-3">
                          <div className="flex-1 bg-gray-100 dark:bg-gray-700 rounded-full h-2 min-w-[100px]">
                            <motion.div
                              initial={{ width: 0 }}
                              animate={{ width: `${projeto.progresso_percentual || 0}%` }}
                              className="bg-primary-600 h-full rounded-full shadow-sm"
                            ></motion.div>
                          </div>
                          <span className="text-xs font-bold text-gray-600 dark:text-gray-400">{projeto.progresso_percentual || 0}%</span>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm">
                        <div className="flex items-center gap-1">
                          {[
                            { icon: FileText, color: 'text-gray-600 hover:text-blue-600', onClick: () => navigate(`/databook/${projeto.id}`), title: 'Ver detalhes' },
                            { icon: Edit, color: 'text-gray-600 hover:text-blue-600', onClick: () => navigate(`/databook/${projeto.id}/editar`), title: 'Editar' },
                            { icon: Copy, color: 'text-gray-600 hover:text-emerald-600', onClick: () => handleClone(projeto), title: 'Clonar' },
                            { icon: Trash2, color: 'text-gray-600 hover:text-red-600', onClick: () => handleDelete(projeto), title: 'Deletar' },
                          ].map((action, actionIdx) => (
                            <button 
                              key={actionIdx}
                              onClick={action.onClick}
                              className={`${action.color} p-2 hover:bg-white dark:hover:bg-gray-600 rounded-lg transition-all border border-transparent hover:border-gray-200 dark:hover:border-gray-500 shadow-sm hover:shadow`}
                              title={action.title}
                            >
                              <action.icon size={16} />
                            </button>
                          ))}
                        </div>
                      </td>
                    </motion.tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={5} className="px-6 py-12 text-center text-gray-500 dark:text-gray-400 italic">
                      Nenhum projeto encontrado. Comece criando um novo databook.
                    </td>
                  </tr>
                )}
              </AnimatePresence>
            </tbody>
          </table>
        </div>
      </motion.div>
      
      {/* Modal de Confirmação de Exclusão */}
      <Modal
        isOpen={deleteModalOpen}
        onClose={() => setDeleteModalOpen(false)}
        title="Deletar Projeto"
      >
        <div className="space-y-4">
          <p className="text-gray-600 dark:text-gray-300">
            Tem certeza que deseja deletar o projeto <strong>{projetoToDelete?.nome_projeto}</strong>?
          </p>
          <div className="bg-red-50 dark:bg-red-900/20 p-3 rounded-lg border border-red-100 dark:border-red-900/30">
            <p className="text-sm text-red-700 dark:text-red-400 font-medium">
              Esta ação não pode ser desfeita e todos os dados relacionados serão perdidos permanentemente.
            </p>
          </div>
          <div className="flex justify-end gap-3 pt-4">
            <Button
              variant="outline"
              onClick={() => setDeleteModalOpen(false)}
            >
              Cancelar
            </Button>
            <Button
              variant="danger"
              onClick={confirmDelete}
              isLoading={deleteMutation.isPending}
              className="px-8 shadow-lg shadow-red-500/20"
            >
              Sim, Deletar
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}
