'use client';

/**
 * StorageTransferModal — audit 15-04-2026 Phase 12.b
 *
 * Modal pour transferer des items entre l'inventaire du joueur (on_person) et
 * une de ses proprietes (residence, business, warehouse, vehicle) via
 * POST /api/property/transfer-item (Phase 5 backend).
 *
 * MVP : transfert uniquement FROM player (on_person) TO la destination.
 * La direction inverse (retirer un item du storage) pourra etre ajoutee ensuite
 * en switchant source/destination via un toggle UI.
 */

import { useState, useEffect, useMemo } from 'react';
import { api } from '@/lib/api';
import { X as XIcon, Package, AlertCircle, Check } from 'lucide-react';

type StorageLocationType = 'residence' | 'business' | 'warehouse' | 'vehicle' | 'player';

interface Props {
  playerId: string;
  destinationType: Exclude<StorageLocationType, 'player'>;
  destinationId: string;
  destinationName: string;
  onClose: () => void;
  onTransferred: () => void;
}

interface InventoryItemLite {
  id: string;
  item_type: string;
  item_subtype: string;
  quantity: number;
  quality: number;
  weight_grams: number | string;
  storage_condition: string;
  is_listed?: boolean;
}

interface LocationCapacityLite {
  capacity_kg: number;
  filled_kg: number;
  remaining_kg: number;
  item_count: number;
}

export function StorageTransferModal({
  playerId,
  destinationType,
  destinationId,
  destinationName,
  onClose,
  onTransferred,
}: Props) {
  const [direction, setDirection] = useState<'to_destination' | 'from_destination'>('to_destination');
  const [playerItems, setPlayerItems] = useState<InventoryItemLite[]>([]);
  const [destItems, setDestItems] = useState<InventoryItemLite[]>([]);
  const [capacity, setCapacity] = useState<LocationCapacityLite | null>(null);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [quantity, setQuantity] = useState<number>(1);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  // Load data
  useEffect(() => {
    let cancelled = false;
    async function load() {
      setLoading(true);
      setError(null);
      try {
        const [playerInv, destInv, cap] = await Promise.all([
          api.property.listItemsAtLocation('player', playerId),
          api.property.listItemsAtLocation(destinationType, destinationId),
          api.property.getCapacity(destinationType, destinationId),
        ]);
        if (cancelled) return;
        setPlayerItems(Array.isArray(playerInv) ? (playerInv as InventoryItemLite[]) : []);
        setDestItems(Array.isArray(destInv) ? (destInv as InventoryItemLite[]) : []);
        setCapacity(cap as LocationCapacityLite);
      } catch (e: any) {
        if (!cancelled) setError(e?.message || 'Erreur de chargement');
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    load();
    return () => { cancelled = true; };
  }, [playerId, destinationType, destinationId]);

  const currentItems = direction === 'to_destination' ? playerItems : destItems;
  const selected = useMemo(
    () => currentItems.find((i) => i.id === selectedId) || null,
    [currentItems, selectedId],
  );

  // Reset selection when direction changes
  useEffect(() => {
    setSelectedId(null);
    setQuantity(1);
  }, [direction]);

  // Clamp quantity to selected item quantity
  useEffect(() => {
    if (selected && quantity > selected.quantity) setQuantity(selected.quantity);
  }, [selected, quantity]);

  const transferWeightKg = useMemo(() => {
    if (!selected) return 0;
    return (Number(selected.weight_grams) * quantity) / 1000;
  }, [selected, quantity]);

  const handleSubmit = async () => {
    if (submitting || !selected || !playerId) return;
    setSubmitting(true);
    setError(null);
    setSuccess(null);
    try {
      const src = direction === 'to_destination' ? 'player' : destinationType;
      const srcId = direction === 'to_destination' ? playerId : destinationId;
      const dst = direction === 'to_destination' ? destinationType : 'player';
      const dstId = direction === 'to_destination' ? destinationId : playerId;
      await api.property.transferItem({
        source_location_type: src,
        source_location_id: srcId,
        destination_location_type: dst,
        destination_location_id: dstId,
        inventory_id: selected.id,
        quantity,
      });
      setSuccess(`${quantity}x ${selected.item_subtype} transferes`);
      // Reload after 600ms then close
      setTimeout(async () => {
        try {
          const [pi, di, c] = await Promise.all([
            api.property.listItemsAtLocation('player', playerId),
            api.property.listItemsAtLocation(destinationType, destinationId),
            api.property.getCapacity(destinationType, destinationId),
          ]);
          setPlayerItems(Array.isArray(pi) ? (pi as InventoryItemLite[]) : []);
          setDestItems(Array.isArray(di) ? (di as InventoryItemLite[]) : []);
          setCapacity(c as LocationCapacityLite);
          setSelectedId(null);
          setQuantity(1);
          onTransferred();
        } catch { /* silent refresh fail */ }
      }, 600);
    } catch (e: any) {
      setError(e?.message || 'Transfert echoue');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[2200] 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-[520px] max-h-[88vh] 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 min-w-0">
            <Package size={16} style={{ color: 'var(--color-gold)' }} />
            <div className="min-w-0">
              <p className="text-sm font-bold truncate" style={{ color: 'var(--text-primary)' }}>
                Stockage — {destinationName}
              </p>
              <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                {destinationType} ·{' '}
                {capacity
                  ? `${capacity.filled_kg.toFixed(2)} / ${capacity.capacity_kg} kg`
                  : '—'}
              </p>
            </div>
          </div>
          <button
            onClick={submitting ? undefined : onClose}
            disabled={submitting}
            className="w-8 h-8 rounded-lg flex items-center justify-center hover:opacity-80 disabled:opacity-30"
            style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.06)' }}
          >
            <XIcon size={16} style={{ color: 'var(--text-secondary)' }} />
          </button>
        </div>

        {/* Direction toggle */}
        <div className="px-4 pt-3 pb-2 flex gap-1">
          <button
            type="button"
            onClick={() => setDirection('to_destination')}
            className="flex-1 py-1.5 rounded text-[11px] font-bold transition-colors"
            style={{
              background: direction === 'to_destination' ? 'var(--color-gold)' : 'rgba(255,255,255,0.04)',
              color: direction === 'to_destination' ? '#000' : 'var(--text-secondary)',
              border: '1px solid rgba(255,255,255,0.08)',
            }}
          >
            Stocker (vers {destinationName})
          </button>
          <button
            type="button"
            onClick={() => setDirection('from_destination')}
            className="flex-1 py-1.5 rounded text-[11px] font-bold transition-colors"
            style={{
              background: direction === 'from_destination' ? 'var(--color-gold)' : 'rgba(255,255,255,0.04)',
              color: direction === 'from_destination' ? '#000' : 'var(--text-secondary)',
              border: '1px solid rgba(255,255,255,0.08)',
            }}
          >
            Retirer (vers moi)
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto px-4 py-2 space-y-2">
          {loading ? (
            <p className="text-[11px]" style={{ color: 'var(--text-muted)' }}>Chargement…</p>
          ) : currentItems.length === 0 ? (
            <p className="text-[11px]" style={{ color: 'var(--text-muted)' }}>
              {direction === 'to_destination'
                ? 'Aucun item dans votre inventaire personnel.'
                : 'Aucun item a cet emplacement.'}
            </p>
          ) : (
            <div className="space-y-1">
              {currentItems.map((item) => {
                const isSelected = item.id === selectedId;
                return (
                  <button
                    key={item.id}
                    type="button"
                    onClick={() => { setSelectedId(item.id); setQuantity(Math.min(1, item.quantity)); }}
                    className="w-full p-2 rounded-lg flex items-center justify-between gap-2"
                    style={{
                      background: isSelected ? 'rgba(212,168,67,0.15)' : 'rgba(255,255,255,0.03)',
                      border: isSelected ? '1px solid var(--color-gold)' : '1px solid rgba(255,255,255,0.06)',
                    }}
                    disabled={item.is_listed}
                  >
                    <div className="min-w-0 flex-1 text-left">
                      <p className="text-[11px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>
                        {item.item_subtype}
                        <span style={{ color: 'var(--text-muted)' }} className="ml-1">x{item.quantity}</span>
                      </p>
                      <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                        {item.item_type} · q{item.quality} · {(Number(item.weight_grams) / 1000).toFixed(2)}kg/u
                        {item.is_listed ? ' · (en vente)' : ''}
                      </p>
                    </div>
                    {isSelected && <Check size={14} style={{ color: 'var(--color-gold)' }} />}
                  </button>
                );
              })}
            </div>
          )}
        </div>

        {/* Quantity picker + submit */}
        {selected && (
          <div className="px-4 py-2 space-y-2" style={{ borderTop: '1px solid var(--border-dark)' }}>
            <div className="flex items-center gap-2">
              <span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Quantite :</span>
              <input
                type="number"
                min={1}
                max={selected.quantity}
                value={quantity}
                onChange={(e) => setQuantity(Math.max(1, Math.min(selected.quantity, parseInt(e.target.value, 10) || 1)))}
                className="w-20 px-2 py-1 rounded text-[11px]"
                style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', color: 'var(--text-primary)' }}
              />
              <span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                / {selected.quantity} · {transferWeightKg.toFixed(2)} kg
              </span>
            </div>
            {capacity && direction === 'to_destination' && transferWeightKg > capacity.remaining_kg && (
              <div className="flex items-center gap-1 text-[10px]" style={{ color: '#ef4444' }}>
                <AlertCircle size={10} />
                <span>Depasse la capacite restante ({capacity.remaining_kg.toFixed(2)} kg dispo)</span>
              </div>
            )}
          </div>
        )}

        {error && (
          <div className="mx-4 mb-2 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>
        )}
        {success && (
          <div className="mx-4 mb-2 p-2 rounded flex items-center gap-2" style={{ background: 'rgba(34,197,94,0.1)', border: '1px solid rgba(34,197,94,0.25)' }}>
            <Check size={12} style={{ color: '#22c55e' }} />
            <p className="text-[11px]" style={{ color: '#22c55e' }}>{success}</p>
          </div>
        )}

        {/* Footer */}
        <div className="flex justify-end gap-2 px-4 py-3" style={{ borderTop: '1px solid var(--border-dark)' }}>
          <button
            type="button"
            onClick={onClose}
            disabled={submitting}
            className="px-3 py-1.5 rounded text-[11px] font-bold disabled:opacity-30"
            style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', color: 'var(--text-secondary)' }}
          >
            Fermer
          </button>
          <button
            type="button"
            onClick={handleSubmit}
            disabled={submitting || !selected || quantity < 1 || (direction === 'to_destination' && capacity != null && transferWeightKg > capacity.remaining_kg)}
            className="px-4 py-1.5 rounded text-[11px] font-bold disabled:opacity-30"
            style={{ background: 'var(--color-gold)', color: '#000' }}
          >
            {submitting ? 'Transfert…' : 'Transferer'}
          </button>
        </div>
      </div>
    </div>
  );
}
