'use client';
/**
 * MessageComposer — lightbox composition message joueur-à-joueur.
 * Style aligné avec les autres lightboxes projet (BaseLightbox pattern).
 *
 * Pré-rempli avec un destinataire donné (ex: admin d'un cartel pour contact
 * post-proposition d'alliance). Utilise POST /api/player/:senderId/messages.
 */
import { useState, useEffect } from 'react';
import { apiFetch } from '@/lib/api';
import { useGameStore } from '@/stores/gameStore';

export function MessageComposer({
  recipientId, recipientName, defaultSubject, context, onClose,
}: {
  recipientId: string;
  recipientName: string;
  defaultSubject?: string;
  /** Phase 16 (2026-04-22) — si 'alliance', le backend crée une notif `alliance_message`
   *  pour le destinataire au lieu d'une notif générique. */
  context?: 'alliance' | 'general';
  onClose: () => void;
}) {
  const player = useGameStore((s) => s.player);
  const [subject, setSubject] = useState(defaultSubject || '');
  const [content, setContent] = useState('');
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);

  useEffect(() => {
    const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [onClose]);

  const handleSend = async () => {
    if (!subject.trim() || !content.trim() || !player?.id) return;
    setSending(true);
    try {
      await apiFetch(`/api/player/${player.id}/messages`, {
        method: 'POST',
        body: JSON.stringify({
          recipient_id: recipientId,
          subject,
          content,
          ...(context ? { context } : {}),
        }),
      });
      setSent(true);
      setTimeout(onClose, 1500);
    } catch (e: any) {
      alert(e?.message || 'Envoi impossible');
    } finally {
      setSending(false);
    }
  };

  return (
    <div
      className="fixed inset-0 z-[4000] flex items-center justify-center p-4"
      style={{ background: 'rgba(0,0,0,0.72)' }}
      onClick={onClose}
    >
      <div
        className="rounded-2xl overflow-hidden w-full"
        style={{
          maxWidth: 520,
          background: 'var(--bg-panel)',
          border: '1px solid var(--border-dark)',
          boxShadow: '0 20px 80px rgba(0,0,0,0.6)',
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <div
          className="px-4 py-3 flex justify-between items-center"
          style={{
            borderBottom: '1px solid var(--border-dark)',
            background: 'linear-gradient(180deg, rgba(212,168,67,0.05), rgba(0,0,0,0))',
          }}
        >
          <p
            className="text-[13px] font-bold"
            style={{ color: 'var(--color-gold-light)', fontFamily: 'var(--font-subtitle)', letterSpacing: '.15em' }}
          >
            NOUVEAU MESSAGE
          </p>
          <button
            onClick={onClose}
            className="text-lg leading-none opacity-60 hover:opacity-100"
            style={{ color: 'var(--text-primary)' }}
          >×</button>
        </div>

        <div className="p-5 space-y-3" style={{ color: 'var(--text-secondary)', fontSize: 12, lineHeight: 1.6 }}>
          <div className="flex items-center gap-2 px-3 py-2 rounded" style={{ background: 'rgba(212,168,67,0.07)', border: '1px solid rgba(212,168,67,0.2)' }}>
            <span className="text-[10px]" style={{ color: 'var(--text-muted)', letterSpacing: '.1em' }}>DESTINATAIRE</span>
            <span className="text-[12px] font-bold" style={{ color: 'var(--color-gold)' }}>{recipientName}</span>
          </div>

          <input
            type="text"
            placeholder="Sujet"
            value={subject}
            onChange={(e) => setSubject(e.target.value)}
            maxLength={100}
            disabled={sent}
            className="w-full px-3 py-2 text-xs rounded"
            style={{
              background: 'rgba(255,255,255,0.03)',
              color: 'var(--text-primary)',
              border: '1px solid var(--border-dark)',
            }}
          />

          <textarea
            placeholder="Votre message…"
            value={content}
            onChange={(e) => setContent(e.target.value)}
            maxLength={2000}
            disabled={sent}
            rows={6}
            className="w-full px-3 py-2 text-xs rounded resize-none"
            style={{
              background: 'rgba(255,255,255,0.03)',
              color: 'var(--text-primary)',
              border: '1px solid var(--border-dark)',
            }}
          />

          <div className="flex justify-between items-center pt-1">
            <span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{content.length}/2000</span>
            <div className="flex gap-2">
              <button
                type="button"
                onClick={onClose}
                className="px-3 py-1.5 text-[11px] rounded"
                style={{ color: 'var(--text-muted)', border: '1px solid var(--border-dark)' }}
              >
                Annuler
              </button>
              <button
                type="button"
                onClick={handleSend}
                disabled={sending || sent || !subject.trim() || !content.trim()}
                className="px-4 py-1.5 text-[11px] font-bold rounded disabled:opacity-40 transition"
                style={{
                  color: sent ? '#fff' : 'var(--bg-panel)',
                  background: sent ? '#16a34a' : 'var(--color-gold)',
                  letterSpacing: '.1em',
                }}
              >
                {sent ? '✓ ENVOYÉ' : sending ? 'ENVOI…' : 'ENVOYER'}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
