import React, { useState } from 'react'
import {
  Flame, Power, Settings2, X, Plus, Trash2,
  Smartphone, MessageSquare,
  AlertCircle,
} from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import { useWarmerLogic, type WarmerConfig } from '../../hooks/useWarmerLogic'
import { PageHeader, Card, Button, Badge, Toast } from '@/components/ui'

// ─── Status dot ──────────────────────────────────────────────────────────────

function StatusDot({ status }: { status: string }) {
  const connected = status === 'CONNECTED'
  return (
    <span className={`inline-block w-2 h-2 rounded-full ${connected ? 'bg-green-400' : 'bg-slate-600'}`} />
  )
}

// ─── Slider ───────────────────────────────────────────────────────────────────

function LabeledSlider({
  label, value, min, max, step = 1, format, onChange,
}: {
  label: string; value: number; min: number; max: number; step?: number
  format?: (v: number) => string; onChange: (v: number) => void
}) {
  const display = format ? format(value) : String(value)
  return (
    <div>
      <div className="flex items-center justify-between mb-1">
        <span className="text-xs text-slate-400">{label}</span>
        <span className="text-xs font-mono text-brand-400">{display}</span>
      </div>
      <input
        type="range" min={min} max={max} step={step} value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        className="w-full accent-brand-500 h-1.5 cursor-pointer"
      />
    </div>
  )
}

// ─── Edit Modal ───────────────────────────────────────────────────────────────

function EditModal({
  instanceName, draft, onClose, onSave,
  onAdd, onRemove, onPatch,
}: {
  instanceName: string
  draft: WarmerConfig
  onClose: () => void
  onSave: () => void
  onAdd: (t: string) => void
  onRemove: (i: number) => void
  onPatch: <K extends keyof WarmerConfig>(k: K, v: WarmerConfig[K]) => void
}) {
  const [newTemplate, setNewTemplate] = useState('')

  const fmtSec = (s: number) =>
    s < 60 ? `${s}s` : `${Math.floor(s / 60)}min ${s % 60 > 0 ? (s % 60) + 's' : ''}`.trim()

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.95 }}
        className="bg-[#13131a] border border-white/10 rounded-3xl w-full max-w-lg shadow-2xl overflow-hidden"
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-white/5">
          <div className="flex items-center gap-2">
            <Settings2 className="w-4 h-4 text-brand-400" />
            <span className="font-bold text-white text-sm">{instanceName}</span>
          </div>
          <button onClick={onClose} className="p-1.5 rounded-full hover:bg-white/5 text-slate-400">
            <X className="w-4 h-4" />
          </button>
        </div>

        <div className="p-6 space-y-6 max-h-[70vh] overflow-y-auto">
          {/* Volume */}
          <div className="space-y-4">
            <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider">Volume Diário</h3>
            <LabeledSlider
              label="Mensagens por dia"
              value={draft.messagesPerDay} min={1} max={200}
              onChange={(v) => onPatch('messagesPerDay', v)}
            />
          </div>

          {/* Intervalo */}
          <div className="space-y-4">
            <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider">Intervalo Entre Envios</h3>
            <LabeledSlider
              label="Mínimo"
              value={draft.minIntervalSec} min={30} max={3600} step={30}
              format={fmtSec}
              onChange={(v) => onPatch('minIntervalSec', Math.min(v, draft.maxIntervalSec))}
            />
            <LabeledSlider
              label="Máximo"
              value={draft.maxIntervalSec} min={30} max={3600} step={30}
              format={fmtSec}
              onChange={(v) => onPatch('maxIntervalSec', Math.max(v, draft.minIntervalSec))}
            />
          </div>

          {/* Templates */}
          <div className="space-y-3">
            <h3 className="text-xs font-bold text-slate-400 uppercase tracking-wider">Modelos de Mensagem</h3>
            <div className="space-y-2">
              {draft.templates.map((t, i) => (
                <div key={i} className="flex items-center gap-2 bg-white/5 rounded-xl px-3 py-2">
                  <MessageSquare className="w-3.5 h-3.5 text-slate-500 flex-shrink-0" />
                  <span className="text-sm text-slate-300 flex-1 truncate">{t}</span>
                  <button onClick={() => onRemove(i)} className="text-slate-500 hover:text-red-400 transition-colors">
                    <Trash2 className="w-3.5 h-3.5" />
                  </button>
                </div>
              ))}
            </div>
            <div className="flex gap-2">
              <input
                type="text" placeholder="Nova mensagem..."
                value={newTemplate} onChange={(e) => setNewTemplate(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') { onAdd(newTemplate); setNewTemplate('') } }}
                className="flex-1 bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white placeholder-slate-600 focus:outline-none focus:border-brand-500/50"
              />
              <button
                onClick={() => { onAdd(newTemplate); setNewTemplate('') }}
                className="p-2 bg-brand-500/20 hover:bg-brand-500/30 border border-brand-500/30 rounded-xl text-brand-400 transition-colors"
              >
                <Plus className="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="px-6 py-4 border-t border-white/5 flex justify-end gap-3">
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <Button variant="primary" onClick={onSave}>Salvar</Button>
        </div>
      </motion.div>
    </div>
  )
}

// ─── Instance Card ────────────────────────────────────────────────────────────

function WarmerCard({
  inst, onToggle, onEdit,
}: {
  inst: ReturnType<typeof useWarmerLogic>['instances'][0]
  onToggle: () => void
  onEdit: () => void
}) {
  const isConnected = inst.status === 'CONNECTED'
  const { warmer } = inst

  const fmtSec = (s: number) =>
    s < 60 ? `${s}s` : `${Math.floor(s / 60)}m`

  return (
    <Card variant="glass" padding="p-5" className="rounded-2xl flex flex-col gap-4">
      {/* Top row */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-full bg-white/5 border border-white/10 flex items-center justify-center">
            <Smartphone className="w-4 h-4 text-slate-400" />
          </div>
          <div>
            <p className="text-sm font-bold text-white leading-tight">{inst.name}</p>
            <div className="flex items-center gap-1.5 mt-0.5">
              <StatusDot status={inst.status} />
              <span className="text-[11px] text-slate-500">
                {isConnected ? inst.phone ?? 'Conectado' : inst.status.toLowerCase()}
              </span>
            </div>
          </div>
        </div>

        {/* Toggle */}
        <button
          onClick={onToggle}
          disabled={!isConnected}
          title={!isConnected ? 'Instância precisa estar conectada' : undefined}
          className={`relative w-11 h-6 rounded-full transition-colors duration-200 focus:outline-none
            ${warmer.enabled ? 'bg-orange-500' : 'bg-white/10'}
            ${!isConnected ? 'opacity-40 cursor-not-allowed' : 'cursor-pointer'}`}
        >
          <span className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform duration-200
            ${warmer.enabled ? 'translate-x-5' : 'translate-x-0'}`} />
        </button>
      </div>

      {/* Stats row */}
      <div className="grid grid-cols-3 gap-2 text-center">
        <div className="bg-white/[0.03] rounded-xl py-2">
          <p className="text-base font-black text-white">{warmer.messagesPerDay}</p>
          <p className="text-[10px] text-slate-500 mt-0.5">msg/dia</p>
        </div>
        <div className="bg-white/[0.03] rounded-xl py-2">
          <p className="text-base font-black text-white">{fmtSec(warmer.minIntervalSec)}–{fmtSec(warmer.maxIntervalSec)}</p>
          <p className="text-[10px] text-slate-500 mt-0.5">intervalo</p>
        </div>
        <div className="bg-white/[0.03] rounded-xl py-2">
          <p className="text-base font-black text-white">{warmer.templates.length}</p>
          <p className="text-[10px] text-slate-500 mt-0.5">modelos</p>
        </div>
      </div>

      {/* Status / footer */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-1.5">
          {warmer.enabled ? (
            <>
              <Flame className="w-3.5 h-3.5 text-orange-400 animate-pulse" />
              <span className="text-[11px] text-orange-300">Aquecendo</span>
            </>
          ) : (
            <>
              <Power className="w-3.5 h-3.5 text-slate-600" />
              <span className="text-[11px] text-slate-500">Inativo</span>
            </>
          )}
        </div>
        <button
          onClick={onEdit}
          className="flex items-center gap-1.5 text-[11px] text-slate-500 hover:text-brand-400 transition-colors"
        >
          <Settings2 className="w-3.5 h-3.5" />
          Configurar
        </button>
      </div>
    </Card>
  )
}

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

export default function WarmerPage() {
  const {
    instances, activeCount, totalCount, toast,
    toggleEnabled, editing, editDraft,
    openEdit, closeEdit, saveEdit,
    addTemplate, removeTemplate, patchDraft,
  } = useWarmerLogic()

  const editingInst = instances.find((i) => i.id === editing)

  return (
    <div className="min-h-screen bg-surface p-6 lg:p-10 font-sans">
      <PageHeader
        icon={Flame}
        title="WhatsApp Warmer"
        subtitle="Aquecimento gradual de chips para evitar bloqueios"
        actions={
          <div className="flex items-center gap-3">
            {activeCount > 0 ? (
              <Badge variant="warning">
                <Flame className="w-3 h-3" />
                {activeCount} aquecendo
              </Badge>
            ) : (
              <Badge variant="neutral">
                <Power className="w-3 h-3" />
                Nenhum ativo
              </Badge>
            )}
          </div>
        }
      />

      {/* Info banner */}
      <div className="mb-8 p-4 rounded-2xl bg-orange-500/10 border border-orange-500/20 flex items-start gap-3">
        <AlertCircle className="w-4 h-4 text-orange-400 flex-shrink-0 mt-0.5" />
        <p className="text-xs text-orange-200/80 leading-relaxed">
          O warmer envia mensagens automáticas em intervalos aleatórios para simular atividade humana.
          Ative apenas em instâncias conectadas. O envio real requer configuração de contatos no backend.
        </p>
      </div>

      {/* Grid */}
      {totalCount === 0 ? (
        <div className="flex flex-col items-center justify-center py-24 text-center">
          <Smartphone className="w-16 h-16 text-white/5 mb-4" />
          <p className="text-slate-500 text-sm">Nenhuma instância encontrada.</p>
          <p className="text-slate-600 text-xs mt-1">
            Adicione instâncias em <a href="/sessions" className="text-brand-400 hover:underline">Sessões</a>.
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
          {instances.map((inst) => (
            <WarmerCard
              key={inst.id}
              inst={inst}
              onToggle={() => toggleEnabled(inst.id)}
              onEdit={() => openEdit(inst.id)}
            />
          ))}
        </div>
      )}

      {/* Edit Modal */}
      <AnimatePresence>
        {editing && editingInst && (
          <EditModal
            instanceName={editingInst.name}
            draft={editDraft}
            onClose={closeEdit}
            onSave={saveEdit}
            onAdd={addTemplate}
            onRemove={removeTemplate}
            onPatch={patchDraft}
          />
        )}
      </AnimatePresence>

      {/* Toast */}
      <Toast message={toast?.msg ?? ''} type={toast?.ok ? 'success' : 'error'} visible={!!toast} />
    </div>
  )
}
