'use client';

import { useState, useMemo, useEffect } from 'react';
import { X, Package, Users, MapPin, Clock, AlertCircle, Check } from 'lucide-react';
import { api, apiFetch } from '@/lib/api';
import { useGameStore } from '@/stores/gameStore';

interface GangMemberLite {
  player_id: string;
  role: string;
  grade?: number;
  in_transit?: boolean;
  guarding_building_id?: string | null;
  assigned_racket_zone_id?: string | null;
  hospitalized_until?: string | null;
  hit_points?: number;
  player?: { username?: string; character_name?: string | null } | null;
}

interface DrugStock {
  item_name: string;
  quantity: number;
}

interface Props {
  gangId: string;
  members: GangMemberLite[];
  onClose: () => void;
  onCreated: () => void;
}

const DURATION_OPTIONS = [1, 2, 4, 8, 12, 24];
const RADIUS_OPTIONS = [0.5, 1, 2, 3, 5];

export function DealerMissionCreateModal({ gangId, members, onClose, onCreated }: Props) {
  const player = useGameStore((s) => s.player);
  const [step, setStep] = useState<'drug' | 'gangsters' | 'config' | 'confirm'>('drug');
  const [drugStocks, setDrugStocks] = useState<DrugStock[]>([]);
  const [loadingStocks, setLoadingStocks] = useState(true);
  const [selectedDrug, setSelectedDrug] = useState<string | null>(null);
  const [stockAmount, setStockAmount] = useState('');
  const [selectedGangsterIds, setSelectedGangsterIds] = useState<string[]>([]);
  const [radiusKm, setRadiusKm] = useState(2);
  const [durationHours, setDurationHours] = useState(4);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Fetch drug stocks on mount.
  // Phase 17 fix (2026-05-04) — bug : l'ancien endpoint
  // `/api/player/inventory?type=drug` n'existait pas (la route réelle est
  // `/api/player/:id/inventory`). De plus, la mission dealer est de scope
  // gang donc le stock doit venir de gang_stock (l'inventaire perso d'un
  // joueur ne sert pas pour cette mission). Nouveau endpoint dédié
  // `/api/gang/:id/drug-stocks` qui agrège par item_subtype.
  useEffect(() => {
    if (!gangId) return;
    setLoadingStocks(true);
    apiFetch<Array<{ item_name: string; quantity: number }>>(`/api/gang/${gangId}/drug-stocks`)
      .then((data) => {
        const items = Array.isArray(data) ? data : [];
        setDrugStocks(items.filter((i) => i.quantity > 0));
      })
      .catch(() => setDrugStocks([]))
      .finally(() => setLoadingStocks(false));
  }, [gangId]);

  const availableGangsters = useMemo(() => members.filter((m) => {
    if (m.role === 'leader') return false;
    if (m.in_transit) return false;
    if (m.guarding_building_id) return false;
    if (m.assigned_racket_zone_id) return false;
    if (m.hospitalized_until && new Date(m.hospitalized_until) > new Date()) return false;
    return true;
  }), [members]);

  const selectedDrugStock = drugStocks.find((d) => d.item_name === selectedDrug);
  const maxStock = selectedDrugStock?.quantity ?? 0;

  const canNext = (): boolean => {
    if (step === 'drug') return !!selectedDrug && parseInt(stockAmount) > 0 && parseInt(stockAmount) <= maxStock;
    if (step === 'gangsters') return selectedGangsterIds.length >= 1;
    if (step === 'config') return true;
    return true;
  };

  const goNext = () => {
    if (!canNext()) return;
    if (step === 'drug') setStep('gangsters');
    else if (step === 'gangsters') setStep('config');
    else if (step === 'config') setStep('confirm');
  };

  const goBack = () => {
    if (step === 'gangsters') setStep('drug');
    else if (step === 'config') setStep('gangsters');
    else if (step === 'confirm') setStep('config');
  };

  const handleSubmit = async () => {
    if (submitting || !selectedDrug) return;
    setSubmitting(true);
    setError(null);
    try {
      await api.dealerMission.create({
        gangId,
        drugName: selectedDrug,
        stockAmount: parseInt(stockAmount),
        gangsterIds: selectedGangsterIds,
        radiusKm,
        durationHours,
        centerLat: player?.current_lat ?? player?.start_lat ?? 0,
        centerLon: player?.current_lon ?? player?.start_lon ?? 0,
      });
      onCreated();
      onClose();
    } catch (e: any) {
      setError(e?.message || 'Erreur creation mission');
    } finally {
      setSubmitting(false);
    }
  };

  const memberName = (m: GangMemberLite) => m.player?.character_name || m.player?.username || `#${m.player_id.slice(0, 6)}`;

  return (
    <div className="fixed inset-0 z-[2100] pointer-events-none flex items-center justify-center">
      <div className="absolute inset-0 pointer-events-auto" style={{ background: 'rgba(0,0,0,0.6)' }} onClick={submitting ? undefined : onClose} />
      <div
        className="relative pointer-events-auto w-[92vw] max-w-[480px] max-h-[85vh] rounded-2xl overflow-hidden flex flex-col"
        style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)', boxShadow: '0 20px 80px rgba(0,0,0,0.5)' }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-4 py-3" style={{ borderBottom: '1px solid var(--border-dark)' }}>
          <div className="flex items-center gap-2">
            <Package size={16} style={{ color: '#a855f7' }} />
            <div>
              <p className="text-sm font-bold" style={{ color: 'var(--text-primary)' }}>Mission dealer</p>
              <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                Etape {step === 'drug' ? '1/4' : step === 'gangsters' ? '2/4' : step === 'config' ? '3/4' : '4/4'}
              </p>
            </div>
          </div>
          <button onClick={submitting ? undefined : onClose} className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ background: 'rgba(255,255,255,0.04)' }}>
            <X size={16} style={{ color: 'var(--text-secondary)' }} />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-4 space-y-3">
          {/* STEP 1: Drug selection */}
          {step === 'drug' && (
            <div className="space-y-2">
              <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>Drogue a dealer</p>
              {loadingStocks ? (
                <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Chargement inventaire...</p>
              ) : drugStocks.length === 0 ? (
                <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Aucune drogue en stock. Produisez ou achetez d'abord.</p>
              ) : (
                <div className="space-y-1">
                  {drugStocks.map((d) => (
                    <button key={d.item_name} onClick={() => { setSelectedDrug(d.item_name); setStockAmount(''); }}
                      className="w-full p-2 rounded-lg flex items-center justify-between"
                      style={{
                        background: selectedDrug === d.item_name ? 'rgba(168,85,247,0.15)' : 'rgba(255,255,255,0.03)',
                        border: selectedDrug === d.item_name ? '1px solid #a855f7' : '1px solid rgba(255,255,255,0.06)',
                      }}>
                      <span className="text-[11px] font-bold" style={{ color: selectedDrug === d.item_name ? '#a855f7' : 'var(--text-primary)' }}>{d.item_name}</span>
                      <span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{d.quantity} en stock</span>
                    </button>
                  ))}
                </div>
              )}
              {selectedDrug && (
                <div>
                  <label className="text-[10px] block mb-1" style={{ color: 'var(--text-muted)' }}>Quantite a envoyer (max {maxStock})</label>
                  <input type="number" min="1" max={maxStock} value={stockAmount}
                    onChange={(e) => setStockAmount(e.target.value)}
                    className="w-full px-2 py-1.5 rounded text-[11px]"
                    style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', color: 'var(--text-primary)' }} />
                </div>
              )}
            </div>
          )}

          {/* STEP 2: Gangster selection */}
          {step === 'gangsters' && (
            <div className="space-y-2">
              <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>
                Gangsters ({selectedGangsterIds.length} selectionne{selectedGangsterIds.length !== 1 ? 's' : ''})
              </p>
              {availableGangsters.length === 0 ? (
                <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Aucun gangster disponible.</p>
              ) : (
                <div className="space-y-1 max-h-[200px] overflow-y-auto">
                  {availableGangsters.map((m) => {
                    const sel = selectedGangsterIds.includes(m.player_id);
                    return (
                      <button key={m.player_id}
                        onClick={() => setSelectedGangsterIds((prev) => sel ? prev.filter((x) => x !== m.player_id) : [...prev, m.player_id])}
                        className="w-full p-2 rounded-lg flex items-center justify-between"
                        style={{
                          background: sel ? 'rgba(168,85,247,0.15)' : 'rgba(255,255,255,0.03)',
                          border: sel ? '1px solid #a855f7' : '1px solid rgba(255,255,255,0.06)',
                        }}>
                        <div className="flex items-center gap-2">
                          <Users size={12} style={{ color: 'var(--text-muted)' }} />
                          <span className="text-[11px]" style={{ color: sel ? '#a855f7' : 'var(--text-primary)' }}>{memberName(m)}</span>
                          <span className="text-[9px]" style={{ color: 'var(--text-muted)' }}>G{m.grade ?? 1}</span>
                        </div>
                        {sel && <Check size={14} style={{ color: '#a855f7' }} />}
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          )}

          {/* STEP 3: Config */}
          {step === 'config' && (
            <div className="space-y-3">
              <div>
                <p className="text-xs font-bold mb-1" style={{ color: 'var(--text-primary)' }}>Rayon de dispersion</p>
                <div className="flex gap-1">
                  {RADIUS_OPTIONS.map((r) => (
                    <button key={r} onClick={() => setRadiusKm(r)}
                      className="flex-1 py-1.5 rounded text-[10px] font-bold"
                      style={{
                        background: radiusKm === r ? 'rgba(168,85,247,0.2)' : 'rgba(255,255,255,0.03)',
                        border: radiusKm === r ? '1px solid #a855f7' : '1px solid rgba(255,255,255,0.06)',
                        color: radiusKm === r ? '#a855f7' : 'var(--text-muted)',
                      }}>
                      {r} km
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <p className="text-xs font-bold mb-1" style={{ color: 'var(--text-primary)' }}>Duree de la mission</p>
                <div className="flex gap-1 flex-wrap">
                  {DURATION_OPTIONS.map((d) => (
                    <button key={d} onClick={() => setDurationHours(d)}
                      className="px-3 py-1.5 rounded text-[10px] font-bold"
                      style={{
                        background: durationHours === d ? 'rgba(168,85,247,0.2)' : 'rgba(255,255,255,0.03)',
                        border: durationHours === d ? '1px solid #a855f7' : '1px solid rgba(255,255,255,0.06)',
                        color: durationHours === d ? '#a855f7' : 'var(--text-muted)',
                      }}>
                      {d}h
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* STEP 4: Confirm */}
          {step === 'confirm' && (
            <div className="space-y-2">
              <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>Confirmer la mission</p>
              <div className="p-3 rounded-xl space-y-1" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
                <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
                  <Package size={10} className="inline mr-1" />
                  Drogue : <span className="font-bold" style={{ color: '#a855f7' }}>{selectedDrug}</span> ({stockAmount} unites)
                </p>
                <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
                  <Users size={10} className="inline mr-1" />
                  Gangsters : <span className="font-bold" style={{ color: 'var(--text-primary)' }}>{selectedGangsterIds.length}</span>
                </p>
                <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
                  <MapPin size={10} className="inline mr-1" />
                  Rayon : {radiusKm} km autour de votre position
                </p>
                <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
                  <Clock size={10} className="inline mr-1" />
                  Duree : {durationHours}h
                </p>
              </div>
            </div>
          )}

          {error && (
            <div className="p-2 rounded flex items-center gap-2" style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.25)' }}>
              <AlertCircle size={12} style={{ color: '#ef4444' }} />
              <p className="text-[11px]" style={{ color: '#ef4444' }}>{error}</p>
            </div>
          )}
        </div>

        {/* Footer nav */}
        <div className="flex items-center justify-between px-4 py-3" style={{ borderTop: '1px solid var(--border-dark)' }}>
          {step !== 'drug' ? (
            <button onClick={goBack} className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Retour</button>
          ) : <span />}
          {step === 'confirm' ? (
            <button onClick={handleSubmit} disabled={submitting}
              className="px-5 py-2 rounded-xl text-xs font-bold disabled:opacity-50"
              style={{ background: '#a855f7', color: '#fff' }}>
              {submitting ? 'Lancement...' : 'Lancer la mission'}
            </button>
          ) : (
            <button onClick={goNext} disabled={!canNext()}
              className="px-5 py-2 rounded-xl text-xs font-bold disabled:opacity-30"
              style={{ background: canNext() ? '#a855f7' : 'rgba(255,255,255,0.06)', color: canNext() ? '#fff' : 'var(--text-muted)' }}>
              Suivant
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
