'use client';

import { useEffect, useState, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { Plane, X } from 'lucide-react';
import { api } from '@/lib/api';

/**
 * Phase 12 (2026-04-20) — Vacances 72h.
 *
 * Rendu :
 *   - Bouton flottant bas-droit "Partir en vacances" (toujours visible si non-vacances)
 *   - Modal confirmation au clic
 *   - Modal reprise automatique à la reconnexion :
 *       • si timer écoulé → "J'espère que vous en avez bien profité" + OK
 *       • si anticipé → "Déjà de retour ? Oui / Non (poursuit timer)"
 *
 * Le composant gère lui-même son poll status via api.vacation.status() au mount.
 */
export function VacationControl() {
  const [status, setStatus] = useState<{
    is_on_vacation: boolean;
    resumes_at: string | null;
    started_at: string | null;
  } | null>(null);
  const [mode, setMode] = useState<'idle' | 'confirm_start' | 'modal_early' | 'modal_done'>('idle');
  const [busy, setBusy] = useState(false);

  const refresh = useCallback(async () => {
    try {
      const s = await api.vacation.status();
      setStatus(s);
      if (s.is_on_vacation) {
        // Vérifie si timer écoulé
        if (s.resumes_at && new Date(s.resumes_at).getTime() <= Date.now()) {
          setMode('modal_done');
        } else {
          // Toujours en vacances — propose reprise anticipée
          setMode('modal_early');
        }
      } else {
        setMode('idle');
      }
    } catch {
      setStatus(null);
    }
  }, []);

  useEffect(() => {
    refresh();
    const interval = setInterval(refresh, 60_000); // re-check toutes les minutes
    return () => clearInterval(interval);
  }, [refresh]);

  const startVacation = async () => {
    setBusy(true);
    try {
      await api.vacation.start();
      await refresh();
    } catch (e: any) { alert(e?.message || 'Erreur'); }
    finally { setBusy(false); }
  };

  const resumeVacation = async (early: boolean) => {
    setBusy(true);
    try {
      const r = await api.vacation.resume(early);
      if (r.resumed) {
        setMode('idle');
        await refresh();
      }
    } catch (e: any) { alert(e?.message || 'Erreur'); }
    finally { setBusy(false); }
  };

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

  return (
    <>
      {/* Phase 16 (2026-04-21) : bouton inline dans SidebarLeft panel Profil (plus flottant).
          Style aligné sur les autres CTAs gold du projet. */}
      {mode === 'idle' && (
        <button
          type="button"
          onClick={() => setMode('confirm_start')}
          className="w-full py-2 rounded-lg text-[11px] font-bold flex items-center justify-center gap-2 transition"
          style={{
            color: 'var(--bg-panel)',
            background: 'linear-gradient(180deg, var(--color-gold-light), var(--color-gold))',
            letterSpacing: '.12em',
            maxWidth: 'max-content',
            margin: '0 auto',
            padding: '11px',
          }}
          title="Mettre le compte sur pause 72h"
        >
          <Plane size={12} />
          PARTIR EN VACANCES (72H)
        </button>
      )}

      {/* Modal confirmation départ */}
      {mode === 'confirm_start' && createPortal(
        <div className="fixed inset-0 z-[2100] flex items-center justify-center" style={{ background: 'rgba(0,0,0,0.6)' }}>
          <div className="w-[92vw] max-w-[460px] rounded-2xl p-5"
            style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)' }}>
            <div className="flex items-center justify-between mb-3">
              <p className="text-sm font-bold" style={{ color: 'var(--text-primary)' }}>
                <Plane size={14} className="inline mr-2" /> Partir en vacances
              </p>
              <button onClick={() => setMode('idle')} className="opacity-60 hover:opacity-100">
                <X size={16} />
              </button>
            </div>
            <p className="text-[12px] mb-4" style={{ color: 'var(--text-secondary)' }}>
              Votre compte est mis sur pause durant <b>72h</b>. Pendant ce temps :
            </p>
            <ul className="text-[11px] mb-4 space-y-1 pl-5 list-disc" style={{ color: 'var(--text-secondary)' }}>
              <li>Aucune action possible sur la carte ou en mission</li>
              <li>Personne ne peut vous attaquer</li>
              <li>Votre chaleur retombe à 0 temporairement</li>
              <li>Votre chaleur d'origine est restaurée au retour</li>
            </ul>
            <div className="flex gap-2 justify-end">
              <button type="button" onClick={() => setMode('idle')}
                className="px-3 py-1.5 rounded-lg text-[11px]"
                style={{ background: 'rgba(255,255,255,0.06)', color: 'var(--text-secondary)' }}>
                Annuler
              </button>
              <button type="button" onClick={startVacation} disabled={busy}
                className="px-3 py-1.5 rounded-lg text-[11px] font-bold disabled:opacity-50"
                style={{ background: '#0ea5e9', color: '#fff' }}>
                Partir
              </button>
            </div>
          </div>
        </div>,
        document.body,
      )}

      {/* Modal timer écoulé — "J'espère que vous en avez bien profité" */}
      {mode === 'modal_done' && createPortal(
        <div className="fixed inset-0 z-[2100] flex items-center justify-center" style={{ background: 'rgba(0,0,0,0.6)' }}>
          <div className="w-[92vw] max-w-[400px] rounded-2xl p-5"
            style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)' }}>
            <p className="text-sm font-bold mb-3" style={{ color: 'var(--text-primary)' }}>
              🌴 J'espère que vous en avez bien profité
            </p>
            <p className="text-[12px] mb-4" style={{ color: 'var(--text-secondary)' }}>
              La partie reprend ! Votre chaleur a été restaurée à sa valeur d'origine.
            </p>
            <button type="button" onClick={() => resumeVacation(false)} disabled={busy}
              className="w-full px-3 py-2 rounded-lg text-[12px] font-bold disabled:opacity-50"
              style={{ background: '#0ea5e9', color: '#fff' }}>
              OK, reprendre
            </button>
          </div>
        </div>,
        document.body,
      )}

      {/* Modal reconnexion anticipée — "Déjà de retour ?" */}
      {mode === 'modal_early' && status?.resumes_at && createPortal(
        <div className="fixed inset-0 z-[2100] flex items-center justify-center" style={{ background: 'rgba(0,0,0,0.6)' }}>
          <div className="w-[92vw] max-w-[400px] rounded-2xl p-5"
            style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)' }}>
            <p className="text-sm font-bold mb-3" style={{ color: 'var(--text-primary)' }}>
              ✈ Déjà de retour ?
            </p>
            <p className="text-[12px] mb-2" style={{ color: 'var(--text-secondary)' }}>
              Vos vacances se terminent {new Date(status.resumes_at).toLocaleString('fr-FR')}.
            </p>
            <p className="text-[12px] mb-4" style={{ color: 'var(--text-secondary)' }}>
              Voulez-vous reprendre la partie maintenant ?
            </p>
            <div className="flex gap-2">
              <button type="button" onClick={() => resumeVacation(true)} disabled={busy}
                className="flex-1 px-3 py-2 rounded-lg text-[12px] font-bold disabled:opacity-50"
                style={{ background: '#0ea5e9', color: '#fff' }}>
                Oui, reprendre
              </button>
              <button type="button" onClick={() => setMode('idle')}
                className="flex-1 px-3 py-2 rounded-lg text-[12px]"
                style={{ background: 'rgba(255,255,255,0.06)', color: 'var(--text-secondary)' }}>
                Non, continuer
              </button>
            </div>
          </div>
        </div>,
        document.body,
      )}
    </>
  );
}
