'use client';

/**
 * GarageRentalsPanel — Phase 17.2 finition (2026-05-06).
 *
 * Vue centralisée des locations de garage actives du joueur. Avant ce panel,
 * le joueur louait un emplacement (clic-droit véhicule sur carte → "Garer au
 * garage") mais n'avait aucune visibilité sur ses contrats en cours : combien
 * il payait par jour, depuis quand, où était garé chaque véhicule. Pas
 * d'endroit pour résilier non plus.
 *
 * Ce panel résout ça :
 *   • Liste les contrats avec status='active' via api.garageRental.mine()
 *   • Affiche : nom garage, nom véhicule, loyer/jour, jours écoulés, total approx
 *   • Total cumulé en tête (somme des loyers quotidiens, sans HT)
 *   • Bouton ✕ Résilier (par contrat) qui appelle api.garageRental.end(id)
 *
 * Monté dans /account → tab "Mes Garages".
 */
import { useCallback, useEffect, useState } from 'react';
import { api } from '@/lib/api';

type Rental = Awaited<ReturnType<typeof api.garageRental.mine>>[number];

function daysSince(iso: string): number {
  return Math.floor((Date.now() - new Date(iso).getTime()) / (24 * 60 * 60 * 1000));
}

export function GarageRentalsPanel() {
  const [rentals, setRentals] = useState<Rental[]>([]);
  const [loading, setLoading] = useState(true);
  const [busyId, setBusyId] = useState<string | null>(null);
  const [err, setErr] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    setLoading(true);
    setErr(null);
    try {
      const data = await api.garageRental.mine();
      setRentals(Array.isArray(data) ? data : []);
    } catch (e) {
      setErr(e instanceof Error ? e.message : 'Erreur chargement');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { refresh(); }, [refresh]);

  const handleEnd = async (id: string) => {
    if (!confirm('Résilier cette location ? Le véhicule reste sur place mais le loyer s\'arrête.')) return;
    setBusyId(id);
    setErr(null);
    try {
      await api.garageRental.end(id);
      await refresh();
    } catch (e) {
      setErr(e instanceof Error ? e.message : 'Échec résiliation');
    } finally {
      setBusyId(null);
    }
  };

  const totalDailyCost = rentals.reduce((sum, r) => sum + Number(r.daily_rent_light || 0), 0);

  if (loading) {
    return <p className="text-xs" style={{ color: 'var(--text-muted)' }}>Chargement…</p>;
  }

  return (
    <div className="space-y-4">
      <div className="rounded-lg p-3" style={{
        background: 'rgba(212,168,67,0.05)',
        border: '1px solid rgba(212,168,67,0.2)',
      }}>
        <p className="text-xs font-bold mb-1" style={{ color: 'var(--color-gold-light)' }}>
          Locations de garage actives
        </p>
        <p className="text-[11px]" style={{ color: 'var(--text-secondary)', lineHeight: 1.4 }}>
          Tes véhicules stockés contre un loyer quotidien (5–35 ∞ lumière). Le débit
          est automatique chaque 24 h. Résilie pour arrêter le débit (le véhicule reste
          au garage jusqu&apos;à ce que tu reviennes le chercher).
        </p>
      </div>

      {err && (
        <div className="rounded p-2 text-xs" style={{
          background: 'rgba(239,68,68,0.1)',
          border: '1px solid rgba(239,68,68,0.3)',
          color: '#ef4444',
        }}>
          {err}
        </div>
      )}

      {rentals.length === 0 && !err && (
        <div className="rounded-lg p-3" style={{
          background: 'rgba(107,114,128,0.08)',
          border: '1px solid rgba(107,114,128,0.2)',
        }}>
          <p className="text-xs italic" style={{ color: 'var(--text-secondary)' }}>
            Aucune location active. Pour stocker un véhicule, fais un clic droit dessus sur la carte
            et choisis « Garer au garage (louer) ».
          </p>
        </div>
      )}

      {rentals.length > 0 && (
        <>
          <div className="rounded p-2 flex items-center justify-between" style={{
            background: 'rgba(255,255,255,0.03)',
            border: '1px solid var(--border-dark)',
          }}>
            <span className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
              {rentals.length} location{rentals.length > 1 ? 's' : ''}
            </span>
            <span className="text-xs font-bold" style={{ color: 'var(--color-gold-light)' }}>
              Total : {totalDailyCost.toLocaleString('fr-FR')} ∞ lumière/jour
            </span>
          </div>

          <div className="space-y-2">
            {rentals.map((r) => {
              const days = daysSince(r.started_at);
              const totalPaid = days * Number(r.daily_rent_light || 0);
              return (
                <div
                  key={r.id}
                  className="rounded-lg p-3"
                  style={{
                    background: 'rgba(255,255,255,0.02)',
                    border: '1px solid var(--border-dark)',
                  }}
                >
                  <div className="flex items-start justify-between gap-2">
                    <div className="min-w-0 flex-1">
                      <div className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>
                        🚗 {r.vehicle?.name ?? '(véhicule)'}
                      </div>
                      <div className="text-[11px] mt-0.5" style={{ color: 'var(--text-secondary)' }}>
                        🏢 {r.business?.name ?? '(garage)'}
                      </div>
                      <div className="text-[10px] mt-1" style={{ color: 'var(--text-muted)' }}>
                        Depuis le {new Date(r.started_at).toLocaleDateString('fr-FR')} · {days} jour{days > 1 ? 's' : ''}
                      </div>
                    </div>
                    <div className="text-right shrink-0">
                      <div className="text-[11px] font-bold" style={{ color: 'var(--color-gold-light)' }}>
                        {Number(r.daily_rent_light).toLocaleString('fr-FR')} ∞/j
                      </div>
                      <div className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                        ≈ {totalPaid.toLocaleString('fr-FR')} ∞ payés
                      </div>
                    </div>
                  </div>
                  <div className="mt-2 flex justify-end">
                    <button
                      type="button"
                      disabled={busyId === r.id}
                      onClick={() => handleEnd(r.id)}
                      className="text-[10px] px-2 py-1 rounded"
                      style={{
                        background: 'rgba(239,68,68,0.15)',
                        border: '1px solid rgba(239,68,68,0.4)',
                        color: '#ef4444',
                        opacity: busyId === r.id ? 0.5 : 1,
                      }}
                    >
                      {busyId === r.id ? '…' : '✕ Résilier'}
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        </>
      )}
    </div>
  );
}
