import { useState, useEffect, useCallback } from 'react';
import { CotacaoService } from '../services/api';
import {
  Landmark, RefreshCw, CheckCircle2, XCircle, AlertTriangle,
  User, MapPin, Clock, Truck, ChevronDown, ChevronUp,
} from 'lucide-react';

const fmtBRL  = (v: any) => Number(v).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
const fmtDate = (d: string) => d ? new Date(d).toLocaleString('pt-BR', { day:'2-digit', month:'2-digit', hour:'2-digit', minute:'2-digit' }) : '—';

function StatusPill({ s }: { s: string }) {
  if (s === 'aprovado')  return <span className="bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-[10px] font-black uppercase px-2 py-0.5 rounded-full">Aprovado</span>
  if (s === 'rejeitado') return <span className="bg-rose-500/10 border border-rose-500/30 text-rose-400 text-[10px] font-black uppercase px-2 py-0.5 rounded-full">Rejeitado</span>
  return <span className="bg-amber-500/10 border border-amber-500/30 text-amber-400 text-[10px] font-black uppercase px-2 py-0.5 rounded-full">Pendente</span>
}

function PedidoCard({ pedido, onDecisao }: { pedido: any; onDecisao: () => void }) {
  const [expanded, setExpanded] = useState(false)
  const [saving, setSaving]     = useState(false)
  const [obs, setObs]           = useState('')
  const [erro, setErro]         = useState('')

  async function decidir(acao: 'aprovar' | 'rejeitar') {
    setSaving(true); setErro('')
    try {
      await CotacaoService.financeiroDecisao(pedido.id, acao, obs || undefined)
      onDecisao()
    } catch (e: any) {
      setErro(e?.response?.data?.error ?? 'Erro ao processar decisão')
    } finally {
      setSaving(false)
    }
  }

  const endereco = [pedido.rua, pedido.end_numero, pedido.bairro, pedido.cidade, pedido.estado].filter(Boolean).join(', ')

  return (
    <div className="bg-slate-900/50 border border-amber-500/20 rounded-2xl overflow-hidden">
      {/* Header do card */}
      <div className="p-5 flex items-start gap-4">
        <div className="w-11 h-11 rounded-xl bg-amber-500/10 border border-amber-500/20 flex items-center justify-center shrink-0">
          <Truck size={18} className="text-amber-400" />
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-3 flex-wrap mb-1">
            <span className="font-black text-white">Pedido #{pedido.id}</span>
            <StatusPill s={pedido.financeiro_status} />
            {pedido.cliente_tipo && (
              <span className={`text-[10px] font-black uppercase ${pedido.cliente_tipo === 'PJ' ? 'text-purple-400' : 'text-cyan-400'}`}>
                {pedido.cliente_tipo}
              </span>
            )}
          </div>
          <div className="flex items-center gap-1.5 text-sm text-slate-400">
            <User size={12} className="shrink-0" />
            <span>{pedido.cliente_nome || 'Cliente não identificado'}</span>
            {pedido.cpf_cnpj && <span className="text-slate-600">· {pedido.cpf_cnpj}</span>}
          </div>
          {endereco && (
            <div className="flex items-center gap-1.5 text-xs text-slate-500 mt-0.5">
              <MapPin size={11} className="shrink-0" />
              <span>{endereco}</span>
            </div>
          )}
          <div className="flex items-center gap-1.5 text-xs text-slate-600 mt-0.5">
            <Clock size={11} className="shrink-0" />
            <span>{fmtDate(pedido.created_at)}</span>
          </div>
        </div>

        <div className="text-right shrink-0">
          <p className="font-black text-white text-lg tabular-nums">{fmtBRL(pedido.total)}</p>
          <button
            onClick={() => setExpanded(e => !e)}
            className="text-slate-500 hover:text-white transition-colors mt-1"
          >
            {expanded ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
          </button>
        </div>
      </div>

      {/* Painel de decisão */}
      {expanded && pedido.financeiro_status === 'pendente' && (
        <div className="border-t border-white/5 p-5 flex flex-col gap-3">
          <p className="text-xs text-slate-400">
            O cliente solicitou <strong className="text-amber-400">pagamento na entrega</strong>. Avalie o histórico e decida se libera ou recusa.
          </p>
          <textarea
            value={obs}
            onChange={e => setObs(e.target.value)}
            placeholder="Observação interna (opcional)..."
            rows={2}
            className="w-full bg-slate-800/60 border border-white/10 rounded-xl px-3 py-2 text-sm text-white placeholder:text-slate-600 resize-none focus:outline-none focus:border-amber-500/50"
          />
          {erro && (
            <div className="flex items-center gap-2 text-rose-400 text-xs">
              <AlertTriangle size={13} /> {erro}
            </div>
          )}
          <div className="grid grid-cols-2 gap-3">
            <button
              disabled={saving}
              onClick={() => decidir('rejeitar')}
              className="flex items-center justify-center gap-2 py-2.5 rounded-xl border border-rose-500/30 bg-rose-500/10 text-rose-400 hover:bg-rose-500/20 font-black text-sm transition-colors disabled:opacity-50"
            >
              <XCircle size={16} /> Rejeitar
            </button>
            <button
              disabled={saving}
              onClick={() => decidir('aprovar')}
              className="flex items-center justify-center gap-2 py-2.5 rounded-xl border border-emerald-500/30 bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20 font-black text-sm transition-colors disabled:opacity-50"
            >
              {saving ? <RefreshCw size={14} className="animate-spin" /> : <CheckCircle2 size={16} />}
              Aprovar
            </button>
          </div>
        </div>
      )}

      {/* Decisão já tomada */}
      {expanded && pedido.financeiro_status !== 'pendente' && (
        <div className="border-t border-white/5 p-5">
          <p className="text-xs text-slate-500">
            Decisão registrada em {fmtDate(pedido.financeiro_em)}.
            {pedido.financeiro_obs && <span className="block mt-1 text-slate-400 italic">"{pedido.financeiro_obs}"</span>}
          </p>
        </div>
      )}
    </div>
  )
}

export default function FinanceiroPage() {
  const [pedidos, setPedidos]   = useState<any[]>([])
  const [loading, setLoading]   = useState(true)
  const [filtro, setFiltro]     = useState<'pendente' | 'todos'>('pendente')

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const rows = await CotacaoService.listFinanceiro()
      setPedidos(rows)
    } catch {
      setPedidos([])
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => { load() }, [load])

  const pendentes = pedidos.filter(p => p.financeiro_status === 'pendente')
  const visíveis  = filtro === 'pendente' ? pendentes : pedidos

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
      {/* Header */}
      <header className="flex justify-between items-center flex-wrap gap-4">
        <div>
          <h2 className="text-3xl font-bold text-white tracking-tighter uppercase italic flex items-center gap-3">
            <Landmark size={28} className="text-amber-400" />
            Financeiro
          </h2>
          <p className="text-slate-400 mt-1 font-medium">Aprovação de pagamentos na entrega.</p>
        </div>
        <div className="flex items-center gap-3">
          {/* Filtro */}
          <div className="bg-slate-900 border border-slate-800 rounded-xl p-1 flex gap-1">
            {(['pendente', 'todos'] as const).map(f => (
              <button
                key={f}
                onClick={() => setFiltro(f)}
                className={`px-4 py-1.5 rounded-lg text-xs font-black uppercase transition-colors ${
                  filtro === f
                    ? 'bg-amber-500 text-black'
                    : 'text-slate-400 hover:text-white'
                }`}
              >
                {f === 'pendente' ? `Pendentes (${pendentes.length})` : `Todos (${pedidos.length})`}
              </button>
            ))}
          </div>
          <button
            onClick={load}
            disabled={loading}
            className="p-2.5 bg-slate-800 border border-slate-700 rounded-xl text-slate-400 hover:text-white transition-colors disabled:opacity-50"
          >
            <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
          </button>
        </div>
      </header>

      {/* Alerta zero pendências */}
      {!loading && pendentes.length === 0 && filtro === 'pendente' && (
        <div className="bg-emerald-500/5 border border-emerald-500/20 rounded-2xl p-10 text-center">
          <CheckCircle2 size={36} className="text-emerald-500/40 mx-auto mb-3" />
          <p className="text-slate-500 font-medium">Nenhuma solicitação pendente.</p>
          <p className="text-slate-600 text-sm mt-1">Todos os pedidos de pagamento na entrega foram avaliados.</p>
        </div>
      )}

      {/* Cards */}
      {loading ? (
        <div className="space-y-4">
          {[1,2,3].map(i => (
            <div key={i} className="h-28 bg-slate-900/40 border border-slate-800 rounded-2xl animate-pulse" />
          ))}
        </div>
      ) : (
        <div className="space-y-4">
          {visíveis.map(p => (
            <PedidoCard key={p.id} pedido={p} onDecisao={load} />
          ))}
        </div>
      )}

      {!loading && visíveis.length === 0 && filtro === 'todos' && (
        <div className="bg-slate-900/40 border border-slate-800 rounded-2xl p-10 text-center">
          <Landmark size={36} className="text-slate-700 mx-auto mb-3" />
          <p className="text-slate-600 text-sm">Nenhum registro de pagamento na entrega ainda.</p>
        </div>
      )}
    </div>
  )
}
