import React, { useState, useRef, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { formatDistanceToNow } from 'date-fns'
import { ptBR } from 'date-fns/locale'
import {
  LayoutDashboard,
  MessageSquare,
  Inbox,
  Zap,
  Users,
  Activity,
  Smartphone,
  TrendingUp,
  Wifi,
  WifiOff,
  ChevronDown,
  Check,
  Phone,
  RefreshCw,
  FileText,
  User,
} from 'lucide-react'
import { PageHeader, StatCard, Card, Button, Badge } from '@/components/ui'
import { useDashboardLogic, type Period } from '../../hooks/useDashboardLogic'
import { getAvatarProxyUrl, formatPhone } from '../../utils/inboxUtils'
import type { Instance } from '../../store/instanceStore'
import type { Chat } from '../../store/chatStore'

const PERIOD_LABELS: Record<Period, string> = { hoje: 'Hoje', '7d': '7 Dias', '30d': '30 Dias' }

const STATUS_META: Record<Instance['status'], { label: string; dot: string; text: string }> = {
  CONNECTED:    { label: 'Conectado',    dot: 'bg-green-400',  text: 'text-green-400' },
  CONNECTING:   { label: 'Conectando',   dot: 'bg-yellow-400', text: 'text-yellow-400' },
  QR_PENDING:   { label: 'QR Pendente',  dot: 'bg-orange-400', text: 'text-orange-400' },
  DISCONNECTED: { label: 'Desconectado', dot: 'bg-slate-500',  text: 'text-slate-500' },
  BANNED:       { label: 'Banido',       dot: 'bg-red-500',    text: 'text-red-400' },
}

// ─── Dropdown de Sessão ───────────────────────────────────────────────────────

function SessionDropdown({
  instances, activeInstance, onSelect,
}: {
  instances: Instance[]
  activeInstance: Instance | null
  onSelect: (id: string) => void
}) {
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const h = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)
    }
    document.addEventListener('mousedown', h)
    return () => document.removeEventListener('mousedown', h)
  }, [])

  const meta = activeInstance ? STATUS_META[activeInstance.status] : null
  const isConnected = activeInstance?.status === 'CONNECTED'

  return (
    <div className="relative" ref={ref}>
      <button
        onClick={() => setOpen((o) => !o)}
        className={`flex items-center gap-3 px-4 py-2.5 rounded-2xl border transition-all
          ${open
            ? 'bg-white/10 border-brand-500/40 shadow-[0_0_0_1px_rgba(59,130,246,0.2)]'
            : 'bg-white/[0.04] border-white/10 hover:bg-white/[0.07] hover:border-white/20'}`}
      >
        <div className={`relative w-8 h-8 rounded-xl overflow-hidden shrink-0
          ${isConnected ? 'ring-2 ring-green-400/60 ring-offset-1 ring-offset-[#080a0e]' : ''}`}>
          {activeInstance?.avatar
            ? <img src={activeInstance.avatar} alt="" className="w-full h-full object-cover" />
            : <div className="w-full h-full bg-brand-500/20 flex items-center justify-center">
                <Smartphone size={14} className="text-brand-400" />
              </div>}
          {meta && <span className={`absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full border-2 border-[#080a0e] ${meta.dot}`} />}
        </div>
        <div className="text-left min-w-0">
          <p className="text-sm font-bold text-white truncate max-w-[140px]">
            {activeInstance?.name ?? 'Selecionar sessão'}
          </p>
          {activeInstance && (
            <p className={`text-[11px] font-medium ${meta?.text ?? 'text-slate-500'}`}>
              {isConnected && activeInstance.phone ? activeInstance.phone : meta?.label}
            </p>
          )}
        </div>
        <ChevronDown size={15} className={`text-slate-400 shrink-0 transition-transform duration-200 ${open ? 'rotate-180' : ''}`} />
      </button>

      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: -8, scale: 0.97 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -8, scale: 0.97 }}
            transition={{ duration: 0.15 }}
            className="absolute right-0 top-full mt-2 w-72 bg-[#0f1117] border border-white/10 rounded-2xl shadow-2xl z-50 overflow-hidden"
          >
            <div className="px-4 pt-3 pb-2">
              <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Sessões</p>
            </div>
            <div className="max-h-72 overflow-y-auto pb-2">
              {instances.length === 0
                ? <p className="text-xs text-slate-600 text-center py-6">Nenhuma instância criada</p>
                : instances.map((inst) => {
                    const m = STATUS_META[inst.status]
                    const isActive = inst.id === activeInstance?.id
                    const conn = inst.status === 'CONNECTED'
                    return (
                      <button key={inst.id} onClick={() => { onSelect(inst.id); setOpen(false) }}
                        className={`w-full flex items-center gap-3 px-4 py-3 transition-colors text-left
                          ${isActive ? 'bg-brand-500/10' : 'hover:bg-white/[0.04]'}`}>
                        <div className={`relative w-9 h-9 rounded-xl overflow-hidden shrink-0
                          ${conn ? 'ring-2 ring-green-400/50 ring-offset-1 ring-offset-[#0f1117]' : ''}`}>
                          {inst.avatar
                            ? <img src={inst.avatar} alt="" className="w-full h-full object-cover" />
                            : <div className="w-full h-full bg-white/5 flex items-center justify-center">
                                <Smartphone size={15} className="text-slate-500" />
                              </div>}
                          <span className={`absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full border-2 border-[#0f1117] ${m.dot}`} />
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className={`text-sm font-semibold truncate ${isActive ? 'text-brand-300' : 'text-white'}`}>{inst.name}</p>
                          <div className="flex items-center gap-1.5 mt-0.5">
                            {conn && inst.phone
                              ? <><Phone size={10} className="text-slate-500 shrink-0" /><span className="text-[11px] text-slate-500 font-mono truncate">{inst.phone}</span></>
                              : <span className={`text-[11px] font-medium ${m.text}`}>{m.label}</span>}
                          </div>
                        </div>
                        {isActive && <Check size={15} className="text-brand-400 shrink-0" />}
                      </button>
                    )
                  })}
            </div>
            <div className="px-4 py-3 border-t border-white/5">
              <a href="/sessions" className="block text-center text-xs font-bold text-slate-500 hover:text-brand-400 transition-colors">
                Gerenciar sessões →
              </a>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}

// ─── Chat recente ─────────────────────────────────────────────────────────────

function RecentChatRow({ chat, activeInstanceId }: { chat: Chat; activeInstanceId: string | null }) {
  const isGroup = chat.jid?.endsWith('@g.us')
  const displayName = chat.contactName ?? chat.name ?? (chat.contactPhone ? formatPhone(chat.contactPhone) : null) ?? 'Contato'
  const lastMsg = chat.lastMessageBody
  const time = chat.lastMessageAt
    ? formatDistanceToNow(new Date(chat.lastMessageAt), { addSuffix: true, locale: ptBR })
    : null

  const avatarUrl = activeInstanceId
    ? getAvatarProxyUrl({ instance_name: activeInstanceId, remote_jid: chat.jid })
    : null

  return (
    <a href="/inbox" className="py-3.5 px-3 flex items-center gap-3 hover:bg-white/[0.03] rounded-xl transition-all duration-200 cursor-pointer group">
      {/* Avatar */}
      <div className="relative w-10 h-10 rounded-full bg-slate-800 border border-white/10 overflow-hidden shrink-0">
        {avatarUrl
          ? <img src={avatarUrl} alt="" className="w-full h-full object-cover"
              onError={(e) => { (e.currentTarget as HTMLImageElement).style.display = 'none' }} />
          : <div className="w-full h-full flex items-center justify-center">
              {isGroup
                ? <Users size={16} className="text-slate-500" />
                : <User size={16} className="text-slate-500" />}
            </div>}
        {chat.unreadCount > 0 && (
          <span className="absolute -top-0.5 -right-0.5 min-w-[18px] h-[18px] px-1 bg-brand-500 text-white text-[10px] font-black rounded-full flex items-center justify-center">
            {chat.unreadCount > 99 ? '99+' : chat.unreadCount}
          </span>
        )}
      </div>

      {/* Info */}
      <div className="flex-1 min-w-0">
        <div className="flex items-center justify-between gap-2">
          <p className="text-sm font-bold text-white group-hover:text-brand-300 transition-colors truncate">{displayName}</p>
          {time && <span className="text-[10px] text-slate-600 shrink-0">{time}</span>}
        </div>
        {lastMsg && (
          <p className="text-xs text-slate-500 truncate mt-0.5">
            {chat.lastMessageFromMe && <span className="text-brand-500/70 font-medium mr-1">Você:</span>}
            {lastMsg}
          </p>
        )}
      </div>
    </a>
  )
}

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

export default function DashboardPage() {
  const {
    period, setPeriod,
    statsLoading,
    stats,
    recentChats,
    instances, instLoading,
    activeInstance, activeId,
    selectInstance,
    connectedCount,
    refetch,
  } = useDashboardLogic()

  const statsCards = [
    {
      label: 'Conversas',
      value: statsLoading ? '—' : (stats?.totalChats?.toLocaleString('pt-BR') ?? '—'),
      icon: MessageSquare, color: 'text-brand-400', bg: 'bg-brand-500/10',
    },
    {
      label: 'Não lidas',
      value: statsLoading ? '—' : (stats?.totalUnread?.toLocaleString('pt-BR') ?? '—'),
      icon: Inbox, color: 'text-yellow-400', bg: 'bg-yellow-500/10',
    },
    {
      label: 'Protocolos abertos',
      value: statsLoading ? '—' : (stats?.openProtocols?.toLocaleString('pt-BR') ?? '—'),
      icon: FileText, color: 'text-purple-400', bg: 'bg-purple-500/10',
    },
    {
      label: 'Sessões ativas',
      value: instLoading ? '—' : connectedCount.toString(),
      icon: Zap, color: 'text-green-400', bg: 'bg-green-500/10',
    },
  ]

  return (
    <div className="min-h-screen bg-surface p-6 lg:p-10 font-sans">
      <PageHeader
        icon={LayoutDashboard}
        title="Dashboard"
        subtitle="Resumo operacional da sua conta"
        actions={
          <div className="flex items-center gap-3">
            <SessionDropdown instances={instances} activeInstance={activeInstance} onSelect={selectInstance} />

            <button
              onClick={refetch}
              title="Atualizar"
              className="p-2.5 rounded-xl bg-white/5 border border-white/10 hover:border-brand-500/30 hover:text-brand-400 text-slate-400 transition-all"
            >
              <RefreshCw size={15} className={statsLoading ? 'animate-spin' : ''} />
            </button>

            <Card variant="glass" padding="p-1.5" className="flex items-center gap-1">
              {(['hoje', '7d', '30d'] as Period[]).map((p) => (
                <Button key={p} variant={period === p ? 'primary' : 'ghost'} size="sm"
                  className="uppercase tracking-wider" onClick={() => setPeriod(p)}>
                  {PERIOD_LABELS[p]}
                </Button>
              ))}
            </Card>
          </div>
        }
      />

      {/* Stats reais */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-10">
        {statsCards.map((stat, i) => (
          <StatCard
            key={i}
            icon={stat.icon}
            label={stat.label}
            value={stat.value}
            color={stat.color}
            bg={stat.bg}
            loading={statsLoading || instLoading}
            delay={i * 0.08}
          />
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
        {/* Main */}
        <div className="lg:col-span-8 flex flex-col gap-6">
          <Card variant="glass" padding="p-6" className="rounded-3xl relative overflow-hidden h-[320px]">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-white font-black text-lg flex items-center gap-2">
                <Activity size={20} className="text-brand-500" />
                Fluxo de Mensagens
              </h2>
            </div>
            <div className="w-full h-full flex flex-col items-center justify-center border-t border-white/5 pt-8 relative">
              <div className="absolute inset-0 bg-gradient-to-br from-brand-500/5 via-transparent to-blue-500/5 rounded-2xl" />
              <TrendingUp size={40} className="text-white/10 mb-3 relative" />
              <p className="text-slate-600 text-xs font-bold uppercase tracking-wider relative">Gráficos em breve</p>
            </div>
          </Card>

          {/* Conversas recentes — dados reais */}
          <Card variant="glass" padding="p-6" className="rounded-3xl">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-white font-black text-lg flex items-center gap-2">
                <MessageSquare size={20} className="text-brand-500" />
                Conversas Recentes
              </h2>
              <a href="/inbox" className="text-xs font-bold text-slate-500 hover:text-brand-400 transition-colors">
                Ver todas →
              </a>
            </div>

            {statsLoading ? (
              <div className="space-y-2">
                {[1, 2, 3, 4, 5].map(i => (
                  <div key={i} className="h-14 rounded-xl bg-white/5 animate-pulse" />
                ))}
              </div>
            ) : recentChats.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-12 gap-3">
                <MessageSquare size={32} className="text-white/10" />
                <p className="text-xs text-slate-600 text-center">
                  {activeInstance
                    ? 'Nenhuma conversa ainda nesta sessão.'
                    : 'Selecione uma sessão para ver as conversas.'}
                </p>
              </div>
            ) : (
              <div className="divide-y divide-white/[0.04]">
                {recentChats.map((chat) => (
                  <RecentChatRow key={chat.id} chat={chat} activeInstanceId={activeId} />
                ))}
              </div>
            )}
          </Card>
        </div>

        {/* Side */}
        <div className="lg:col-span-4 flex flex-col gap-6">
          {/* Card sessão ativa */}
          {activeInstance ? (
            <motion.div
              key={activeInstance.id}
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              className={`rounded-3xl p-5 border relative overflow-hidden ${
                activeInstance.status === 'CONNECTED'
                  ? 'bg-gradient-to-br from-green-900/40 to-emerald-900/20 border-green-500/20'
                  : 'bg-gradient-to-br from-slate-900/60 to-slate-800/20 border-white/10'}`}
            >
              <div className="flex items-center gap-4">
                <div className={`w-14 h-14 rounded-2xl overflow-hidden shrink-0 ${
                  activeInstance.status === 'CONNECTED' ? 'ring-2 ring-green-400/60 ring-offset-2 ring-offset-[#080a0e]' : ''}`}>
                  {activeInstance.avatar
                    ? <img src={activeInstance.avatar} alt="" className="w-full h-full object-cover" />
                    : <div className="w-full h-full bg-white/5 flex items-center justify-center">
                        <Smartphone size={22} className="text-slate-400" />
                      </div>}
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-white font-black text-base truncate">{activeInstance.name}</p>
                  {activeInstance.phone && (
                    <div className="flex items-center gap-1.5 mt-0.5">
                      <Phone size={11} className="text-slate-400 shrink-0" />
                      <p className="text-xs text-slate-400 font-mono">{activeInstance.phone}</p>
                    </div>
                  )}
                  <div className="flex items-center gap-1.5 mt-1.5">
                    <span className={`w-2 h-2 rounded-full ${STATUS_META[activeInstance.status].dot}
                      ${activeInstance.status === 'CONNECTED' ? 'shadow-[0_0_6px_rgba(74,222,128,0.8)]' : ''}`} />
                    <span className={`text-xs font-bold ${STATUS_META[activeInstance.status].text}`}>
                      {STATUS_META[activeInstance.status].label}
                    </span>
                  </div>
                </div>
              </div>
            </motion.div>
          ) : instLoading ? (
            <div className="h-24 rounded-3xl bg-white/5 animate-pulse" />
          ) : null}

          <div className="bg-gradient-to-br from-brand-600 to-blue-700 rounded-3xl p-6 text-white shadow-premium relative overflow-hidden group shimmer-line">
            <Zap size={120} className="absolute -right-8 -bottom-8 opacity-10 group-hover:scale-110 transition-transform duration-500" />
            <h2 className="text-xl font-black mb-2">Plano ProAtivo</h2>
            <p className="text-white/80 text-sm leading-relaxed mb-6">Seu limite de disparos está em 80% este mês. Recomendamos upgrade para evitar bloqueios.</p>
            <Button variant="secondary" size="lg" className="w-full bg-white text-brand-600 border-0 font-black hover:bg-slate-100 uppercase tracking-widest text-xs">
              Aumentar Limite
            </Button>
          </div>

          {/* Todas as sessões */}
          <Card variant="glass" padding="p-5" className="rounded-3xl flex-1">
            <div className="flex items-center gap-2 mb-4">
              <Smartphone size={15} className="text-slate-400" />
              <h2 className="text-white font-black text-sm">Todas as Sessões</h2>
            </div>
            <div className="space-y-2">
              {instLoading ? (
                [1, 2, 3].map(i => <div key={i} className="h-12 rounded-xl bg-white/5 animate-pulse" />)
              ) : instances.length === 0 ? (
                <p className="text-xs text-slate-600 text-center py-4">
                  Nenhuma instância. <a href="/sessions" className="text-brand-400 hover:underline">Adicionar</a>
                </p>
              ) : (
                instances.map((inst) => {
                  const m = STATUS_META[inst.status]
                  const isActive = inst.id === activeId
                  const conn = inst.status === 'CONNECTED'
                  return (
                    <motion.button key={inst.id} onClick={() => selectInstance(inst.id)}
                      initial={{ opacity: 0, y: 4 }} animate={{ opacity: 1, y: 0 }}
                      className={`w-full p-3 rounded-xl flex items-center gap-3 transition-all text-left ${
                        isActive
                          ? 'bg-brand-500/10 border border-brand-500/20'
                          : 'bg-black/20 border border-white/5 hover:border-white/15 hover:bg-white/[0.04]'}`}
                    >
                      <div className={`relative w-8 h-8 rounded-lg overflow-hidden shrink-0 ${conn ? 'ring-1 ring-green-400/50' : ''}`}>
                        {inst.avatar
                          ? <img src={inst.avatar} alt="" className="w-full h-full object-cover" />
                          : <div className="w-full h-full bg-white/5 flex items-center justify-center">
                              <Smartphone size={12} className="text-slate-500" />
                            </div>}
                        <span className={`absolute bottom-0 right-0 w-2 h-2 rounded-full border border-[#080a0e] ${m.dot}`} />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className={`text-xs font-bold truncate ${isActive ? 'text-brand-300' : 'text-slate-300'}`}>{inst.name}</p>
                        <p className={`text-[10px] font-mono truncate ${conn ? 'text-slate-500' : m.text}`}>
                          {conn && inst.phone ? inst.phone : m.label}
                        </p>
                      </div>
                      {conn ? <Wifi size={13} className="text-green-400 shrink-0" /> : <WifiOff size={13} className="text-slate-600 shrink-0" />}
                    </motion.button>
                  )
                })
              )}
            </div>
          </Card>
        </div>
      </div>
    </div>
  )
}
