'use client';

/**
 * Phase 4 (2026-04-26) — Modal Soudoyer POI gouvernemental.
 *
 * Déclenché par window event 'poi-bribe-open' avec detail = { poiId, poiName, poiKind }.
 * MapContextMenu dispatch cet event quand on clique-droit un POI police/townhall/courthouse.
 *
 * UX :
 *   - Liste déroulante crescendo des tiers disponibles (label + prix)
 *   - Pour police/townhall : checkbox « Établir un arrangement récurrent (quotidien) »
 *   - Pour courthouse : pas de récurrent (one_shot)
 *   - Lightbox récap effets après bribe (heat -X, items grantés, gangsters libérés)
 *   - Style aligné sur le thème or du jeu (cf VehicleActionHandler/OrderWizard)
 */
import { useEffect, useState, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { X, Scale, Shield, Gavel } from 'lucide-react';
import { api } from '@/lib/api';

type PoiKind = 'police' | 'townhall' | 'courthouse';

type Tier = {
  tier: number;
  amount: number;
  currency: 'infinite_light' | 'infinite_shadow';
  heat_delta: number;
  cycle_kind: 'daily' | 'monthly' | 'one_shot';
  grants_items?: Array<{ item_subtype: string; quantity: number }>;
  releases_gang_members?: boolean;
  label: string;
  description: string;
};

type Mode =
  | { kind: 'idle' }
  | { kind: 'open'; poiId: string; poiName: string; poiKind: PoiKind; tiers: Tier[]; selectedTier: number; isRecurring: boolean }
  | { kind: 'result'; flavor: string; result: any };

const KIND_META: Record<PoiKind, { title: string; icon: any; accent: string }> = {
  police:     { title: 'Soudoyer les forces de l\'ordre',           icon: Shield, accent: 'rgba(59,130,246,0.4)'   },
  townhall:   { title: 'Sous main à la mairie',                       icon: Scale,  accent: 'rgba(212,168,67,0.4)'  },
  courthouse: { title: 'Affaire au tribunal',                         icon: Gavel,  accent: 'rgba(168,85,247,0.4)'  },
};

export function PoiBribeModal() {
  const [mode, setMode] = useState<Mode>({ kind: 'idle' });
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Listen open event
  useEffect(() => {
    const handler = async (e: Event) => {
      const detail = (e as CustomEvent).detail as { poiId: string; poiName: string; poiKind: PoiKind };
      if (!detail?.poiId || !detail?.poiKind) return;
      setError(null);
      setBusy(true);
      try {
        const opts = await api.poiBribe.options(detail.poiId);
        setMode({
          kind: 'open',
          poiId: detail.poiId,
          poiName: detail.poiName || detail.poiKind,
          poiKind: detail.poiKind,
          tiers: opts.tiers as Tier[],
          selectedTier: opts.tiers[0]?.tier ?? 1,
          isRecurring: false,
        });
      } catch (err: any) {
        setError(err?.message || 'Erreur de chargement');
      } finally {
        setBusy(false);
      }
    };
    window.addEventListener('poi-bribe-open', handler);
    return () => window.removeEventListener('poi-bribe-open', handler);
  }, []);

  const close = useCallback(() => {
    setMode({ kind: 'idle' });
    setError(null);
    setBusy(false);
  }, []);

  const submit = async () => {
    if (mode.kind !== 'open') return;
    setBusy(true);
    setError(null);
    try {
      const result = await api.poiBribe.bribe(mode.poiId, {
        tier: mode.selectedTier,
        is_recurring: mode.isRecurring,
        poi_kind: mode.poiKind,
      });
      const tier = mode.tiers.find(t => t.tier === mode.selectedTier);
      const flavor = mode.poiKind === 'courthouse'
        ? `Le dossier est classé. ${result.heat_applied < 0 ? `Chaleur ${result.heat_applied}.` : ''}`
        : mode.poiKind === 'townhall'
          ? `L'enveloppe a glissé sous le bureau. ${result.heat_applied < 0 ? `Chaleur ${result.heat_applied}/jour.` : ''}`
          : `Le bakchich est accepté. ${result.heat_applied < 0 ? `Chaleur ${result.heat_applied}/jour.` : ''}`;
      setMode({ kind: 'result', flavor, result });
    } catch (err: any) {
      setError(err?.message || 'Soudoiement refusé');
    } finally {
      setBusy(false);
    }
  };

  if (mode.kind === 'idle') return null;
  if (typeof document === 'undefined') return null;

  const meta = mode.kind === 'open' ? KIND_META[mode.poiKind] : KIND_META.courthouse;
  const Icon = meta.icon;

  return createPortal(
    <div
      onClick={close}
      style={{
        position: 'fixed', inset: 0, zIndex: 3500,
        background: 'rgba(0,0,0,0.7)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: '92vw', maxWidth: 520,
          background: 'var(--bg-panel)',
          color: 'var(--text-primary)',
          border: `1px solid ${meta.accent}`,
          borderRadius: 16,
          boxShadow: `0 0 60px ${meta.accent}, 0 20px 60px rgba(0,0,0,0.7)`,
          overflow: 'hidden',
        }}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-4 py-3"
          style={{ borderBottom: '1px solid var(--border-dark)' }}>
          <div className="flex items-center gap-2">
            <Icon size={16} style={{ color: 'var(--color-gold-light)' }} />
            <p className="text-sm font-bold" style={{ color: 'var(--color-gold-light)', letterSpacing: '.12em', fontFamily: 'var(--font-subtitle)' }}>
              {meta.title.toUpperCase()}
            </p>
          </div>
          <button onClick={close}
            className="w-8 h-8 rounded-lg flex items-center justify-center hover:opacity-80"
            style={{ background: 'rgba(255,255,255,0.04)' }}>
            <X size={14} style={{ color: 'var(--text-secondary)' }} />
          </button>
        </div>

        {/* Body */}
        <div className="p-4" style={{ maxHeight: '70vh', overflowY: 'auto' }}>
          {error && (
            <div className="mb-3 p-2 rounded text-[11px]"
              style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.3)', color: '#ef4444' }}>
              {error}
            </div>
          )}

          {mode.kind === 'open' && (
            <div className="space-y-3">
              <p className="text-[11px] italic" style={{ color: 'var(--text-secondary)' }}>
                Cible : {mode.poiName}
              </p>

              {/* Tier selector — liste déroulante crescendo (style or thème) */}
              <div>
                <label className="block text-[10px] uppercase font-bold mb-1" style={{ color: 'var(--color-gold-light)', letterSpacing: '.15em' }}>
                  Montant à proposer
                </label>
                <select
                  value={mode.selectedTier}
                  onChange={(e) => setMode((m) => m.kind === 'open' ? { ...m, selectedTier: Number(e.target.value) } : m)}
                  className="w-full px-3 py-2 rounded-lg text-[12px] outline-none"
                  style={{
                    background: 'var(--bg-tertiary)',
                    color: 'var(--text-primary)',
                    border: `1px solid ${meta.accent}`,
                    fontFamily: 'var(--font-subtitle)',
                  }}
                >
                  {mode.tiers.map((t) => (
                    <option key={t.tier} value={t.tier}>
                      {t.label} — {t.description}
                    </option>
                  ))}
                </select>
              </div>

              {/* Récurrence — pas pour courthouse (one_shot forcé) */}
              {mode.poiKind !== 'courthouse' && (
                <label className="flex items-start gap-2 p-2 rounded cursor-pointer text-[11px]"
                  style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid var(--border-dark)' }}>
                  <input
                    type="checkbox"
                    checked={mode.isRecurring}
                    onChange={(e) => setMode((m) => m.kind === 'open' ? { ...m, isRecurring: e.target.checked } : m)}
                    className="mt-0.5"
                  />
                  <span style={{ color: 'var(--text-secondary)' }}>
                    Établir un arrangement récurrent quotidien
                    <span className="block text-[9px] italic mt-0.5" style={{ color: 'var(--text-muted)' }}>
                      Prélèvement automatique chaque 24h. Annulé si fonds insuffisants.
                    </span>
                  </span>
                </label>
              )}

              {/* Récap effet selected tier */}
              {(() => {
                const sel = mode.tiers.find(t => t.tier === mode.selectedTier);
                if (!sel) return null;
                return (
                  <div className="p-3 rounded text-[11px]"
                    style={{ background: 'rgba(212,168,67,0.06)', border: '1px solid var(--border-gold)', color: 'var(--text-primary)' }}>
                    <p>
                      <b style={{ color: 'var(--color-gold-light)' }}>{sel.label}</b>
                    </p>
                    <p className="mt-1" style={{ color: 'var(--text-secondary)' }}>
                      Effet : {sel.description}
                    </p>
                    {sel.grants_items && sel.grants_items.length > 0 && (
                      <p className="mt-1" style={{ color: 'var(--text-secondary)' }}>
                        Bonus item : {sel.grants_items.map(g => `${g.quantity}× ${g.item_subtype}`).join(', ')}
                      </p>
                    )}
                    {sel.releases_gang_members && (
                      <p className="mt-1" style={{ color: '#22c55e' }}>
                        ✓ Libère tous les gangsters de votre gang direct actuellement incarcérés.
                      </p>
                    )}
                  </div>
                );
              })()}
            </div>
          )}

          {mode.kind === 'result' && (
            <div className="space-y-3">
              <p className="text-[12px] italic" style={{ color: 'var(--color-gold-light)' }}>
                « {mode.flavor} »
              </p>
              <div className="p-3 rounded text-[11px]"
                style={{ background: 'rgba(34,197,94,0.08)', border: '1px solid rgba(34,197,94,0.3)', color: 'var(--text-primary)' }}>
                <p>
                  Payé : <b>{mode.result.amount_paid.toLocaleString('fr-FR')} ∞</b> ·
                  Chaleur : <b>{mode.result.heat_applied}</b>
                </p>
                {mode.result.granted_items?.length > 0 && (
                  <p className="mt-1" style={{ color: 'var(--color-gold-light)' }}>
                    Items obtenus : {mode.result.granted_items.map((g: any) => `${g.quantity}× ${g.item_subtype}`).join(', ')}
                  </p>
                )}
                {mode.result.released_gang_members?.length > 0 && (
                  <p className="mt-1" style={{ color: '#22c55e' }}>
                    {mode.result.released_gang_members.length} gangster(s) libéré(s).
                  </p>
                )}
                {mode.result.is_recurring && mode.result.next_payment_at && (
                  <p className="mt-1 text-[10px] italic" style={{ color: 'var(--text-muted)' }}>
                    Prochain paiement : {new Date(mode.result.next_payment_at).toLocaleString('fr-FR')}.
                    Vous pouvez l'annuler depuis le panneau « Mes arrangements ».
                  </p>
                )}
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between p-3"
          style={{ borderTop: '1px solid var(--border-dark)' }}>
          <button type="button" onClick={close} disabled={busy}
            className="px-3 py-1.5 rounded-lg text-[11px]"
            style={{ background: 'rgba(255,255,255,0.06)', color: 'var(--text-secondary)', border: '1px solid var(--border-dark)' }}>
            {mode.kind === 'result' ? 'Fermer' : 'Annuler'}
          </button>
          {mode.kind === 'open' && (
            <button type="button" onClick={submit} disabled={busy}
              className="px-4 py-1.5 rounded-lg text-[11px] font-bold disabled:opacity-50"
              style={{
                background: 'linear-gradient(180deg, var(--color-gold-light), var(--color-gold))',
                color: 'var(--bg-panel)',
                letterSpacing: '.12em',
              }}>
              {busy ? '…' : 'PROPOSER'}
            </button>
          )}
        </div>
      </div>
    </div>,
    document.body,
  );
}
