'use client';

import { useState } from 'react';
import { Users, Home, X, CheckSquare, Square, ChevronDown, ChevronUp } from 'lucide-react';
import { useMapStore, MapEntity } from '@/stores/mapStore';
import { useGameStore } from '@/stores/gameStore';

interface GangsterPanelProps {
  onReturnToBase: (gangsterKeys: string[]) => void;
}

export function GangsterPanel({ onReturnToBase }: GangsterPanelProps) {
  const [expanded, setExpanded] = useState(false);
  const [lightboxOpen, setLightboxOpen] = useState(false);

  const visibleGangsters = useMapStore((s) => s.visibleGangsters);
  const selectedGangsterIds = useMapStore((s) => s.selectedGangsterIds);
  const selectionMode = useMapStore((s) => s.selectionMode);
  const toggleGangsterSelection = useMapStore((s) => s.toggleGangsterSelection);
  const setSelectedGangsterIds = useMapStore((s) => s.setSelectedGangsterIds);
  const clearGangsterSelection = useMapStore((s) => s.clearGangsterSelection);
  const player = useGameStore((s) => s.player);

  // Only show allied gangsters (our gang members)
  const alliedGangsters = visibleGangsters.filter((g) => g.allied);

  if (alliedGangsters.length === 0) return null;

  const selectedCount = selectedGangsterIds.length;

  const handleSelectAll = () => {
    const allKeys = alliedGangsters
      .filter((g) => !g.hospitalized)
      .map((g) => `${g.gang_id}:${g.id}`);
    setSelectedGangsterIds(allKeys);
  };

  const handleDeselectAll = () => {
    clearGangsterSelection();
  };

  const handleReturnToBase = () => {
    if (selectedCount === 0) return;
    onReturnToBase(selectedGangsterIds);
  };

  const isSelected = (g: MapEntity) =>
    selectedGangsterIds.includes(`${g.gang_id}:${g.id}`);

  const toggleOne = (g: MapEntity) => {
    if (g.gang_id) {
      toggleGangsterSelection(g.gang_id, g.id);
    }
  };

  return (
    <>
      {/* Floating panel — top-left */}
      <div
        className="absolute top-3 left-3 z-[1000] rounded-xl overflow-hidden"
        style={{
          background: 'var(--bg-panel)',
          border: '1px solid var(--border-dark)',
          minWidth: 200,
          boxShadow: '0 4px 24px rgba(0,0,0,0.3)',
        }}
      >
        {/* Header */}
        <button
          onClick={() => setExpanded(!expanded)}
          className="w-full flex items-center justify-between px-3 py-2 text-xs font-bold hover:bg-white/5 transition-colors"
          style={{ color: 'var(--color-gold)', borderBottom: expanded ? '1px solid var(--border-dark)' : 'none' }}
        >
          <span className="flex items-center gap-2">
            <Users size={14} />
            Gangsters ({alliedGangsters.length})
            {selectedCount > 0 && (
              <span
                className="px-1.5 py-0.5 rounded text-[9px] font-bold"
                style={{ background: 'rgba(34,197,94,0.2)', color: '#22c55e' }}
              >
                {selectedCount} sel.
              </span>
            )}
          </span>
          {expanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
        </button>

        {expanded && (
          <div className="p-2 space-y-1.5">
            {/* Quick actions */}
            <button
              onClick={handleReturnToBase}
              disabled={selectedCount === 0}
              className="w-full flex items-center gap-2 px-2.5 py-1.5 rounded-lg text-[11px] font-medium transition-colors disabled:opacity-40"
              style={{
                background: selectedCount > 0 ? 'rgba(212,168,67,0.12)' : 'rgba(255,255,255,0.03)',
                border: '1px solid rgba(212,168,67,0.2)',
                color: 'var(--color-gold)',
              }}
            >
              <Home size={12} />
              Rentrer a la planque
            </button>

            <button
              onClick={() => setLightboxOpen(true)}
              className="w-full flex items-center gap-2 px-2.5 py-1.5 rounded-lg text-[11px] font-medium transition-colors hover:bg-white/5"
              style={{
                background: 'rgba(255,255,255,0.03)',
                border: '1px solid rgba(255,255,255,0.08)',
                color: 'var(--text-primary)',
              }}
            >
              <Users size={12} />
              Selectionner gangsters
            </button>

            {/* Selection mode indicator */}
            {selectionMode && selectedCount > 0 && (
              <div
                className="px-2.5 py-1.5 rounded-lg text-[10px]"
                style={{ background: 'rgba(34,197,94,0.08)', border: '1px solid rgba(34,197,94,0.2)', color: '#22c55e' }}
              >
                Mode ordre : cliquez sur la carte ou un POI pour donner un ordre aux {selectedCount} gangster(s)
              </div>
            )}
          </div>
        )}
      </div>

      {/* Lightbox — gangster selection */}
      {lightboxOpen && (
        <div className="fixed inset-0 z-[2500] flex items-center justify-center pointer-events-none">
          <div
            className="absolute inset-0 pointer-events-auto"
            style={{ background: 'rgba(0,0,0,0.6)' }}
            onClick={() => setLightboxOpen(false)}
          />
          <div
            className="relative pointer-events-auto w-[90vw] max-w-[440px] max-h-[75vh] 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.4)',
            }}
            onClick={(e) => e.stopPropagation()}
          >
            {/* Header */}
            <div
              className="flex items-center justify-between px-4 py-3"
              style={{ borderBottom: '1px solid var(--border-dark)' }}
            >
              <div>
                <p className="text-sm font-bold" style={{ color: 'var(--text-primary)' }}>
                  Selectionner gangsters
                </p>
                <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                  {selectedCount}/{alliedGangsters.length} selectionne(s)
                </p>
              </div>
              <button
                onClick={() => setLightboxOpen(false)}
                className="w-8 h-8 rounded-lg flex items-center justify-center hover:opacity-80"
                style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.06)' }}
              >
                <X size={16} style={{ color: 'var(--text-secondary)' }} />
              </button>
            </div>

            {/* Select all / Deselect all */}
            <div className="flex gap-2 px-4 py-2" style={{ borderBottom: '1px solid var(--border-dark)' }}>
              <button
                onClick={handleSelectAll}
                className="flex-1 py-1.5 rounded-lg text-[11px] font-bold transition-colors hover:bg-white/5"
                style={{ background: 'rgba(34,197,94,0.1)', border: '1px solid rgba(34,197,94,0.2)', color: '#22c55e' }}
              >
                Tout selectionner
              </button>
              <button
                onClick={handleDeselectAll}
                className="flex-1 py-1.5 rounded-lg text-[11px] font-bold transition-colors hover:bg-white/5"
                style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.2)', color: '#ef4444' }}
              >
                Tout deselectionner
              </button>
            </div>

            {/* Gangster list */}
            <div className="flex-1 overflow-y-auto p-2 space-y-1">
              {alliedGangsters.map((g) => {
                const selected = isSelected(g);
                const disabled = !!g.hospitalized;
                const statusLabel = g.hospitalized
                  ? 'Hospitalise'
                  : g.in_transit
                  ? 'En transit'
                  : g.guarding_building_id
                  ? 'En garde'
                  : g.assigned_racket_zone_id
                  ? 'En racket'
                  : 'Disponible';
                const statusColor = g.hospitalized
                  ? '#ef4444'
                  : g.in_transit
                  ? '#3b82f6'
                  : g.guarding_building_id
                  ? '#f59e0b'
                  : g.assigned_racket_zone_id
                  ? '#a855f7'
                  : '#22c55e';

                return (
                  <button
                    key={`${g.gang_id}:${g.id}`}
                    onClick={() => !disabled && toggleOne(g)}
                    disabled={disabled}
                    className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-left transition-colors disabled:opacity-40"
                    style={{
                      background: selected ? 'rgba(34,197,94,0.1)' : 'rgba(255,255,255,0.02)',
                      border: `1px solid ${selected ? 'rgba(34,197,94,0.3)' : 'rgba(255,255,255,0.06)'}`,
                    }}
                  >
                    {/* Checkbox */}
                    <div className="flex-shrink-0">
                      {selected ? (
                        <CheckSquare size={16} style={{ color: '#22c55e' }} />
                      ) : (
                        <Square size={16} style={{ color: 'var(--text-muted)' }} />
                      )}
                    </div>

                    {/* Grade badge */}
                    <div
                      className="flex-shrink-0 w-7 h-7 rounded-full flex items-center justify-center text-[10px] font-bold"
                      style={{
                        background: statusColor,
                        border: `2px solid ${statusColor}40`,
                        color: '#fff',
                      }}
                    >
                      {g.grade || 1}
                    </div>

                    {/* Info */}
                    <div className="min-w-0 flex-1">
                      <p className="text-[11px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>
                        {g.name || 'Gangster'}
                      </p>
                      <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                        <span style={{ color: '#d4a843' }}>{g.grade_name || 'Recrue'}</span>
                        {' — '}
                        <span style={{ color: statusColor }}>{statusLabel}</span>
                        {g.assigned_weapon && (
                          <span style={{ color: '#ef4444' }}>{' — '}{g.assigned_weapon}</span>
                        )}
                      </p>
                    </div>
                  </button>
                );
              })}
            </div>

            {/* Footer — Donner ordre */}
            <div className="px-4 py-3" style={{ borderTop: '1px solid var(--border-dark)' }}>
              <button
                onClick={() => setLightboxOpen(false)}
                disabled={selectedCount === 0}
                className="w-full py-2.5 rounded-xl text-xs font-bold transition-colors disabled:opacity-40"
                style={{
                  background: selectedCount > 0 ? 'rgba(34,197,94,0.15)' : 'rgba(255,255,255,0.04)',
                  border: `1px solid ${selectedCount > 0 ? 'rgba(34,197,94,0.3)' : 'rgba(255,255,255,0.08)'}`,
                  color: selectedCount > 0 ? '#22c55e' : 'var(--text-muted)',
                }}
              >
                {selectedCount > 0
                  ? `Donner ordre (${selectedCount} gangster${selectedCount > 1 ? 's' : ''})`
                  : 'Selectionnez au moins un gangster'}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
