'use client';

/**
 * Phase 8.4 (2026-04-29) — Modal organisation d'évasion (B3 uniquement).
 *
 * Affiche le coût progressif (200k/500k/1M/3M/5M selon escape_count) + warning
 * chaleur 99 + délai 5 min. Confirmation → POST /api/prison/escape/start.
 *
 * Si escape_count >= 5 → blocked, message "Plus jamais d'évasion possible".
 *
 * Phase 7 i18n (2026-04-29) — toutes les strings via t()/tFmt().
 */
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { api } from '@/lib/api';
import { t, tFmt } from '@/lib/i18n';
import { Skull, X, AlertTriangle, Clock } from 'lucide-react';

interface PrisonEscapeModalProps {
  onClose: () => void;
  onScheduled?: (scheduledAt: string) => void;
}

export function PrisonEscapeModal({ onClose, onScheduled }: PrisonEscapeModalProps) {
  const [info, setInfo] = useState<{ escape_count: number; next_cost: number; blocked: boolean; delay_seconds: number } | null>(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [scheduled, setScheduled] = useState<{ scheduled_at: string; cost: number; evasion_number: number } | null>(null);

  useEffect(() => {
    api.prisonExtras.getEscapeCost()
      .then((r) => setInfo(r))
      .catch((e: any) => setError(e?.message || t('prison_phase8.escape.load_error')))
      .finally(() => setLoading(false));
  }, []);

  const submit = async () => {
    if (!info || info.blocked) return;
    const confirmMsg = tFmt('prison_phase8.escape.confirm_message', {
      cost: info.next_cost.toLocaleString('fr-FR'),
      minutes: Math.round(info.delay_seconds / 60),
    });
    if (!confirm(confirmMsg)) return;
    setSubmitting(true);
    setError(null);
    try {
      const r = await api.prisonExtras.startEscape();
      setScheduled({ scheduled_at: r.scheduled_at, cost: r.cost, evasion_number: r.evasion_number });
      onScheduled?.(r.scheduled_at);
    } catch (e: any) {
      setError(e?.message || t('prison_phase8.escape.submit_error'));
    } finally {
      setSubmitting(false);
    }
  };

  if (typeof document === 'undefined') return null;

  return createPortal(
    <div
      className="fixed inset-0 z-[10000] flex items-center justify-center"
      style={{ background: 'rgba(0,0,0,0.85)' }}
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div
        className="w-full max-w-md rounded-xl p-5 relative"
        style={{ background: 'var(--bg-panel)', border: '1px solid var(--color-red)' }}
      >
        <button onClick={onClose} className="absolute top-3 right-3 p-1 hover:opacity-70">
          <X size={18} style={{ color: 'var(--text-muted)' }} />
        </button>

        <div className="flex items-center gap-2 mb-3">
          <Skull size={18} style={{ color: 'var(--color-red-light)' }} />
          <h2 className="font-gothic text-base" style={{ color: 'var(--color-red-light)' }}>{t('prison_phase8.escape.title')}</h2>
        </div>

        {loading ? (
          <p className="text-[11px]" style={{ color: 'var(--text-muted)' }}>{t('prison_phase8.escape.loading')}</p>
        ) : !info ? (
          <p className="text-[11px]" style={{ color: 'var(--color-red-light)' }}>{error || t('prison_phase8.escape.load_error')}</p>
        ) : info.blocked ? (
          <div className="p-3 rounded text-center"
            style={{ background: 'rgba(239,68,68,0.12)', border: '1px solid rgba(239,68,68,0.5)' }}>
            <p className="text-[11px] font-bold" style={{ color: '#fca5a5' }}>
              {t('prison_phase8.escape.blocked_title')}
            </p>
            <p className="text-[10px] italic mt-2" style={{ color: 'var(--text-secondary)' }}>
              {t('prison_phase8.escape.blocked_message')}
            </p>
            <button
              onClick={onClose}
              className="mt-3 px-4 py-1.5 rounded text-[11px]"
              style={{ color: 'var(--text-muted)', border: '1px solid var(--border-subtle)' }}>
              {t('prison_phase8.escape.blocked_close')}
            </button>
          </div>
        ) : scheduled ? (
          <div className="p-3 rounded"
            style={{ background: 'rgba(34,197,94,0.12)', border: '1px solid rgba(34,197,94,0.5)' }}>
            <p className="text-[12px] font-bold mb-1" style={{ color: '#86efac' }}>
              {tFmt('prison_phase8.escape.success_title', { number: scheduled.evasion_number })}
            </p>
            <p className="text-[10px] italic mb-2" style={{ color: 'var(--text-secondary)' }}>
              {tFmt('prison_phase8.escape.success_message', {
                time: new Date(scheduled.scheduled_at).toLocaleTimeString('fr-FR'),
              })}
            </p>
            <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
              {tFmt('prison_phase8.escape.success_cost', { cost: scheduled.cost.toLocaleString('fr-FR') })}
            </p>
            <button
              onClick={onClose}
              className="mt-3 w-full py-2 rounded text-[11px] font-bold"
              style={{
                background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))',
                color: 'white',
              }}>
              {t('prison_phase8.escape.success_close')}
            </button>
          </div>
        ) : (
          <>
            <div className="space-y-2 mb-3">
              <div className="p-2 rounded text-[11px]"
                style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
                <span style={{ color: 'var(--text-muted)' }}>{t('prison_phase8.escape.evasion_number')} </span>
                <strong style={{ color: 'var(--color-red-light)' }}>
                  {tFmt('prison_phase8.escape.evasion_count', { current: info.escape_count + 1 })}
                </strong>
              </div>
              <div className="p-2 rounded text-[11px]"
                style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
                <span style={{ color: 'var(--text-muted)' }}>{t('prison_phase8.escape.cost_label')} </span>
                <strong style={{ color: 'var(--color-red-light)' }}>
                  {tFmt('prison_phase8.escape.cost_value', { cost: info.next_cost.toLocaleString('fr-FR') })}
                </strong>
              </div>
              <div className="p-2 rounded text-[11px] flex items-center gap-2"
                style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
                <Clock size={11} style={{ color: 'var(--text-muted)' }} />
                <span style={{ color: 'var(--text-muted)' }}>{t('prison_phase8.escape.delay_label')} </span>
                <strong style={{ color: 'var(--text-primary)' }}>
                  {tFmt('prison_phase8.escape.delay_value', { minutes: Math.round(info.delay_seconds / 60) })}
                </strong>
              </div>
            </div>

            <div className="p-2 rounded text-[10px] flex items-start gap-1 mb-3"
              style={{ background: 'rgba(239,68,68,0.06)', border: '1px solid rgba(239,68,68,0.4)' }}>
              <AlertTriangle size={11} style={{ color: '#fca5a5', marginTop: 1 }} />
              <div style={{ color: 'var(--text-secondary)' }}>
                <strong>{t('prison_phase8.escape.consequences_title')}</strong>
                <ul className="list-disc pl-4 mt-1 space-y-0.5">
                  <li>{t('prison_phase8.escape.consequences_heat')}</li>
                  <li>{t('prison_phase8.escape.consequences_casier')}</li>
                  <li>{t('prison_phase8.escape.consequences_held')}</li>
                  <li>{t('prison_phase8.escape.consequences_exit')}</li>
                </ul>
              </div>
            </div>

            {error && (
              <p className="text-[11px] mb-2" style={{ color: 'var(--color-red-light)' }}>{error}</p>
            )}

            <div className="flex gap-2">
              <button
                onClick={submit}
                disabled={submitting}
                className="flex-1 py-2 rounded font-bold text-[11px] uppercase tracking-[.1em] disabled:opacity-50"
                style={{
                  background: 'linear-gradient(135deg, var(--color-red-dark), rgba(14,14,22,0.9))',
                  border: '1px solid var(--color-red)',
                  color: '#fca5a5',
                  cursor: 'pointer',
                }}>
                {submitting
                  ? t('prison_phase8.escape.submit_progress')
                  : tFmt('prison_phase8.escape.submit_button', { number: info.escape_count + 1 })}
              </button>
              <button
                onClick={onClose}
                disabled={submitting}
                className="px-4 py-2 rounded text-[11px]"
                style={{ color: 'var(--text-muted)', border: '1px solid var(--border-subtle)' }}>
                {t('prison_phase8.escape.cancel')}
              </button>
            </div>
          </>
        )}
      </div>
    </div>,
    document.body,
  );
}
