'use client';

import React from 'react';
import { Send, RefreshCw, ChevronDown, CheckCircle2, XCircle, Loader2, Users, BookUser } from 'lucide-react';
import { motion } from 'framer-motion';
import { format } from 'date-fns';
import { ptBR } from 'date-fns/locale';
import { useSendingLogic } from '../../hooks/useSendingLogic';
import PageHeader from '../../components/ui/PageHeader';
import Button from '../../components/ui/Button';
import Badge from '../../components/ui/Badge';
import Toast from '../../components/ui/Toast';
import ContactPickerModal from '../../components/ContactPickerModal';
import type { BroadcastJob } from '../../hooks/useSendingLogic';

// ─── Job status helpers ───────────────────────────────────────────────────────

function jobBadge(status: BroadcastJob['status']) {
  if (status === 'DONE') return <Badge variant="success" dot>Concluído</Badge>
  if (status === 'FAILED') return <Badge variant="error" dot>Falhou</Badge>
  return <Badge variant="warning" dot>Enviando…</Badge>
}

function progressPct(job: BroadcastJob) {
  if (job.totalCount === 0) return 0
  return Math.round(((job.sentCount + job.failedCount) / job.totalCount) * 100)
}

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

export default function SendingPage() {
  const {
    connectedInstances,
    activeInstance,
    activeInstanceId,
    selectInstance,

    numbersRaw,
    setNumbersRaw,
    message,
    setMessage,
    delayMs,
    setDelayMs,
    parsedNumbers,

    jobs,
    jobsLoading,
    loadJobs,

    submitting,
    handleSubmit,

    toast,

    isPickerOpen,
    setIsPickerOpen,
    addContactsToNumbers,
  } = useSendingLogic()

  const [showInstanceMenu, setShowInstanceMenu] = React.useState(false)
  const menuRef = React.useRef<HTMLDivElement>(null)

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

  return (
    <div className="flex-1 overflow-y-auto p-6 md:p-10">
      <PageHeader
        icon={Send}
        title="Disparo"
        titleAccent=" em Massa"
        subtitle="Envie mensagens para múltiplos contatos"
      />

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
        {/* ── Form ──────────────────────────────────────────────────────────── */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.35 }}
          className="glass rounded-2xl p-6 border border-white/5 space-y-5"
        >
          <h2 className="text-white font-bold text-base flex items-center gap-2">
            <Send className="w-4 h-4 text-brand-400" />
            Novo Disparo
          </h2>

          {/* Instance selector */}
          <div>
            <label className="block text-xs text-slate-400 uppercase tracking-widest mb-1.5">
              Instância conectada
            </label>
            <div className="relative" ref={menuRef}>
              <button
                type="button"
                onClick={() => setShowInstanceMenu(!showInstanceMenu)}
                className="w-full flex items-center justify-between gap-2 bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white hover:bg-white/10 transition-colors"
              >
                <span className={activeInstance ? 'text-white' : 'text-slate-500'}>
                  {activeInstance?.name ?? 'Selecione uma instância…'}
                </span>
                <ChevronDown className={`w-4 h-4 text-slate-400 transition-transform ${showInstanceMenu ? 'rotate-180' : ''}`} />
              </button>

              {showInstanceMenu && (
                <div className="absolute z-20 top-full mt-1 w-full bg-[#1a1f2e] border border-white/10 rounded-xl shadow-2xl overflow-hidden">
                  {connectedInstances.length === 0 ? (
                    <p className="px-4 py-3 text-sm text-slate-500">Nenhuma instância conectada.</p>
                  ) : (
                    connectedInstances.map((i) => (
                      <button
                        key={i.id}
                        type="button"
                        onClick={() => { selectInstance(i.id); setShowInstanceMenu(false) }}
                        className={`w-full text-left px-4 py-2.5 text-sm hover:bg-white/5 transition-colors flex items-center gap-2 ${i.id === activeInstanceId ? 'text-brand-400' : 'text-white'}`}
                      >
                        <span className="w-2 h-2 rounded-full bg-emerald-400" />
                        {i.name}
                        {i.phone && <span className="text-slate-500 text-xs ml-auto">{i.phone}</span>}
                      </button>
                    ))
                  )}
                </div>
              )}
            </div>
          </div>

          {/* Numbers textarea */}
          <div>
            <div className="flex items-center justify-between mb-1.5">
              <label className="text-xs text-slate-400 uppercase tracking-widest">
                Números
                {parsedNumbers.length > 0 && (
                  <span className="ml-2 text-brand-400 normal-case font-bold">
                    {parsedNumbers.length} {parsedNumbers.length === 1 ? 'número' : 'números'} detectados
                  </span>
                )}
              </label>
              <button
                type="button"
                onClick={() => setIsPickerOpen(true)}
                disabled={!activeInstanceId}
                className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-medium bg-brand-500/15 hover:bg-brand-500/25 text-brand-400 hover:text-brand-300 border border-brand-500/20 transition-all disabled:opacity-40 disabled:cursor-not-allowed"
              >
                <BookUser className="w-3.5 h-3.5" />
                Selecionar da Agenda
              </button>
            </div>
            <textarea
              value={numbersRaw}
              onChange={(e) => setNumbersRaw(e.target.value)}
              placeholder={'5511999999999\n5521888888888\n...'}
              rows={8}
              className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm text-white placeholder-slate-500 resize-none focus:outline-none focus:border-brand-500/50 focus:ring-1 focus:ring-brand-500/30 transition-colors"
            />
            <p className="text-xs text-slate-500 mt-1">
              Um número por linha, ou separados por vírgula / ponto-e-vírgula. Apenas dígitos (DDI+DDD+número).
            </p>
          </div>

          {/* Message */}
          <div>
            <label className="block text-xs text-slate-400 uppercase tracking-widest mb-1.5">
              Mensagem
            </label>
            <textarea
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              placeholder="Digite a mensagem que será enviada para todos os contatos…"
              rows={5}
              maxLength={4096}
              className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm text-white placeholder-slate-500 resize-none focus:outline-none focus:border-brand-500/50 focus:ring-1 focus:ring-brand-500/30 transition-colors"
            />
            <p className="text-xs text-slate-500 mt-1 text-right">{message.length}/4096</p>
          </div>

          {/* Delay slider */}
          <div>
            <label className="block text-xs text-slate-400 uppercase tracking-widest mb-1.5">
              Intervalo entre envios —{' '}
              <span className="text-brand-400 font-bold">
                {delayMs >= 1000 ? `${(delayMs / 1000).toFixed(1)}s` : `${delayMs}ms`}
              </span>
            </label>
            <input
              type="range"
              min={500}
              max={30000}
              step={500}
              value={delayMs}
              onChange={(e) => setDelayMs(Number(e.target.value))}
              className="w-full accent-brand-500"
            />
            <div className="flex justify-between text-xs text-slate-500 mt-1">
              <span>0.5s (rápido)</span>
              <span>30s (seguro)</span>
            </div>
          </div>

          {/* Submit */}
          <Button
            variant="primary"
            size="lg"
            loading={submitting}
            icon={<Send className="w-4 h-4" />}
            onClick={handleSubmit}
            disabled={submitting || parsedNumbers.length === 0 || !message.trim() || !activeInstanceId}
            className="w-full"
          >
            {submitting ? 'Enviando…' : `Disparar para ${parsedNumbers.length || '—'} contatos`}
          </Button>
        </motion.div>

        {/* ── Jobs list ─────────────────────────────────────────────────────── */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.35, delay: 0.1 }}
          className="space-y-4"
        >
          <div className="flex items-center justify-between">
            <h2 className="text-white font-bold text-base flex items-center gap-2">
              <Users className="w-4 h-4 text-brand-400" />
              Histórico de Disparos
            </h2>
            <Button
              variant="ghost"
              size="sm"
              icon={<RefreshCw className={`w-3.5 h-3.5 ${jobsLoading ? 'animate-spin' : ''}`} />}
              onClick={loadJobs}
              disabled={jobsLoading}
            >
              Atualizar
            </Button>
          </div>

          {jobsLoading && jobs.length === 0 ? (
            <div className="glass rounded-2xl p-10 border border-white/5 flex items-center justify-center">
              <Loader2 className="w-6 h-6 text-brand-400 animate-spin" />
            </div>
          ) : jobs.length === 0 ? (
            <div className="glass rounded-2xl p-10 border border-white/5 flex flex-col items-center justify-center text-center gap-3">
              <Send className="w-10 h-10 text-slate-600" />
              <p className="text-slate-500 text-sm">Nenhum disparo realizado ainda.</p>
            </div>
          ) : (
            <div className="space-y-3">
              {jobs.map((job) => {
                const pct = progressPct(job)
                return (
                  <div key={job.id} className="glass rounded-2xl p-5 border border-white/5 space-y-3">
                    {/* Header row */}
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex-1 min-w-0">
                        <p className="text-white text-sm font-medium truncate">{job.message}</p>
                        <p className="text-slate-500 text-xs mt-0.5">
                          {format(new Date(job.createdAt), "dd/MM/yyyy 'às' HH:mm", { locale: ptBR })}
                        </p>
                      </div>
                      {jobBadge(job.status as BroadcastJob['status'])}
                    </div>

                    {/* Progress bar */}
                    <div>
                      <div className="flex justify-between text-xs text-slate-500 mb-1">
                        <span>{job.sentCount + job.failedCount} / {job.totalCount} processados</span>
                        <span>{pct}%</span>
                      </div>
                      <div className="h-1.5 bg-white/5 rounded-full overflow-hidden">
                        <div
                          className={`h-full rounded-full transition-all duration-500 ${
                            job.status === 'FAILED' ? 'bg-red-500' :
                            job.status === 'DONE' ? 'bg-emerald-500' : 'bg-brand-500'
                          }`}
                          style={{ width: `${pct}%` }}
                        />
                      </div>
                    </div>

                    {/* Stats row */}
                    <div className="flex gap-4 text-xs">
                      <span className="flex items-center gap-1 text-emerald-400">
                        <CheckCircle2 className="w-3.5 h-3.5" />
                        {job.sentCount} enviados
                      </span>
                      {job.failedCount > 0 && (
                        <span className="flex items-center gap-1 text-red-400">
                          <XCircle className="w-3.5 h-3.5" />
                          {job.failedCount} falhas
                        </span>
                      )}
                      <span className="text-slate-500 ml-auto">
                        {job.totalCount} total
                      </span>
                    </div>
                  </div>
                )
              })}
            </div>
          )}
        </motion.div>
      </div>

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

      <ContactPickerModal
        open={isPickerOpen}
        instanceId={activeInstanceId}
        onConfirm={addContactsToNumbers}
        onClose={() => setIsPickerOpen(false)}
      />
    </div>
  )
}
