import { useState, useEffect, useRef } from 'react';
import { ClaimService } from '../services/api';
import { RefreshCw, Trophy, Phone, User, Package } from 'lucide-react';

type ClaimStatus = 'pending' | 'approved' | 'delivered';

interface Claim {
  id: number;
  status: ClaimStatus;
  raffle_titulo: string;
  ticket_numero: number;
  user_nome: string;
  user_cpf: string;
  user_telefone: string;
  delivery_address: string | null;
  delivery_notes: string | null;
  claimed_at: string;
  updated_at: string;
}

const COLUMNS: { key: ClaimStatus; label: string; color: string; border: string; badge: string }[] = [
  { key: 'pending',   label: 'Pendente',  color: 'text-yellow-400', border: 'border-yellow-500/20', badge: 'bg-yellow-400/10 text-yellow-400' },
  { key: 'approved',  label: 'Aprovado',  color: 'text-cyan-400',   border: 'border-cyan-500/20',   badge: 'bg-cyan-400/10 text-cyan-400' },
  { key: 'delivered', label: 'Entregue',  color: 'text-emerald-400',border: 'border-emerald-500/20',badge: 'bg-emerald-400/10 text-emerald-400' },
];

function ClaimCard({
  claim,
  onDragStart,
}: {
  claim: Claim;
  onDragStart: (e: React.DragEvent, id: number) => void;
}) {
  return (
    <div
      draggable
      onDragStart={e => onDragStart(e, claim.id)}
      className="bg-slate-900 border border-slate-800 rounded-2xl p-4 cursor-grab active:cursor-grabbing hover:border-slate-700 transition-all select-none"
    >
      <div className="flex items-start justify-between gap-2 mb-3">
        <div className="flex items-center gap-2 min-w-0">
          <Trophy size={14} className="text-yellow-400 shrink-0" />
          <span className="text-xs font-black text-white truncate">{claim.raffle_titulo}</span>
        </div>
        <span className="text-[10px] font-bold text-slate-500 tabular-nums shrink-0">
          #{claim.ticket_numero}
        </span>
      </div>

      <div className="space-y-1.5">
        <div className="flex items-center gap-1.5 text-xs text-slate-400">
          <User size={11} className="shrink-0" />
          <span className="truncate">{claim.user_nome || '—'}</span>
        </div>
        {claim.user_telefone && (
          <div className="flex items-center gap-1.5 text-xs text-slate-500">
            <Phone size={11} className="shrink-0" />
            <span className="font-mono">{claim.user_telefone}</span>
          </div>
        )}
        {claim.delivery_address && (
          <div className="flex items-start gap-1.5 text-xs text-slate-500">
            <Package size={11} className="shrink-0 mt-0.5" />
            <span className="line-clamp-2">{claim.delivery_address}</span>
          </div>
        )}
      </div>

      <div className="mt-3 pt-3 border-t border-slate-800 text-[10px] text-slate-600 tabular-nums">
        {new Date(claim.claimed_at).toLocaleString('pt-BR')}
      </div>
    </div>
  );
}

function KanbanColumn({
  col,
  claims,
  onDragStart,
  onDrop,
  onDragOver,
}: {
  col: typeof COLUMNS[0];
  claims: Claim[];
  onDragStart: (e: React.DragEvent, id: number) => void;
  onDrop: (e: React.DragEvent, status: ClaimStatus) => void;
  onDragOver: (e: React.DragEvent) => void;
}) {
  const [isDragOver, setIsDragOver] = useState(false);

  return (
    <div
      onDragOver={e => { onDragOver(e); setIsDragOver(true); }}
      onDragLeave={() => setIsDragOver(false)}
      onDrop={e => { onDrop(e, col.key); setIsDragOver(false); }}
      className={`flex-1 min-w-[260px] bg-slate-950/60 border rounded-3xl p-5 transition-all ${
        isDragOver ? `${col.border} shadow-lg` : 'border-slate-900'
      }`}
    >
      <div className="flex items-center justify-between mb-5">
        <h3 className={`text-sm font-black uppercase tracking-widest ${col.color}`}>{col.label}</h3>
        <span className={`text-[10px] font-black px-2 py-1 rounded-lg ${col.badge}`}>
          {claims.length}
        </span>
      </div>

      <div className="space-y-3 min-h-[80px]">
        {claims.length === 0 ? (
          <div className="flex items-center justify-center h-20 text-slate-700 text-xs italic border border-dashed border-slate-800 rounded-xl">
            Arraste para cá
          </div>
        ) : (
          claims.map(c => (
            <ClaimCard key={c.id} claim={c} onDragStart={onDragStart} />
          ))
        )}
      </div>
    </div>
  );
}

export default function ClaimsPage() {
  const [claims, setClaims] = useState<Claim[]>([]);
  const [loading, setLoading] = useState(true);
  const dragId = useRef<number | null>(null);

  const fetchClaims = async () => {
    setLoading(true);
    try {
      const data = await ClaimService.list();
      setClaims(data);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchClaims(); }, []);

  const handleDragStart = (e: React.DragEvent, id: number) => {
    dragId.current = id;
    e.dataTransfer.effectAllowed = 'move';
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDrop = async (e: React.DragEvent, newStatus: ClaimStatus) => {
    e.preventDefault();
    const id = dragId.current;
    if (id === null) return;

    const claim = claims.find(c => c.id === id);
    if (!claim || claim.status === newStatus) return;

    // Optimistic update
    setClaims(prev => prev.map(c => c.id === id ? { ...c, status: newStatus } : c));

    try {
      await ClaimService.updateStatus(id, newStatus);
    } catch {
      // Revert on failure
      setClaims(prev => prev.map(c => c.id === id ? { ...c, status: claim.status } : c));
      alert('Erro ao atualizar status. Tente novamente.');
    }

    dragId.current = null;
  };

  const byStatus = (status: ClaimStatus) => claims.filter(c => c.status === status);

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <header className="flex justify-between items-start">
        <div>
          <h2 className="text-3xl font-bold text-white">Resgates de Prêmios</h2>
          <p className="text-slate-400 mt-1">Gerencie os resgates dos ganhadores. Arraste os cards entre colunas para atualizar o status.</p>
        </div>
        <button
          onClick={fetchClaims}
          className="p-3 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl transition-all border border-slate-700 active:rotate-180 duration-500"
        >
          <RefreshCw size={20} />
        </button>
      </header>

      {loading ? (
        <div className="flex gap-6">
          {COLUMNS.map(col => (
            <div key={col.key} className="flex-1 min-w-[260px] bg-slate-950/60 border border-slate-900 rounded-3xl p-5 animate-pulse">
              <div className="h-4 bg-slate-800 rounded w-24 mb-5" />
              {[1, 2].map(i => <div key={i} className="h-32 bg-slate-800/40 rounded-2xl mb-3" />)}
            </div>
          ))}
        </div>
      ) : (
        <div className="flex gap-6 overflow-x-auto pb-4">
          {COLUMNS.map(col => (
            <KanbanColumn
              key={col.key}
              col={col}
              claims={byStatus(col.key)}
              onDragStart={handleDragStart}
              onDrop={handleDrop}
              onDragOver={handleDragOver}
            />
          ))}
        </div>
      )}
    </div>
  );
}
