'use client';
/**
 * AlliancesLightbox — gestion des alliances entre cartels pour l'admin.
 * Style aligné sur BaseLightbox du projet.
 */
import { useState, useEffect, useCallback } from 'react';
import { api } from '@/lib/api';
import { AllianceButtons } from './AllianceButtons';
import { MessageComposer } from './MessageComposer';

interface Cartel {
  id: string;
  name: string;
  xp?: number;
  member_count?: number;
  distance_m?: number | null;
}

interface Member {
  is_admin: boolean;
  primary_player_id: string | null;
  player?: { id: string; username: string };
}

type HistoryRow = {
  id: string;
  requester_cartel_id: string;
  target_cartel_id: string;
  status: 'rejected' | 'cancelled' | 'broken';
  requested_at: string;
  responded_at: string | null;
  cancelled_at: string | null;
  broken_at: string | null;
};

const HISTORY_LABEL: Record<HistoryRow['status'], { label: string; color: string }> = {
  broken: { label: 'Rompue', color: '#ef4444' },
  rejected: { label: 'Refusée', color: '#fbbf24' },
  cancelled: { label: 'Annulée', color: '#9ca3af' },
};

function formatHistoryDate(row: HistoryRow): string {
  const d = row.broken_at || row.cancelled_at || row.responded_at || row.requested_at;
  if (!d) return '—';
  return new Date(d).toLocaleDateString('fr-FR', {
    day: '2-digit', month: 'short', year: 'numeric',
  });
}

export function AlliancesLightbox({ ownCartelId, onClose }: { ownCartelId: string; onClose: () => void }) {
  const [tab, setTab] = useState<'cartels' | 'history'>('cartels');
  const [cartels, setCartels] = useState<Cartel[]>([]);
  const [incoming, setIncoming] = useState<any[]>([]);
  const [active, setActive] = useState<any[]>([]);
  const [history, setHistory] = useState<HistoryRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [composer, setComposer] = useState<{ recipientId: string; recipientName: string; subject: string } | null>(null);

  useEffect(() => {
    const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [onClose]);

  const refresh = useCallback(async () => {
    setLoading(true);
    try {
      const [list, inc, act, hist] = await Promise.all([
        api.cartel.listActive().catch(() => []),
        api.cartelAlliance.incoming().catch(() => []),
        api.cartelAlliance.active().catch(() => []),
        api.cartelAlliance.history().catch(() => []),
      ]);
      setCartels((list as Cartel[]).filter((c) => c.id !== ownCartelId));
      setIncoming(inc as any[]);
      setActive(act as any[]);
      setHistory(hist as HistoryRow[]);
    } finally {
      setLoading(false);
    }
  }, [ownCartelId]);

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

  // Map cartel_id → name pour l'affichage history (basé sur list cartels)
  const cartelNameMap = new Map<string, string>(cartels.map((c) => [c.id, c.name]));

  const openComposer = async (cartelId: string, cartelName: string) => {
    try {
      const details: any = await api.cartel.getDetails(cartelId);
      const admin = details?.members?.find((m: Member) => m.is_admin) || details?.members?.[0];
      const recipientId = admin?.primary_player_id || admin?.player?.id;
      const recipientName = admin?.player?.username || 'Admin du cartel';
      if (!recipientId) { alert('Admin introuvable'); return; }
      setComposer({
        recipientId, recipientName,
        subject: `Au sujet de l'alliance — ${cartelName}`,
      });
    } catch (e: any) {
      alert(e?.message || 'Impossible de charger l\'admin');
    }
  };

  return (
    <div
      className="fixed inset-0 z-[3500] flex items-center justify-center p-4"
      style={{ background: 'rgba(0,0,0,0.72)' }}
      onClick={onClose}
    >
      <div
        className="rounded-2xl overflow-hidden w-full flex flex-col"
        style={{
          maxWidth: 620, maxHeight: '88vh',
          background: 'var(--bg-panel)',
          border: '1px solid var(--border-dark)',
          boxShadow: '0 20px 80px rgba(0,0,0,0.6)',
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <div
          className="px-4 py-3 flex justify-between items-center flex-shrink-0"
          style={{
            borderBottom: '1px solid var(--border-dark)',
            background: 'linear-gradient(180deg, rgba(212,168,67,0.05), rgba(0,0,0,0))',
          }}
        >
          <p
            className="text-[13px] font-bold"
            style={{ color: 'var(--color-gold-light)', fontFamily: 'var(--font-subtitle)', letterSpacing: '.15em' }}
          >
            ALLIANCES — CARTELS
          </p>
          <button
            onClick={onClose}
            className="text-lg leading-none opacity-60 hover:opacity-100"
            style={{ color: 'var(--text-primary)' }}
          >×</button>
        </div>

        {/* Phase 17.2 finition Gap 3 (2026-05-06) — Tabs Cartels / Historique */}
        <div className="flex gap-1 px-4 pt-2 flex-shrink-0" style={{ borderBottom: '1px solid var(--border-dark)' }}>
          {(['cartels', 'history'] as const).map((t) => (
            <button
              key={t}
              onClick={() => setTab(t)}
              className="px-3 py-1.5 text-[10px] font-bold"
              style={{
                color: tab === t ? 'var(--color-gold-light)' : 'var(--text-muted)',
                borderBottom: tab === t ? '2px solid var(--color-gold-light)' : '2px solid transparent',
                background: 'transparent',
                letterSpacing: '.1em',
              }}
            >
              {t === 'cartels' ? 'CARTELS' : `HISTORIQUE ${history.length > 0 ? `(${history.length})` : ''}`}
            </button>
          ))}
        </div>

        <div className="p-5 space-y-4 overflow-y-auto" style={{ color: 'var(--text-secondary)', fontSize: 12, lineHeight: 1.5 }}>
          {loading && <p className="text-[11px]" style={{ color: 'var(--text-muted)' }}>Chargement…</p>}

          {!loading && tab === 'cartels' && (active.length > 0 || incoming.length > 0) && (
            <div className="grid grid-cols-2 gap-2 text-center">
              <div className="p-2 rounded" style={{ background: 'rgba(22,101,52,0.15)', border: '1px solid rgba(22,101,52,0.4)' }}>
                <div className="text-[10px]" style={{ color: '#4ade80' }}>ALLIANCES ACTIVES</div>
                <div className="text-lg font-bold" style={{ color: '#4ade80' }}>{active.length}</div>
              </div>
              <div className="p-2 rounded" style={{ background: 'rgba(168,85,247,0.15)', border: '1px solid rgba(168,85,247,0.4)' }}>
                <div className="text-[10px]" style={{ color: '#c084fc' }}>REÇUES EN ATTENTE</div>
                <div className="text-lg font-bold" style={{ color: '#c084fc' }}>{incoming.length}</div>
              </div>
            </div>
          )}

          {!loading && tab === 'history' && (
            <div>
              {history.length === 0 ? (
                <p className="text-[10px] py-3 text-center italic" style={{ color: 'var(--text-muted)' }}>
                  Aucun historique diplomatique. Vos alliances rompues, refusées ou annulées apparaîtront ici.
                </p>
              ) : (
                <div className="space-y-1.5">
                  {history.map((row) => {
                    const otherId = row.requester_cartel_id === ownCartelId ? row.target_cartel_id : row.requester_cartel_id;
                    const otherName = cartelNameMap.get(otherId) || '(cartel disparu)';
                    const meta = HISTORY_LABEL[row.status];
                    return (
                      <div
                        key={row.id}
                        className="rounded p-2 text-[10px] flex items-center justify-between"
                        style={{
                          background: 'rgba(255,255,255,0.02)',
                          border: '1px solid var(--border-dark)',
                        }}
                      >
                        <div className="min-w-0">
                          <span className="font-bold" style={{ color: 'var(--text-primary)' }}>{otherName}</span>
                          <span className="ml-2" style={{ color: 'var(--text-muted)' }}>
                            {formatHistoryDate(row)}
                          </span>
                        </div>
                        <span
                          className="px-2 py-0.5 rounded text-[9px] font-bold"
                          style={{
                            background: `${meta.color}1a`,
                            border: `1px solid ${meta.color}66`,
                            color: meta.color,
                          }}
                        >
                          {meta.label}
                        </span>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}

          {!loading && tab === 'cartels' && (
            <div>
              <p className="text-[10px] font-bold mb-2" style={{ color: 'var(--color-gold-light)', letterSpacing: '.15em' }}>
                CARTELS ({cartels.length})
              </p>
              {cartels.length === 0 ? (
                <p className="text-[10px] py-3 text-center" style={{ color: 'var(--text-muted)' }}>Aucun autre cartel actif.</p>
              ) : (
                <div className="space-y-2">
                  {cartels.map((c) => (
                    <div
                      key={c.id}
                      className="p-3 rounded-lg transition-colors"
                      style={{
                        background: 'rgba(255,255,255,0.02)',
                        border: '1px solid var(--border-dark)',
                      }}
                    >
                      <div className="flex justify-between items-center mb-2">
                        <div className="min-w-0">
                          <div className="text-[12px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>
                            {c.name}
                          </div>
                          <div className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                            {c.member_count ?? 0} membres · XP {c.xp ?? 0}
                            {c.distance_m != null && ` · ${(c.distance_m / 1000).toFixed(1)} km`}
                          </div>
                        </div>
                      </div>
                      <AllianceButtons
                        cartelId={c.id}
                        cartelName={c.name}
                        onContact={() => openComposer(c.id, c.name)}
                        onChanged={refresh}
                      />
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {composer && (
        <MessageComposer
          recipientId={composer.recipientId}
          recipientName={composer.recipientName}
          defaultSubject={composer.subject}
          context="alliance"
          onClose={() => setComposer(null)}
        />
      )}
    </div>
  );
}
