'use client';

import React from 'react';
import {
  Users, Search, RefreshCw, Ban, Check,
  Pencil, Trash2, ChevronLeft, ChevronRight,
  MessageSquarePlus, ShieldAlert, Loader2,
} from 'lucide-react';
import { getAvatarProxyUrl } from '../../utils/inboxUtils';
import { motion, AnimatePresence } from 'framer-motion';
import { format } from 'date-fns';
import { ptBR } from 'date-fns/locale';
import { useRouter } from 'next/router';
import { usePhonebookLogic } from '../../hooks/usePhonebookLogic';
import { PageHeader, StatCard, Button, Badge, Toast } from '@/components/ui';
import type { BackendContact } from '../../services/chatApiService';

// ─── Avatar ───────────────────────────────────────────────────────────────────

function ContactAvatar({ contact, name, instanceId }: { contact: BackendContact; name: string; instanceId: string | null }) {
  const initials = name.slice(0, 2).toUpperCase()
  // Só pede o proxy se o banco já confirmou que existe avatar — evita um GET
  // por contato sem foto, cada um custando prisma.findFirst + 204 no backend.
  const proxyUrl = contact.avatarUrl
    ? getAvatarProxyUrl({ instance_name: instanceId, remote_jid: contact.jid })
    : null
  const [imgFailed, setImgFailed] = React.useState(false)
  React.useEffect(() => { setImgFailed(false) }, [proxyUrl])

  if (proxyUrl && !imgFailed) {
    return (
      <img
        src={proxyUrl}
        alt={name}
        loading="lazy"
        decoding="async"
        className="w-9 h-9 rounded-full object-cover"
        onError={() => setImgFailed(true)}
      />
    )
  }
  return (
    <div className="w-9 h-9 rounded-full bg-brand-500/20 flex items-center justify-center text-brand-300 text-xs font-bold">
      {initials}
    </div>
  )
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function PhonebookPage() {
  const router = useRouter()
  const {
    contacts, total, stats, loading,
    activeInstanceId,
    search, setSearch,
    blockedFilter, setBlockedFilter,
    currentPage, totalPages, goToPage,
    handleToggleBlock, handleDelete, refresh,
    openEdit, closeEdit, saveEdit,
    editingContact, editName, setEditName, editSaving,
    toast,
    displayName,
  } = usePhonebookLogic()

  const [confirmDelete, setConfirmDelete] = React.useState<string | null>(null)

  return (
    <div className="flex-1 overflow-y-auto p-6 md:p-10">
      <PageHeader
        icon={Users}
        title="Phonebook"
        subtitle="Contatos sincronizados pelo WhatsApp"
        actions={
          <Button
            variant="ghost"
            size="sm"
            icon={<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />}
            onClick={refresh}
            disabled={loading}
          >
            Atualizar
          </Button>
        }
      />

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        <StatCard label="Total" value={stats.total.toLocaleString('pt-BR')} icon={Users} color="text-brand-400" bg="bg-brand-500/10" />
        <StatCard label="Ativos" value={stats.active.toLocaleString('pt-BR')} icon={Check} color="text-emerald-400" bg="bg-emerald-500/10" />
        <StatCard label="Bloqueados" value={stats.blocked.toLocaleString('pt-BR')} icon={Ban} color="text-red-400" bg="bg-red-500/10" />
        <StatCard label="Restritos" value={stats.flagged.toLocaleString('pt-BR')} icon={ShieldAlert} color="text-amber-400" bg="bg-amber-500/10" />
      </div>

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-3 mb-6">
        <div className="relative flex-1 min-w-[200px] max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" />
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Nome, telefone ou JID…"
            className="w-full bg-white/5 border border-white/10 rounded-xl pl-9 pr-4 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-brand-500/50 focus:ring-1 focus:ring-brand-500/30 transition-colors"
          />
        </div>

        <div className="flex gap-1.5">
          {(['all', 'active', 'blocked'] as const).map((f) => (
            <button
              key={f}
              onClick={() => setBlockedFilter(f)}
              className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${
                blockedFilter === f ? 'bg-brand-500 text-white' : 'bg-white/5 text-slate-400 hover:bg-white/10'
              }`}
            >
              {f === 'all' ? 'Todos' : f === 'active' ? 'Ativos' : 'Bloqueados'}
            </button>
          ))}
        </div>

        <span className="text-slate-500 text-xs ml-auto">{total.toLocaleString('pt-BR')} contatos</span>
      </div>

      {/* Table */}
      <div className="glass rounded-2xl border border-white/5 overflow-hidden">
        {loading && contacts.length === 0 ? (
          <div className="flex items-center justify-center py-20">
            <Loader2 className="w-6 h-6 text-brand-400 animate-spin" />
          </div>
        ) : contacts.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 gap-3">
            <Users className="w-10 h-10 text-slate-600" />
            <p className="text-slate-500 text-sm">Nenhum contato encontrado.</p>
            {total === 0 && (
              <p className="text-slate-600 text-xs">Conecte uma instância para sincronizar contatos via WhatsApp.</p>
            )}
          </div>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-white/5 text-left">
                <th className="px-4 py-3 text-xs text-slate-500 font-bold uppercase tracking-widest">Contato</th>
                <th className="px-4 py-3 text-xs text-slate-500 font-bold uppercase tracking-widest hidden md:table-cell">Telefone</th>
                <th className="px-4 py-3 text-xs text-slate-500 font-bold uppercase tracking-widest hidden lg:table-cell">JID</th>
                <th className="px-4 py-3 text-xs text-slate-500 font-bold uppercase tracking-widest hidden xl:table-cell">Atualizado</th>
                <th className="px-4 py-3 text-xs text-slate-500 font-bold uppercase tracking-widest text-right">Status</th>
                <th className="px-4 py-3 text-xs text-slate-500 font-bold uppercase tracking-widest text-right">Ações</th>
              </tr>
            </thead>
            <tbody>
              {contacts.map((contact, i) => {
                const name = displayName(contact)
                return (
                  <motion.tr
                    key={contact.id}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: i * 0.015 }}
                    className="border-b border-white/5 last:border-0 hover:bg-white/[0.03] transition-colors group"
                  >
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-3">
                        <ContactAvatar contact={contact} name={name} instanceId={activeInstanceId ?? null} />
                        <div>
                          <p className="text-white font-medium">{name}</p>
                          {contact.verifiedName && contact.verifiedName !== contact.name && (
                            <p className="text-xs text-slate-500">{contact.verifiedName}</p>
                          )}
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-slate-400 hidden md:table-cell">{contact.phone ?? '—'}</td>
                    <td className="px-4 py-3 text-slate-500 text-xs font-mono hidden lg:table-cell">{contact.jid}</td>
                    <td className="px-4 py-3 text-slate-500 text-xs hidden xl:table-cell">
                      {format(new Date(contact.updatedAt), 'dd/MM/yy HH:mm', { locale: ptBR })}
                    </td>
                    <td className="px-4 py-3 text-right">
                      {contact.isBlocked ? (
                        <Badge variant="error">Bloqueado</Badge>
                      ) : contact.flagRestricao ? (
                        <Badge variant="warning">Restrito</Badge>
                      ) : (
                        <Badge variant="success">Ativo</Badge>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button
                          title="Enviar mensagem"
                          onClick={() => router.push('/inbox')}
                          className="p-1.5 rounded-lg text-slate-400 hover:text-brand-400 hover:bg-brand-500/10 transition-colors"
                        >
                          <MessageSquarePlus className="w-3.5 h-3.5" />
                        </button>
                        <button
                          title="Editar nome"
                          onClick={() => openEdit(contact)}
                          className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-white/10 transition-colors"
                        >
                          <Pencil className="w-3.5 h-3.5" />
                        </button>
                        <button
                          title={contact.isBlocked ? 'Desbloquear' : 'Bloquear'}
                          onClick={() => handleToggleBlock(contact)}
                          className={`p-1.5 rounded-lg transition-colors ${
                            contact.isBlocked
                              ? 'text-emerald-400 hover:bg-emerald-500/10'
                              : 'text-slate-400 hover:text-red-400 hover:bg-red-500/10'
                          }`}
                        >
                          {contact.isBlocked ? <Check className="w-3.5 h-3.5" /> : <Ban className="w-3.5 h-3.5" />}
                        </button>
                        <button
                          title="Remover"
                          onClick={() => setConfirmDelete(contact.id)}
                          className="p-1.5 rounded-lg text-slate-400 hover:text-red-400 hover:bg-red-500/10 transition-colors"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                        </button>
                      </div>
                    </td>
                  </motion.tr>
                )
              })}
            </tbody>
          </table>
        )}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-3 mt-6">
          <button
            onClick={() => goToPage(currentPage - 1)}
            disabled={currentPage === 0}
            className="p-2 rounded-lg bg-white/5 text-slate-400 hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed"
          >
            <ChevronLeft className="w-4 h-4" />
          </button>
          <span className="text-sm text-slate-400">{currentPage + 1} / {totalPages}</span>
          <button
            onClick={() => goToPage(currentPage + 1)}
            disabled={currentPage >= totalPages - 1}
            className="p-2 rounded-lg bg-white/5 text-slate-400 hover:bg-white/10 disabled:opacity-30 disabled:cursor-not-allowed"
          >
            <ChevronRight className="w-4 h-4" />
          </button>
        </div>
      )}

      {/* Edit modal */}
      <AnimatePresence>
        {editingContact && (
          <motion.div
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
            onClick={closeEdit}
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.95, opacity: 0 }}
              onClick={(e) => e.stopPropagation()}
              className="glass rounded-2xl border border-white/10 p-6 w-full max-w-sm space-y-4"
            >
              <h3 className="text-white font-bold text-base">Editar contato</h3>
              <div>
                <label className="block text-xs text-slate-400 uppercase tracking-widest mb-1.5">Nome</label>
                <input
                  type="text"
                  value={editName}
                  onChange={(e) => setEditName(e.target.value)}
                  placeholder={displayName(editingContact)}
                  autoFocus
                  onKeyDown={(e) => { if (e.key === 'Enter') saveEdit() }}
                  className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-brand-500/50 transition-colors"
                />
                <p className="text-xs text-slate-500 mt-1">
                  Nome original: {editingContact.verifiedName ?? editingContact.notify ?? '—'}
                </p>
              </div>
              <div className="flex gap-2">
                <Button variant="secondary" size="sm" onClick={closeEdit} className="flex-1">Cancelar</Button>
                <Button variant="primary" size="sm" loading={editSaving} onClick={saveEdit} className="flex-1">Salvar</Button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Confirm delete */}
      <AnimatePresence>
        {confirmDelete && (
          <motion.div
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
            onClick={() => setConfirmDelete(null)}
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.95, opacity: 0 }}
              onClick={(e) => e.stopPropagation()}
              className="glass rounded-2xl border border-white/10 p-6 w-full max-w-sm space-y-4"
            >
              <h3 className="text-white font-bold text-base">Remover contato?</h3>
              <p className="text-slate-400 text-sm">
                O contato será removido do sistema. Chats e mensagens não serão afetados.
              </p>
              <div className="flex gap-2">
                <Button variant="secondary" size="sm" onClick={() => setConfirmDelete(null)} className="flex-1">Cancelar</Button>
                <Button
                  variant="danger"
                  size="sm"
                  onClick={() => { handleDelete(confirmDelete); setConfirmDelete(null) }}
                  className="flex-1"
                >
                  Remover
                </Button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      <Toast message={toast?.message ?? ''} type={toast?.type ?? 'success'} visible={!!toast} />
    </div>
  )
}
