'use client';

/**
 * Phase 7 (2026-04-29) — Lightbox porte-document au jugement.
 *
 * Le joueur DÉCIDE de présenter ou non un item judiciaire (manuel, pas auto-court-circuit).
 * Items utilisables au jugement :
 *   - Alibi : libération directe
 *   - Jurisprudence : libération directe
 *   - Vice de procédure : libération aléatoire 5-45 min
 * (Grâce / Appel : prison-only, pas listés ici.)
 *
 * Phase 7 i18n (2026-04-29) — toutes les strings via t()/tFmt().
 * Note : item_subtype reste 'Alibi'/'Jurisprudence'/'Vice de procédure' (clé
 * métier backend). Le label affiché vient de judicial.items.<key>.name.
 */
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { api } from '@/lib/api';
import { t, tFmt } from '@/lib/i18n';
import { FileText, X, ShieldCheck, Scale, BookOpen } from 'lucide-react';

interface JudicialPorteDocumentProps {
  recordId: string;
  onClose: () => void;
  onResult: (flavor: string) => void;
}

interface InventoryDoc {
  id: string;
  item_subtype: string;
  uses_remaining: number;
  quantity: number;
}

const JUGEMENT_ITEMS = ['Alibi', 'Jurisprudence', 'Vice de procédure'] as const;
type JugementItem = typeof JUGEMENT_ITEMS[number];

const ITEM_META: Record<JugementItem, { icon: any; color: string; i18nKey: string }> = {
  'Alibi':              { icon: ShieldCheck, color: '#86efac', i18nKey: 'alibi' },
  'Jurisprudence':      { icon: BookOpen,    color: '#86efac', i18nKey: 'jurisprudence' },
  'Vice de procédure':  { icon: Scale,       color: '#fbbf24', i18nKey: 'vice_procedure' },
};

export function JudicialPorteDocument({ recordId, onClose, onResult }: JudicialPorteDocumentProps) {
  const [docs, setDocs] = useState<InventoryDoc[]>([]);
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    api.allocation.myInventory()
      .then((items: any[]) => {
        const eligible = (Array.isArray(items) ? items : [])
          .filter((it: any) =>
            it?.id
            && it.item_type === 'document'
            && JUGEMENT_ITEMS.includes(it.item_subtype as JugementItem)
            && (it.uses_remaining ?? 1) > 0,
          )
          .map((it: any) => ({
            id: it.id,
            item_subtype: it.item_subtype,
            uses_remaining: it.uses_remaining ?? 1,
            quantity: it.quantity ?? 1,
          }));
        setDocs(eligible);
      })
      .catch((e: any) => setError(e?.message || t('judicial.porte_doc.inventory_error')))
      .finally(() => setLoading(false));
  }, []);

  const useItem = async (subtype: JugementItem) => {
    const itemLabel = t(`judicial.items.${ITEM_META[subtype].i18nKey}.name`);
    if (!confirm(tFmt('judicial.porte_doc.confirm', { item: itemLabel }))) return;
    setBusy(subtype);
    setError(null);
    try {
      const r = await api.judicialFlow.useItem(recordId, subtype);
      onResult(r.flavor);
    } catch (e: any) {
      setError(e?.message || t('judicial.porte_doc.use_error'));
    } finally {
      setBusy(null);
    }
  };

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

  return createPortal(
    <div
      className="fixed inset-0 z-[10001] 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 max-h-[80vh] overflow-y-auto"
        style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)' }}
      >
        <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">
          <FileText size={16} style={{ color: '#86efac' }} />
          <h2 className="font-gothic text-base" style={{ color: '#86efac' }}>{t('judicial.porte_doc.title')}</h2>
        </div>
        <p className="text-[10px] italic mb-3" style={{ color: 'var(--text-secondary)' }}>
          {t('judicial.porte_doc.intro')}
        </p>

        {loading ? (
          <p className="text-[11px]" style={{ color: 'var(--text-muted)' }}>{t('judicial.porte_doc.loading')}</p>
        ) : docs.length === 0 ? (
          <p className="text-[11px] italic" style={{ color: 'var(--text-muted)' }}>
            {t('judicial.porte_doc.empty')}
          </p>
        ) : (
          <div className="space-y-2">
            {docs.map((doc) => {
              const meta = ITEM_META[doc.item_subtype as JugementItem];
              const Icon = meta?.icon || FileText;
              const itemName = t(`judicial.items.${meta.i18nKey}.name`);
              const itemDesc = t(`judicial.items.${meta.i18nKey}.desc`);
              return (
                <div
                  key={doc.id}
                  className="p-3 rounded"
                  style={{ background: 'rgba(255,255,255,0.03)', border: `1px solid ${meta.color}40` }}
                >
                  <div className="flex items-center gap-2 mb-1">
                    <Icon size={12} style={{ color: meta.color }} />
                    <span className="text-[11px] font-bold" style={{ color: 'var(--text-primary)' }}>
                      {itemName}
                    </span>
                    <span className="ml-auto text-[9px]" style={{ color: 'var(--text-muted)' }}>
                      {tFmt('judicial.porte_doc.uses_remaining', { count: doc.uses_remaining })}
                    </span>
                  </div>
                  <p className="text-[9px] mb-2" style={{ color: 'var(--text-secondary)' }}>{itemDesc}</p>
                  <button
                    onClick={() => useItem(doc.item_subtype as JugementItem)}
                    disabled={!!busy}
                    className="w-full py-1.5 rounded text-[10px] font-bold uppercase tracking-[.1em] disabled:opacity-50"
                    style={{
                      background: `linear-gradient(135deg, ${meta.color}40, rgba(14,14,22,0.7))`,
                      border: `1px solid ${meta.color}60`,
                      color: meta.color,
                      cursor: 'pointer',
                    }}>
                    {busy === doc.item_subtype ? t('judicial.porte_doc.use_progress') : t('judicial.porte_doc.use_button')}
                  </button>
                </div>
              );
            })}
          </div>
        )}

        {error && (
          <p className="text-[11px] mt-2" style={{ color: 'var(--color-red-light)' }}>{error}</p>
        )}
      </div>
    </div>,
    document.body,
  );
}
