import React from 'react';
import { Zone, ZoneType } from './types';

interface ZoneGridProps {
  zones: Zone[][];
  selectedZone: Zone | Zone[] | null;
  onSelectZone: (zone: Zone) => void;
  disabled?: boolean;
  prices?: Record<'vip' | 'general' | 'empty', number>;
}

const ZONE_COLORS: Record<ZoneType, string> = {
  vip: 'bg-purple-600 hover:bg-purple-700',
  general: 'bg-blue-600 hover:bg-blue-700',
};

const ZONE_SELECTED_COLORS: Record<ZoneType, string> = {
  vip: 'bg-[#f4a825] hover:bg-[#e6a11f] ring-4 ring-[#f4a825]',
  general: 'bg-[#f4a825] hover:bg-[#e6a11f] ring-4 ring-[#f4a825]',
};

const ZONE_UNAVAILABLE = 'bg-gray-700 cursor-not-allowed opacity-50';

export default function ZoneGrid({
  zones,
  selectedZone,
  onSelectZone,
  disabled = false,
  prices,
}: ZoneGridProps) {
  const handleZoneClick = (zone: Zone) => {
    if (disabled || !zone.available) return;
    onSelectZone(zone);
  };

  const getZoneColor = (zone: Zone): string => {
    if (!zone.available) return ZONE_UNAVAILABLE;
    
    // Check if zone is selected (handle both single zone and array of zones)
    let isSelected = false;
    if (Array.isArray(selectedZone)) {
      isSelected = selectedZone.some(z => z.id === zone.id);
    } else if (selectedZone) {
      isSelected = selectedZone.id === zone.id;
    }
    
    if (isSelected) {
      return ZONE_SELECTED_COLORS[zone.type];
    }
    
    return ZONE_COLORS[zone.type];
  };

  const getZoneLabel = (zone: Zone): string => {
    if (zone.label) return zone.label;
    
    const rowLetter = String.fromCharCode(65 + zone.row); // A, B, C...
    const colNumber = zone.col + 1;
    
    switch (zone.type) {
      case 'vip':
        return `V${rowLetter}${colNumber}`;
      case 'general':
        return `G${rowLetter}${colNumber}`;
      default:
        return `${rowLetter}${colNumber}`;
    }
  };

  return (
    <div className="space-y-4">
      {/* Leyenda */}
      <div className="flex flex-wrap gap-4 justify-center mb-6">
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 bg-purple-600 rounded"></div>
          <span className="text-sm text-slate-300">⭐ VIP - ${prices?.vip || 100}</span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 bg-blue-600 rounded"></div>
          <span className="text-sm text-slate-300">🎫 General - ${prices?.general || 60}</span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 bg-gray-700 rounded opacity-50"></div>
          <span className="text-sm text-slate-300">✖️ No disponible</span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 bg-[#f4a825] rounded ring-4 ring-[#f4a825]"></div>
          <span className="text-sm text-slate-300">✓ Seleccionado</span>
        </div>
      </div>

      <p className="text-sm text-center text-slate-400 mb-4">
        💡 Puedes seleccionar múltiples stands para tu reserva
      </p>

      {/* Grid de zonas */}
      <div className="overflow-x-auto">
        <div className="inline-block min-w-full">
          {/* Etiquetas de columnas */}
          <div className="flex mb-2">
            <div className="w-10 flex-shrink-0"></div>
            {zones[0]?.map((_, colIndex) => (
              <div
                key={`col-${colIndex}`}
                className="w-12 h-8 flex items-center justify-center text-xs text-slate-400 font-semibold"
              >
                {colIndex + 1}
              </div>
            ))}
          </div>

          {/* Filas de zonas */}
          {zones.map((row, rowIndex) => (
            <div key={`row-${rowIndex}`} className="flex mb-1">
              {/* Etiqueta de fila */}
              <div className="w-10 flex-shrink-0 flex items-center justify-center text-xs text-slate-400 font-semibold">
                {String.fromCharCode(65 + rowIndex)}
              </div>

              {/* Celdas de la fila */}
              {row.map((zone) => {
                // Check if zone is selected (handle both single zone and array of zones)
                let isSelected = false;
                if (Array.isArray(selectedZone)) {
                  isSelected = selectedZone.some(z => z.id === zone.id);
                } else if (selectedZone) {
                  isSelected = selectedZone.id === zone.id;
                }
                const zoneColor = getZoneColor(zone);

                return (
                  <button
                    key={zone.id}
                    type="button"
                    onClick={() => handleZoneClick(zone)}
                    disabled={disabled || !zone.available}
                    className={`
                      w-12 h-12 m-0.5 rounded text-xs font-bold text-white
                      transition-all duration-200 flex items-center justify-center
                      ${zoneColor}
                      ${zone.available && !disabled ? 'cursor-pointer' : ''}
                      ${isSelected ? 'scale-110 shadow-lg' : ''}
                    `}
                    title={
                      zone.available
                        ? `${getZoneLabel(zone)} - $${zone.price}`
                        : 'No disponible'
                    }
                  >
                    {isSelected && '✓'}
                  </button>
                );
              })}
            </div>
          ))}
        </div>
      </div>

      {/* Instrucciones */}
      <div className="mt-6 rounded-lg bg-[#231f1a] border border-[#393328] p-4">
        <p className="text-sm text-slate-300">
          💡 <span className="font-semibold">Instrucciones:</span> Haz clic en una zona disponible para seleccionarla. Las zonas VIP ofrecen las mejores ubicaciones para tu stand o tienda en el evento.
        </p>
      </div>
    </div>
  );
}
