'use client';

/**
 * Phase 8 Session 2C (2026-04-27) — Modal parloir.
 * Sélectionne items à transférer au prisonnier (cigarettes, drogues, docs
 * judiciaires Grâce/Vice/Appel/Alibi/Jurisprudence). Submit → POST visit.
 * 25% risque gaulé (visiteur incarcéré 24h + items saisis).
 *
 * Phase 7 i18n (2026-04-29) — toutes les strings via t()/tFmt().
 */
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { X, Package, AlertTriangle } from 'lucide-react';
import { api } from '@/lib/api';
import { t, tFmt } from '@/lib/i18n';

interface InventoryItem {
  id: string;
  item_type: string;
  item_subtype: string;
  quantity: number;
  uses_remaining?: number | null;
}

interface ParloirModalProps {
  inmate: { player_id: string; username: string; character_name: string | null };
  onClose: () => void;
  onDone: () => void;
}

const ELIGIBLE_TYPES = new Set(['drug', 'document']);
const ELIGIBLE_SUBTYPES_DOCUMENT = new Set([
  'Grâce présidentielle', 'Vice de procédure', 'Appel accordé',
  'Alibi', 'Jurisprudence',
]);
const ELIGIBLE_SUBTYPES_OTHER = new Set([
  'cigarettes_paquet', 'cigarettes',
]);

export function ParloirModal({ inmate, onClose, onDone }: ParloirModalProps) {
  const [inv, setInv] = useState<InventoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<any | null>(null);
  // Map inventory_id -> quantity selected
  const [selected, setSelected] = useState<Record<string, number>>({});

  useEffect(() => {
    api.allocation.myInventory()
      .then((items: any[]) => {
        const eligible = (Array.isArray(items) ? items : []).filter((it: any) => {
          if (!it?.id) return false;
          if (ELIGIBLE_TYPES.has(it.item_type) && it.item_type === 'drug') return true;
          if (it.item_type === 'document' && ELIGIBLE_SUBTYPES_DOCUMENT.has(it.item_subtype)) return true;
          if (ELIGIBLE_SUBTYPES_OTHER.has(it.item_subtype)) return true;
          return false;
        });
        setInv(eligible);
      })
      .catch((e: any) => setError(e?.message || t('prison_phase8.parloir.load_error')))
      .finally(() => setLoading(false));
  }, []);

  const setQty = (id: string, qty: number, max: number) => {
    const v = Math.max(0, Math.min(qty, max));
    setSelected((prev) => {
      const next = { ...prev };
      if (v <= 0) delete next[id];
      else next[id] = v;
      return next;
    });
  };

  const totalSelected = Object.values(selected).reduce((sum, n) => sum + n, 0);
  const inmateName = inmate.character_name || inmate.username;

  const submit = async () => {
    if (totalSelected === 0) {
      setError(t('prison_phase8.parloir.select_at_least_one'));
      return;
    }
    if (!confirm(tFmt('prison_phase8.parloir.confirm_message', { count: totalSelected }))) return;

    setSubmitting(true);
    setError(null);
    try {
      const items = Object.entries(selected).map(([inventory_id, quantity]) => ({ inventory_id, quantity }));
      const res = await api.prisonExtras.visitParloir(inmate.player_id, items);
      setResult(res);
    } catch (e: any) {
      setError(e?.message || t('prison_phase8.parloir.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.7)' }}
      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">
          <Package size={16} style={{ color: '#86efac' }} />
          <h2 className="font-gothic text-base" style={{ color: '#86efac' }}>{t('prison_phase8.parloir.title')}</h2>
        </div>
        <p className="text-[11px] mb-3" style={{ color: 'var(--text-secondary)' }}>
          {tFmt('prison_phase8.parloir.desc', { name: inmateName })}
        </p>

        {result ? (
          <div
            className="p-3 rounded mb-3"
            style={{
              background: result.caught ? 'rgba(239,68,68,0.12)' : 'rgba(34,197,94,0.12)',
              border: `1px solid ${result.caught ? 'rgba(239,68,68,0.5)' : 'rgba(34,197,94,0.5)'}`,
              color: result.caught ? '#fca5a5' : '#86efac',
            }}>
            <div className="text-[12px] font-bold mb-1">
              {result.caught ? t('prison_phase8.parloir.result_caught') : t('prison_phase8.parloir.result_success')}
            </div>
            <p className="text-[10px] italic">« {result.flavor} »</p>
            {!result.caught && result.transferred_count > 0 && (
              <p className="text-[10px] mt-2">{tFmt('prison_phase8.parloir.result_received', { count: result.transferred_count })}</p>
            )}
            <button
              onClick={() => onDone()}
              className="mt-3 w-full py-2 rounded text-[11px] font-bold"
              style={{
                background: 'linear-gradient(135deg, var(--color-gold-dark), var(--color-gold))',
                color: '#000',
              }}>
              {t('prison_phase8.parloir.close')}
            </button>
          </div>
        ) : (
          <>
            {loading ? (
              <p className="text-[11px]" style={{ color: 'var(--text-muted)' }}>{t('prison_phase8.parloir.loading')}</p>
            ) : inv.length === 0 ? (
              <p className="text-[11px] italic" style={{ color: 'var(--text-muted)' }}>
                {t('prison_phase8.parloir.empty')}
              </p>
            ) : (
              <div className="space-y-1.5 mb-3">
                {inv.map((it) => (
                  <div key={it.id} className="flex items-center gap-2 p-2 rounded"
                    style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
                    <div className="flex-1 min-w-0">
                      <div className="text-[11px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>
                        {it.item_subtype}
                      </div>
                      <div className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                        {tFmt('prison_phase8.parloir.stock', { qty: it.quantity })}
                        {it.uses_remaining != null ? tFmt('prison_phase8.parloir.uses_suffix', { count: it.uses_remaining }) : ''}
                      </div>
                    </div>
                    <input
                      type="number"
                      min={0}
                      max={it.quantity}
                      value={selected[it.id] ?? 0}
                      onChange={(e) => setQty(it.id, Number(e.target.value) || 0, it.quantity)}
                      className="w-16 px-2 py-1 rounded text-[11px]"
                      style={{
                        background: 'var(--bg-primary)',
                        border: '1px solid var(--border-subtle)',
                        color: 'var(--text-primary)',
                      }}
                    />
                  </div>
                ))}
              </div>
            )}

            <div className="p-2 rounded text-[9px] flex items-start gap-1 mb-3"
              style={{ background: 'rgba(239,68,68,0.06)', border: '1px solid rgba(239,68,68,0.2)', color: 'var(--text-secondary)' }}>
              <AlertTriangle size={10} style={{ color: '#fca5a5', marginTop: 1 }} />
              <span>{t('prison_phase8.parloir.warning')}</span>
            </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 || totalSelected === 0 || inv.length === 0}
                className="flex-1 py-2 rounded font-bold text-[11px] uppercase tracking-[.1em] disabled:opacity-50"
                style={{
                  background: 'linear-gradient(135deg, rgba(34,197,94,0.4), rgba(14,14,22,0.9))',
                  border: '1px solid rgba(34,197,94,0.6)',
                  color: '#86efac',
                  cursor: 'pointer',
                }}>
                {submitting
                  ? t('prison_phase8.parloir.submit_progress')
                  : tFmt('prison_phase8.parloir.submit', { count: totalSelected })}
              </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.parloir.cancel')}
              </button>
            </div>
          </>
        )}
      </div>
    </div>,
    document.body,
  );
}
