import { useState, useEffect } from 'react';
import { 
  loadSeatingMaps, 
  createSeatingMap, 
  deleteSeatingMap, 
  applySeatingMapToEvent,
  type SeatingMap,
  type LayoutItem
} from '../../lib/seating-management';
import { loadEventData, updateEventData } from '../../lib/event-management';
import SeatingMapModal from '../modals/SeatingMapModal';

interface VenueTabProps {
  eventId: string;
  organizationId: string;
}

export default function VenueTab({ eventId, organizationId }: VenueTabProps) {
  const [seatingMaps, setSeatingMaps] = useState<SeatingMap[]>([]);
  const [currentSeatingMap, setCurrentSeatingMap] = useState<SeatingMap | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [editingMap, setEditingMap] = useState<SeatingMap | undefined>();
  const [venueData, setVenueData] = useState<any>(null);
  const [seatingType, setSeatingType] = useState<'general' | 'assigned'>('general');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadData();
  }, [eventId, organizationId]);

  const loadData = async () => {
    setLoading(true);
    try {

      const [mapsData, eventData] = await Promise.all([
        loadSeatingMaps(organizationId),
        loadEventData(eventId, organizationId)
      ]);

      // Validate seating maps data
      const validMaps = mapsData.filter(map => {
        if (!map.layout_data) {

          return false;
        }
        return true;
      });
      
      setSeatingMaps(validMaps);
      setVenueData({
        venue: eventData?.venue || '',
        seating_type: eventData?.seating_type || 'general_admission'
      });
      setCurrentSeatingMap(eventData?.seating_map || null);
      setSeatingType(eventData?.seating_type === 'assigned' ? 'assigned' : 'general');
    } catch (error) {

    } finally {
      setLoading(false);
    }
  };

  const handleCreateSeatingMap = () => {
    setEditingMap(undefined);
    setShowModal(true);
  };

  const handleEditSeatingMap = (seatingMap: SeatingMap) => {
    setEditingMap(seatingMap);
    setShowModal(true);
  };

  const handleDeleteSeatingMap = async (seatingMap: SeatingMap) => {
    if (confirm(`Are you sure you want to delete "${seatingMap.name}"?`)) {
      const success = await deleteSeatingMap(seatingMap.id);
      if (success) {
        setSeatingMaps(prev => prev.filter(m => m.id !== seatingMap.id));
        if (currentSeatingMap?.id === seatingMap.id) {
          setCurrentSeatingMap(null);
        }
      }
    }
  };

  const handleApplySeatingMap = async (seatingMap: SeatingMap) => {
    const success = await applySeatingMapToEvent(eventId, seatingMap.id);
    if (success) {
      setCurrentSeatingMap(seatingMap);
      setSeatingType('assigned');
    }
  };

  const handleRemoveSeatingMap = async () => {
    const success = await updateEventData(eventId, { seating_map_id: null });
    if (success) {
      setCurrentSeatingMap(null);
      setSeatingType('general');
    }
  };

  const handleModalSave = (seatingMap: SeatingMap) => {
    if (editingMap) {
      setSeatingMaps(prev => prev.map(m => 
        m.id === seatingMap.id ? seatingMap : m
      ));
    } else {
      setSeatingMaps(prev => [...prev, seatingMap]);
    }
    setShowModal(false);
  };

  const renderSeatingPreview = (seatingMap: SeatingMap) => {
    const layoutItems = Array.isArray(seatingMap.layout_data) 
      ? seatingMap.layout_data as LayoutItem[] 
      : [];
    const totalCapacity = layoutItems.reduce((sum, item) => sum + (item.capacity || 0), 0);

    return (
      <div className="bg-white/5 border border-white/20 rounded-xl p-6 hover:bg-white/10 transition-all duration-200">
        <div className="flex justify-between items-start mb-4">
          <div>
            <h3 className="text-xl font-semibold text-white mb-2">{seatingMap.name}</h3>
            <div className="flex items-center gap-4 text-sm text-white/60">
              <span>{layoutItems.length} sections</span>
              <span>{totalCapacity} capacity</span>
              <span>Created {new Date(seatingMap.created_at).toLocaleDateString()}</span>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => handleEditSeatingMap(seatingMap)}
              className="p-2 text-white/60 hover:text-white transition-colors"
              title="Edit"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
              </svg>
            </button>
            <button
              onClick={() => handleDeleteSeatingMap(seatingMap)}
              className="p-2 text-white/60 hover:text-red-400 transition-colors"
              title="Delete"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
              </svg>
            </button>
          </div>
        </div>

        <div className="mb-4">
          <div className="bg-white/5 border border-white/10 rounded-lg p-4 h-48 relative overflow-hidden">
            <div className="absolute inset-0 flex items-center justify-center">
              <div className="text-center">
                <div className="text-white/40 mb-2">Layout Preview</div>
                <div className="grid grid-cols-4 gap-2 max-w-32">
                  {layoutItems.slice(0, 16).map((item, index) => (
                    <div
                      key={index}
                      className={`w-6 h-6 rounded border-2 border-dashed ${
                        item.type === 'table' ? 'border-blue-400/60 bg-blue-500/20' :
                        item.type === 'seat_row' ? 'border-green-400/60 bg-green-500/20' :
                        'border-purple-400/60 bg-purple-500/20'
                      }`}
                    />
                  ))}
                </div>
                {layoutItems.length > 16 && (
                  <div className="text-xs text-white/40 mt-2">
                    +{layoutItems.length - 16} more sections
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="flex items-center justify-between">
          <div className="text-sm text-white/60">
            Capacity: {totalCapacity} people
          </div>
          <div className="flex items-center gap-2">
            {currentSeatingMap?.id === seatingMap.id ? (
              <div className="flex items-center gap-2">
                <span className="px-3 py-1 bg-green-500/20 text-green-300 border border-green-500/30 rounded-lg text-sm">
                  Currently Applied
                </span>
                <button
                  onClick={handleRemoveSeatingMap}
                  className="px-3 py-1 bg-red-500/20 text-red-300 border border-red-500/30 rounded-lg text-sm hover:bg-red-500/30 transition-colors"
                >
                  Remove
                </button>
              </div>
            ) : (
              <button
                onClick={() => handleApplySeatingMap(seatingMap)}
                className="px-4 py-2 text-white rounded-lg text-sm transition-colors"
                style={{
                  background: 'var(--glass-text-accent)'
                }}
              >
                Apply to Event
              </button>
            )}
          </div>
        </div>
      </div>
    );
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-white"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h2 className="text-2xl font-light text-white">Venue & Seating</h2>
        <button
          onClick={handleCreateSeatingMap}
          className="flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-all duration-200"
          style={{
            background: 'var(--glass-text-accent)',
            color: 'white'
          }}
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
          Create Seating Map
        </button>
      </div>

      {/* Seating Type Selection */}
      <div className="bg-white/5 border border-white/20 rounded-xl p-6">
        <h3 className="text-lg font-semibold text-white mb-4">Seating Configuration</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div 
            className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
              seatingType === 'general' 
                ? 'border-blue-500 bg-blue-500/10' 
                : 'border-white/20 hover:border-white/40'
            }`}
            onClick={() => setSeatingType('general')}
          >
            <div className="flex items-center justify-between mb-2">
              <h4 className="font-semibold text-white">General Admission</h4>
              <div className={`w-4 h-4 rounded-full border-2 ${
                seatingType === 'general' ? 'border-blue-500 bg-blue-500' : 'border-white/40'
              }`} />
            </div>
            <p className="text-white/60 text-sm">
              No assigned seats. First-come, first-served seating arrangement.
            </p>
          </div>

          <div 
            className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${
              seatingType === 'assigned' 
                ? 'border-blue-500 bg-blue-500/10' 
                : 'border-white/20 hover:border-white/40'
            }`}
            onClick={() => setSeatingType('assigned')}
          >
            <div className="flex items-center justify-between mb-2">
              <h4 className="font-semibold text-white">Assigned Seating</h4>
              <div className={`w-4 h-4 rounded-full border-2 ${
                seatingType === 'assigned' ? 'border-blue-500 bg-blue-500' : 'border-white/40'
              }`} />
            </div>
            <p className="text-white/60 text-sm">
              Specific seat assignments with custom venue layout.
            </p>
          </div>
        </div>
      </div>

      {/* Current Seating Map */}
      {currentSeatingMap && (
        <div className="bg-white/5 border border-white/20 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-white mb-4">Current Seating Map</h3>
          {renderSeatingPreview(currentSeatingMap)}
        </div>
      )}

      {/* Available Seating Maps */}
      <div>
        <h3 className="text-lg font-semibold text-white mb-4">
          Available Seating Maps ({seatingMaps.length})
        </h3>
        
        {seatingMaps.length === 0 ? (
          <div className="text-center py-12">
            <svg className="w-12 h-12 text-white/40 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
            </svg>
            <p className="text-white/60 mb-4">No seating maps created yet</p>
            <button
              onClick={handleCreateSeatingMap}
              className="px-6 py-3 rounded-lg font-medium transition-all duration-200"
              style={{
                background: 'var(--glass-text-accent)',
                color: 'white'
              }}
            >
              Create Your First Seating Map
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {seatingMaps.map((seatingMap) => (
              <div key={seatingMap.id}>
                {renderSeatingPreview(seatingMap)}
              </div>
            ))}
          </div>
        )}
      </div>

      <SeatingMapModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        onSave={handleModalSave}
        organizationId={organizationId}
        seatingMap={editingMap}
      />
    </div>
  );
}