'use client';

import { useEffect, useState } from 'react';
import { api } from '@/lib/api';

/**
 * Phase 15 v2 (2026-04-22, refonte UI 2026-05-05) — gère les 3 événements
 * dispatchés depuis MapContextMenu quand on clique-droit un véhicule :
 *   - 'carjack-start'       → voler le véhicule (combat si conducteur)
 *   - 'recovery-start'      → lancer une mission de récupération avec équipe
 *   - 'open-garage-rental'  → louer un garage de stockage à proximité
 *
 * Lightbox propre avec sélecteurs (gangsters, véhicules, garages) — plus de
 * saisie d'UUID à la main.
 */
type VehicleLite = {
  id: string;
  name: string;
  speed: number;
  condition: number;
  in_use: boolean;
  driven_by: string | null;
};

type GangMemberLite = {
  player_id: string;
  in_transit?: boolean | null;
  guarding_building_id?: string | null;
  hospitalized_until?: string | null;
  player?: {
    id: string;
    pseudo?: string | null;
    nickname?: string | null;
    name?: string | null;
  } | null;
};

type GarageNearby = {
  id: string;
  name: string;
  location_lat: number;
  location_lon: number;
  distance_km: number;
};

type RecoveryPreviewT = {
  scenario: 'accident' | 'abandoned' | 'stolen_return';
  distance_km: number;
  outbound_ms: number;
  return_ms: number;
};

type Mode =
  | { kind: 'idle' }
  | { kind: 'carjack'; vehicle_id: string }
  | {
      kind: 'recovery';
      vehicle_id: string;
      preview: RecoveryPreviewT | null;
      members: GangMemberLite[];
      vehicles: VehicleLite[];
      selectedTeam: Set<string>;
      outbound_vehicle_id: string;
      loadingPickers: boolean;
      pickerError: string | null;
    }
  | {
      kind: 'garage';
      vehicle_id: string;
      vehicleLat: number | null;
      vehicleLon: number | null;
      garages: GarageNearby[];
      selectedGarageId: string;
      daily: number;
      loadingPickers: boolean;
      pickerError: string | null;
    };

const SCENARIO_LABELS: Record<RecoveryPreviewT['scenario'], string> = {
  accident: 'Accidenté (réparation 50 % au retour)',
  abandoned: 'Abandonné — récupération simple',
  stolen_return: 'Volé par un rival — restauration de propriété',
};

function memberDisplay(m: GangMemberLite): string {
  const p = m.player;
  return (p?.nickname || p?.pseudo || p?.name || m.player_id.slice(0, 8)) ?? m.player_id.slice(0, 8);
}

function memberDisabledReason(m: GangMemberLite): string | null {
  if (m.in_transit) return 'en transit';
  if (m.guarding_building_id) return 'en garde';
  if (m.hospitalized_until && new Date(m.hospitalized_until) > new Date()) return 'hospitalisé';
  return null;
}

export function VehicleActionHandler() {
  const [mode, setMode] = useState<Mode>({ kind: 'idle' });
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<string | null>(null);

  useEffect(() => {
    const onCarjack = (e: Event) => {
      const detail = (e as CustomEvent).detail as { vehicle_id: string };
      if (!detail?.vehicle_id) return;
      setResult(null); setError(null);
      setMode({ kind: 'carjack', vehicle_id: detail.vehicle_id });
    };

    const onRecovery = async (e: Event) => {
      const detail = (e as CustomEvent).detail as { vehicle_id: string };
      if (!detail?.vehicle_id) return;
      setResult(null); setError(null);
      setMode({
        kind: 'recovery',
        vehicle_id: detail.vehicle_id,
        preview: null,
        members: [],
        vehicles: [],
        selectedTeam: new Set(),
        outbound_vehicle_id: '',
        loadingPickers: true,
        pickerError: null,
      });

      try {
        const [preview, gang, myVehicles] = await Promise.all([
          api.recovery.preview(detail.vehicle_id).catch((err) => { throw err; }),
          api.gang.getMy().catch(() => null),
          api.allocation.myVehicles().catch(() => [] as unknown[]),
        ]);
        const members = ((gang as { members?: GangMemberLite[] } | null)?.members ?? []);
        const vehicles = (myVehicles as VehicleLite[]).filter((v) => !v.in_use);
        setMode((m) => m.kind === 'recovery'
          ? { ...m, preview: preview as RecoveryPreviewT, members, vehicles, loadingPickers: false }
          : m);
      } catch (err: any) {
        setMode((m) => m.kind === 'recovery'
          ? { ...m, loadingPickers: false, pickerError: err?.message || 'Aperçu indisponible' }
          : m);
      }
    };

    const onGarage = async (e: Event) => {
      const detail = (e as CustomEvent).detail as {
        vehicle_id: string;
        lat?: number;
        lon?: number;
      };
      if (!detail?.vehicle_id) return;
      setResult(null); setError(null);
      setMode({
        kind: 'garage',
        vehicle_id: detail.vehicle_id,
        vehicleLat: detail.lat ?? null,
        vehicleLon: detail.lon ?? null,
        garages: [],
        selectedGarageId: '',
        daily: 10,
        loadingPickers: true,
        pickerError: null,
      });

      // Fallback : on cherche le véhicule dans la liste perso pour avoir ses coords.
      try {
        let lat = detail.lat;
        let lon = detail.lon;
        if (lat == null || lon == null) {
          const myVehicles = (await api.allocation.myVehicles().catch(() => [])) as Array<
            VehicleLite & { current_lat: number | null; current_lon: number | null }
          >;
          const v = myVehicles.find((vv) => vv.id === detail.vehicle_id);
          lat = v?.current_lat ?? undefined;
          lon = v?.current_lon ?? undefined;
        }
        if (lat == null || lon == null) {
          setMode((m) => m.kind === 'garage'
            ? { ...m, loadingPickers: false, pickerError: 'Position du véhicule inconnue — impossible de chercher un garage à proximité.' }
            : m);
          return;
        }
        const garages = await api.garageRental.nearby({ lat, lon, radius_km: 5 });
        setMode((m) => m.kind === 'garage'
          ? { ...m, garages, vehicleLat: lat ?? null, vehicleLon: lon ?? null, loadingPickers: false }
          : m);
      } catch (err: any) {
        setMode((m) => m.kind === 'garage'
          ? { ...m, loadingPickers: false, pickerError: err?.message || 'Garages à proximité indisponibles' }
          : m);
      }
    };

    window.addEventListener('carjack-start', onCarjack);
    window.addEventListener('recovery-start', onRecovery);
    window.addEventListener('open-garage-rental', onGarage);
    return () => {
      window.removeEventListener('carjack-start', onCarjack);
      window.removeEventListener('recovery-start', onRecovery);
      window.removeEventListener('open-garage-rental', onGarage);
    };
  }, []);

  const close = () => { setMode({ kind: 'idle' }); setBusy(false); setError(null); setResult(null); };

  const runCarjack = async () => {
    if (mode.kind !== 'carjack') return;
    setBusy(true); setError(null);
    try {
      const res = await api.carjack.carjack(mode.vehicle_id) as { message?: string } | undefined;
      setResult(res?.message || 'Carjack terminé');
    } catch (e: any) {
      setError(e?.message || 'Carjack impossible');
    } finally {
      setBusy(false);
    }
  };

  const runRecovery = async () => {
    if (mode.kind !== 'recovery') return;
    const team = Array.from(mode.selectedTeam);
    if (team.length === 0) {
      setError('Sélectionnez au moins 1 gangster pour l\'équipe');
      return;
    }
    if (team.length > 5) {
      setError('Maximum 5 gangsters');
      return;
    }
    setBusy(true); setError(null);
    try {
      const res = await api.recovery.initiate(mode.vehicle_id, {
        team_player_ids: team,
        outbound_vehicle_id: mode.outbound_vehicle_id || null,
      });
      const totalMin = Math.round(res.total_ms / 60000);
      setResult(`Mission lancée — retour dans ~${totalMin} min (arrivée ${new Date(res.scheduled_arrival_at).toLocaleTimeString()})`);
    } catch (e: any) {
      setError(e?.message || 'Mission impossible');
    } finally {
      setBusy(false);
    }
  };

  const runGarage = async () => {
    if (mode.kind !== 'garage') return;
    if (!mode.selectedGarageId) {
      setError('Sélectionnez un garage');
      return;
    }
    setBusy(true); setError(null);
    try {
      await api.garageRental.start({
        business_id: mode.selectedGarageId,
        vehicle_id: mode.vehicle_id,
        daily_rent_light: mode.daily,
      });
      setResult(`Véhicule stocké — loyer ${mode.daily} ∞ lumière/jour`);
    } catch (e: any) {
      setError(e?.message || 'Location impossible');
    } finally {
      setBusy(false);
    }
  };

  if (mode.kind === 'idle') return null;

  const inputStyle: React.CSSProperties = {
    width: '100%',
    padding: 8,
    margin: '4px 0 10px',
    background: 'var(--bg-primary,#0b0e14)',
    border: '1px solid var(--border-dark,#2a2f3a)',
    borderRadius: 6,
    color: 'inherit',
    fontSize: 13,
  };
  const labelStyle: React.CSSProperties = {
    fontSize: 11,
    color: 'var(--text-muted,#9ca3af)',
    display: 'block',
    marginTop: 6,
  };

  return (
    <div
      onClick={close}
      style={{
        position: 'fixed', inset: 0, zIndex: 3500,
        background: 'rgba(0,0,0,0.7)', display: 'flex',
        alignItems: 'center', justifyContent: 'center',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: 520,
          maxHeight: '88vh', overflowY: 'auto',
          background: 'var(--bg-panel, #141820)', color: 'var(--text-primary, #e5e7eb)',
          border: '1px solid var(--border-dark, #2a2f3a)', borderRadius: 12,
          padding: 20,
          fontSize: 13,
        }}
      >
        {mode.kind === 'carjack' && (
          <>
            <h3 style={{ margin: '0 0 8px', fontSize: 15 }}>Voler ce véhicule</h3>
            <p style={{ color: 'var(--text-muted)', marginBottom: 12, fontSize: 12 }}>
              Si un conducteur est présent, un combat s&apos;engage. Le vol est effectif immédiatement :
              le véhicule porte <code>is_stolen</code> pendant 48h (l&apos;ancien propriétaire peut
              tenter une récupération). Après, le vol devient définitif (+5 police_risk sur
              patrouille/visite, −5 sur braquage/attaque).
            </p>
          </>
        )}

        {mode.kind === 'recovery' && (
          <>
            <h3 style={{ margin: '0 0 8px', fontSize: 15 }}>Récupérer le véhicule</h3>

            {mode.preview ? (
              <div style={{ background: 'rgba(212,168,67,0.06)', border: '1px solid rgba(212,168,67,0.25)', borderRadius: 6, padding: 8, marginBottom: 10 }}>
                <div style={{ fontSize: 12, fontWeight: 600 }}>{SCENARIO_LABELS[mode.preview.scenario]}</div>
                <div style={{ fontSize: 11, color: 'var(--text-muted,#9ca3af)', marginTop: 2 }}>
                  Distance {mode.preview.distance_km.toFixed(1)} km · aller ~{Math.round(mode.preview.outbound_ms / 60000)} min · retour ~{Math.round(mode.preview.return_ms / 60000)} min
                </div>
              </div>
            ) : mode.loadingPickers ? (
              <p style={{ color: 'var(--text-muted)', marginBottom: 10 }}>Calcul de l&apos;aperçu…</p>
            ) : null}
            {mode.pickerError && (
              <p style={{ color: '#ef4444', fontSize: 12, marginBottom: 10 }}>{mode.pickerError}</p>
            )}

            <label style={labelStyle}>Équipe (1 à 5 gangsters)</label>
            <div style={{
              maxHeight: 180, overflowY: 'auto',
              background: 'var(--bg-primary,#0b0e14)',
              border: '1px solid var(--border-dark,#2a2f3a)',
              borderRadius: 6, padding: 6, marginBottom: 10,
            }}>
              {mode.loadingPickers ? (
                <div style={{ color: 'var(--text-muted,#9ca3af)', fontSize: 12, padding: 8 }}>Chargement…</div>
              ) : mode.members.length === 0 ? (
                <div style={{ color: 'var(--text-muted,#9ca3af)', fontSize: 12, padding: 8 }}>
                  Aucun gangster dans votre gang.
                </div>
              ) : mode.members.map((m) => {
                const reason = memberDisabledReason(m);
                const checked = mode.selectedTeam.has(m.player_id);
                return (
                  <label
                    key={m.player_id}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 8,
                      padding: '4px 6px', borderRadius: 4,
                      cursor: reason ? 'not-allowed' : 'pointer',
                      opacity: reason ? 0.5 : 1,
                      fontSize: 12,
                    }}
                  >
                    <input
                      type="checkbox"
                      checked={checked}
                      disabled={!!reason || (!checked && mode.selectedTeam.size >= 5)}
                      onChange={() => {
                        setMode((cur) => {
                          if (cur.kind !== 'recovery') return cur;
                          const next = new Set(cur.selectedTeam);
                          if (next.has(m.player_id)) next.delete(m.player_id);
                          else next.add(m.player_id);
                          return { ...cur, selectedTeam: next };
                        });
                      }}
                    />
                    <span style={{ flex: 1 }}>{memberDisplay(m)}</span>
                    {reason && <span style={{ color: 'var(--text-muted,#9ca3af)', fontSize: 11 }}>({reason})</span>}
                  </label>
                );
              })}
            </div>

            <label style={labelStyle}>Véhicule aller (optionnel — sinon à pied)</label>
            <select
              value={mode.outbound_vehicle_id}
              onChange={(e) =>
                setMode((cur) => cur.kind === 'recovery' ? { ...cur, outbound_vehicle_id: e.target.value } : cur)
              }
              style={inputStyle}
            >
              <option value="">— À pied —</option>
              {mode.vehicles.map((v) => (
                <option key={v.id} value={v.id}>
                  {v.name} ({v.speed} km/h, condition {v.condition}%)
                </option>
              ))}
            </select>
          </>
        )}

        {mode.kind === 'garage' && (
          <>
            <h3 style={{ margin: '0 0 8px', fontSize: 15 }}>Garer au garage</h3>
            <p style={{ color: 'var(--text-muted)', marginBottom: 12, fontSize: 12 }}>
              Loyer quotidien 5..35 ∞ lumière. Ponctionné chaque 24h. Contrat résilié auto si fonds manquants.
            </p>

            <label style={labelStyle}>Garage à proximité (rayon 5 km)</label>
            <select
              value={mode.selectedGarageId}
              onChange={(e) =>
                setMode((cur) => cur.kind === 'garage' ? { ...cur, selectedGarageId: e.target.value } : cur)
              }
              style={inputStyle}
              disabled={mode.loadingPickers || mode.garages.length === 0}
            >
              {mode.loadingPickers ? (
                <option value="">Recherche en cours…</option>
              ) : mode.garages.length === 0 ? (
                <option value="">Aucun garage de stockage à proximité</option>
              ) : (
                <>
                  <option value="">— Choisir —</option>
                  {mode.garages.map((g) => (
                    <option key={g.id} value={g.id}>
                      {g.name} ({g.distance_km.toFixed(1)} km)
                    </option>
                  ))}
                </>
              )}
            </select>
            {mode.pickerError && (
              <p style={{ color: '#ef4444', fontSize: 12, marginBottom: 10 }}>{mode.pickerError}</p>
            )}

            <label style={labelStyle}>
              Loyer quotidien : <strong>{mode.daily} ∞ lumière</strong>
            </label>
            <input
              type="range"
              min={5}
              max={35}
              step={1}
              value={mode.daily}
              onChange={(e) =>
                setMode((cur) => cur.kind === 'garage' ? { ...cur, daily: Number(e.target.value) } : cur)
              }
              style={{ width: '100%', margin: '4px 0 10px' }}
            />
          </>
        )}

        {error && <div style={{ color: '#ef4444', fontSize: 12, marginBottom: 10 }}>{error}</div>}
        {result && <div style={{ color: '#22c55e', fontSize: 12, marginBottom: 10 }}>{result}</div>}

        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button
            onClick={close}
            disabled={busy}
            style={{ padding: '6px 12px', background: 'transparent', border: '1px solid var(--border-dark,#2a2f3a)', color: 'var(--text-secondary,#9ca3af)', borderRadius: 6 }}
          >
            {result ? 'Fermer' : 'Annuler'}
          </button>
          {!result && (
            <button
              onClick={
                mode.kind === 'carjack' ? runCarjack
                : mode.kind === 'recovery' ? runRecovery
                : runGarage
              }
              disabled={busy || (mode.kind !== 'carjack' && (mode as { loadingPickers: boolean }).loadingPickers)}
              style={{ padding: '6px 16px', background: '#c89b3c', border: 'none', color: '#000', fontWeight: 700, borderRadius: 6, opacity: busy ? 0.6 : 1 }}
            >
              {busy ? '…' : mode.kind === 'carjack' ? 'Voler' : mode.kind === 'recovery' ? 'Lancer' : 'Louer'}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
