'use client';

/**
 * Phase 8.6c (2026-04-29) — Lightbox confirmation consommation Fiche RPS.
 *
 * Affichée quand le joueur clique "Utiliser" sur une Fiche RPS dans le
 * porte-document (ActivityPanel). Le joueur valide ou annule.
 *
 * i18n via t()/tFmt() namespace prison_phase8.activity_panel.
 */
import { useState } from 'react';
import { createPortal } from 'react-dom';
import { api } from '@/lib/api';
import { t, tFmt } from '@/lib/i18n';
import { FileMinus, X } from 'lucide-react';

interface RpsItem {
  id: string;
  item_subtype: string;
  reduction_hours: number;
}

interface RpsConsumeConfirmProps {
  item: RpsItem;
  /** ISO string de la libération actuelle (imprisoned_until). null si pas en prison. */
  currentRelease: string | null;
  /** ms restants en held_remaining_ms (si pas en prison). 0 sinon. */
  currentHeldMs: number;
  onClose: () => void;
  onResult: () => void;
}

export function RpsConsumeConfirm({
  item,
  currentRelease,
  currentHeldMs,
  onClose,
  onResult,
}: RpsConsumeConfirmProps) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const reductionMs = item.reduction_hours * 3_600_000;
  const isImprisoned = currentRelease ? new Date(currentRelease).getTime() > Date.now() : false;

  // Estimation locale (le backend ré-applique sa propre logique avec min)
  const newReleaseEstimate = isImprisoned && currentRelease
    ? new Date(new Date(currentRelease).getTime() - reductionMs)
    : null;
  const newHeldMs = !isImprisoned ? Math.max(0, currentHeldMs - reductionMs) : currentHeldMs;

  const formatRelease = (iso: string | Date | null): string => {
    if (!iso) return '—';
    const d = typeof iso === 'string' ? new Date(iso) : iso;
    if (Number.isNaN(d.getTime())) return '—';
    return d.toLocaleString(undefined, {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const formatHeld = (ms: number): string => {
    const hours = Math.floor(ms / 3_600_000);
    const days = Math.floor(hours / 24);
    if (days > 0) return `${days}j ${hours % 24}h`;
    return `${hours}h`;
  };

  const consume = async () => {
    setBusy(true);
    setError(null);
    try {
      await api.prison.consumeRps(item.id);
      onResult();
    } catch (e: any) {
      setError(e?.message || t('prison_phase8.activity_panel.consume_error'));
    } finally {
      setBusy(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 && !busy) onClose(); }}
    >
      <div
        className="w-full max-w-md rounded-xl p-5 relative"
        style={{ background: 'var(--bg-panel)', border: '1px solid var(--color-gold)' }}
      >
        <button
          onClick={onClose}
          disabled={busy}
          className="absolute top-3 right-3 p-1 hover:opacity-70 disabled:opacity-30"
        >
          <X size={18} style={{ color: 'var(--text-muted)' }} />
        </button>

        <div className="flex items-center gap-2 mb-3">
          <FileMinus size={18} style={{ color: 'var(--color-gold)' }} />
          <h2 className="font-gothic text-base" style={{ color: 'var(--color-gold)' }}>
            {tFmt('prison_phase8.activity_panel.consume_confirm_title', { hours: item.reduction_hours })}
          </h2>
        </div>

        {isImprisoned ? (
          <p className="text-[12px] mb-4 whitespace-pre-line" style={{ color: 'var(--text-secondary)' }}>
            {tFmt('prison_phase8.activity_panel.consume_confirm_body', {
              hours: item.reduction_hours,
              current_release: formatRelease(currentRelease),
              new_release: formatRelease(newReleaseEstimate),
            })}
          </p>
        ) : (
          <p className="text-[12px] mb-4" style={{ color: 'var(--text-secondary)' }}>
            {tFmt('prison_phase8.activity_panel.consume_confirm_held', {
              hours: item.reduction_hours,
              current_held: formatHeld(currentHeldMs),
              new_held: formatHeld(newHeldMs),
            })}
          </p>
        )}

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

        <div className="grid grid-cols-2 gap-2">
          <button
            onClick={consume}
            disabled={busy}
            className="py-2 rounded font-bold text-[11px] uppercase tracking-[.1em] disabled:opacity-50"
            style={{
              background: 'linear-gradient(135deg, rgba(212,175,55,0.4), rgba(14,14,22,0.9))',
              border: '1px solid var(--color-gold)',
              color: 'var(--color-gold)',
              cursor: busy ? 'wait' : 'pointer',
            }}
          >
            {busy
              ? t('prison_phase8.activity_panel.consume_progress')
              : t('prison_phase8.activity_panel.consume_yes')}
          </button>
          <button
            onClick={onClose}
            disabled={busy}
            className="py-2 rounded font-bold text-[11px] uppercase tracking-[.1em] disabled:opacity-50"
            style={{
              background: 'rgba(255,255,255,0.05)',
              border: '1px solid rgba(255,255,255,0.15)',
              color: 'var(--text-muted)',
              cursor: busy ? 'wait' : 'pointer',
            }}
          >
            {t('prison_phase8.activity_panel.consume_no')}
          </button>
        </div>
      </div>
    </div>,
    document.body,
  );
}
