'use client';
/**
 * AllianceButtons — boutons adaptés selon le statut entre le cartel du viewer
 * et un cartel cible. Style aligné sur le projet (gold / red-light / text-muted).
 *
 * Statuts (résolus via api.cartelAlliance.status(cartelId)) :
 *   - none              : → "Proposer alliance"
 *   - pending_sent      : → "Proposition envoyée" + "Annuler"
 *   - pending_received  : → "Accepter" / "Refuser" (label "X vous propose…")
 *   - allied            : → badge "✓ Alliés" + "Rompre alliance"
 * + Bouton "Contacter" ouvre le MessageComposer côté parent.
 */
import { useEffect, useState, useCallback } from 'react';
import { api } from '@/lib/api';

type Status = 'none' | 'pending_sent' | 'pending_received' | 'allied' | 'loading' | 'unauthorized';

export function AllianceButtons({
  cartelId, cartelName, onContact, onChanged,
}: {
  cartelId: string;
  cartelName: string;
  onContact?: () => void;
  onChanged?: () => void;
}) {
  const [status, setStatus] = useState<Status>('loading');
  const [allianceId, setAllianceId] = useState<string | undefined>();
  const [busy, setBusy] = useState(false);

  const refresh = useCallback(async () => {
    setStatus('loading');
    try {
      const r = await api.cartelAlliance.status(cartelId);
      setStatus(r.status);
      setAllianceId(r.alliance_id);
    } catch {
      setStatus('unauthorized');
    }
  }, [cartelId]);

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

  const handle = async (fn: () => Promise<unknown>, confirmMsg?: string) => {
    if (confirmMsg && !window.confirm(confirmMsg)) return;
    setBusy(true);
    try {
      await fn();
      onChanged?.();
      await refresh();
    } catch (e: any) {
      alert(e?.message || 'Opération impossible');
    } finally {
      setBusy(false);
    }
  };

  if (status === 'loading' || status === 'unauthorized') return null;

  const btnPrimary = (label: string, onClick: () => void) => (
    <button
      type="button"
      disabled={busy}
      onClick={onClick}
      className="px-3 py-1.5 text-[10px] font-bold rounded disabled:opacity-40 transition"
      style={{
        color: 'var(--bg-panel)',
        background: 'var(--color-gold)',
        letterSpacing: '.1em',
      }}
    >{label}</button>
  );

  const btnDanger = (label: string, onClick: () => void) => (
    <button
      type="button"
      disabled={busy}
      onClick={onClick}
      className="px-3 py-1.5 text-[10px] font-bold rounded disabled:opacity-40 transition"
      style={{
        color: '#fff',
        background: 'var(--color-red-light, #dc2626)',
        letterSpacing: '.1em',
      }}
    >{label}</button>
  );

  const btnGhost = (label: string, onClick: () => void) => (
    <button
      type="button"
      disabled={busy}
      onClick={onClick}
      className="px-3 py-1.5 text-[10px] rounded disabled:opacity-40 transition"
      style={{
        color: 'var(--text-muted)',
        border: '1px solid var(--border-dark)',
      }}
    >{label}</button>
  );

  return (
    <div className="flex flex-wrap items-center gap-1.5">
      {status === 'none' && btnPrimary(
        'Proposer alliance',
        () => handle(() => api.cartelAlliance.propose(cartelId), `Proposer une alliance à ${cartelName} ?`),
      )}

      {status === 'pending_sent' && (
        <>
          <span
            className="px-2 py-1 text-[10px] italic rounded"
            style={{ color: 'var(--color-gold-light)', border: '1px dashed var(--color-gold-light)' }}
          >⏳ Proposition envoyée</span>
          {btnGhost('Annuler', () => handle(() => api.cartelAlliance.cancel(allianceId!), 'Annuler votre proposition ?'))}
        </>
      )}

      {status === 'pending_received' && (
        <>
          <span
            className="px-2 py-1 text-[10px] font-bold rounded w-full"
            style={{ color: '#c084fc', background: 'rgba(168,85,247,0.15)', border: '1px solid rgba(168,85,247,0.4)' }}
          >
            {cartelName} vous propose une alliance
          </span>
          {btnPrimary('Accepter', () => handle(() => api.cartelAlliance.accept(allianceId!)))}
          {btnDanger('Refuser', () => handle(() => api.cartelAlliance.reject(allianceId!), `Refuser l'alliance avec ${cartelName} ?`))}
        </>
      )}

      {status === 'allied' && (
        <>
          <span
            className="px-2 py-1 text-[10px] font-bold rounded"
            style={{ color: '#4ade80', background: 'rgba(22,101,52,0.25)', border: '1px solid rgba(22,101,52,0.6)' }}
          >✓ Alliés</span>
          {btnDanger('Rompre', () => handle(() => api.cartelAlliance.break(allianceId!), `Rompre l'alliance avec ${cartelName} ?`))}
        </>
      )}

      {onContact && status !== 'none' && btnGhost('✉ Contacter', onContact)}
    </div>
  );
}
