import React, { useState, useEffect } from 'react';
import type { SeatingMap, LayoutItem, LayoutType } from '../../lib/seating-management';
import { createSeatingMap, updateSeatingMap, generateInitialLayout } from '../../lib/seating-management';

interface SeatingMapModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (seatingMap: SeatingMap) => void;
  organizationId: string;
  seatingMap?: SeatingMap;
}

export default function SeatingMapModal({ 
  isOpen, 
  onClose, 
  onSave, 
  organizationId, 
  seatingMap 
}: SeatingMapModalProps) {
  const [name, setName] = useState('');
  const [layoutType, setLayoutType] = useState<LayoutType>('theater');
  const [capacity, setCapacity] = useState(100);
  const [layoutItems, setLayoutItems] = useState<LayoutItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (seatingMap) {
      setName(seatingMap.name);
      setLayoutItems(seatingMap.layout_data || []);
    } else {
      setName('');
      setLayoutItems([]);
    }
    setError(null);
  }, [seatingMap, isOpen]);

  useEffect(() => {
    if (!seatingMap) {
      const initialLayout = generateInitialLayout(layoutType, capacity);
      setLayoutItems(initialLayout);
    }
  }, [layoutType, capacity, seatingMap]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const seatingMapData = {
        name,
        layout_data: layoutItems
      };

      if (seatingMap) {
        // Update existing seating map
        const success = await updateSeatingMap(seatingMap.id, seatingMapData);
        if (success) {
          onSave({ ...seatingMap, ...seatingMapData });
          onClose();
        } else {
          setError('Failed to update seating map');
        }
      } else {
        // Create new seating map
        const newSeatingMap = await createSeatingMap(organizationId, seatingMapData);
        if (newSeatingMap) {
          onSave(newSeatingMap);
          onClose();
        } else {
          setError('Failed to create seating map');
        }
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An unexpected error occurred');
    } finally {
      setLoading(false);
    }
  };

  const addLayoutItem = (type: LayoutItem['type']) => {
    const newItem: LayoutItem = {
      id: `${type}-${Date.now()}`,
      type,
      x: 50 + (layoutItems.length * 20),
      y: 50 + (layoutItems.length * 20),
      width: type === 'table' ? 80 : type === 'seat_row' ? 200 : 150,
      height: type === 'table' ? 80 : type === 'seat_row' ? 40 : 100,
      label: `${type.replace('_', ' ')} ${layoutItems.length + 1}`,
      capacity: type === 'table' ? 8 : type === 'seat_row' ? 10 : 50
    };
    setLayoutItems(prev => [...prev, newItem]);
  };

  const removeLayoutItem = (id: string) => {
    setLayoutItems(prev => prev.filter(item => item.id !== id));
  };

  const updateLayoutItem = (id: string, updates: Partial<LayoutItem>) => {
    setLayoutItems(prev => prev.map(item => 
      item.id === id ? { ...item, ...updates } : item
    ));
  };

  const totalCapacity = layoutItems.reduce((sum, item) => sum + (item.capacity || 0), 0);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50">
      <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-2xl w-full max-w-sm sm:max-w-2xl lg:max-w-4xl max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-2xl font-light text-white">
              {seatingMap ? 'Edit Seating Map' : 'Create Seating Map'}
            </h2>
            <button
              onClick={onClose}
              className="text-white/60 hover:text-white transition-colors p-2 rounded-full hover:bg-white/10 touch-manipulation"
              aria-label="Close modal"
            >
              <svg className="w-5 h-5 sm:w-6 sm:h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {error && (
            <div className="mb-4 p-3 bg-red-500/20 border border-red-500/30 rounded-lg text-red-200">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <label htmlFor="name" className="block text-sm font-medium text-white/80 mb-2">
                Map Name *
              </label>
              <input
                type="text"
                id="name"
                required
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="e.g., Main Theater Layout"
              />
            </div>

            {!seatingMap && (
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label htmlFor="layoutType" className="block text-sm font-medium text-white/80 mb-2">
                    Layout Type
                  </label>
                  <select
                    id="layoutType"
                    value={layoutType}
                    onChange={(e) => setLayoutType(e.target.value as LayoutType)}
                    className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  >
                    <option value="theater">Theater (Rows of Seats)</option>
                    <option value="reception">Reception (Tables)</option>
                    <option value="concert_hall">Concert Hall (Mixed)</option>
                    <option value="general">General Admission</option>
                  </select>
                </div>

                <div>
                  <label htmlFor="capacity" className="block text-sm font-medium text-white/80 mb-2">
                    Target Capacity
                  </label>
                  <input
                    type="number"
                    id="capacity"
                    min="1"
                    value={capacity}
                    onChange={(e) => setCapacity(parseInt(e.target.value) || 100)}
                    className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
              </div>
            )}

            <div className="border border-white/20 rounded-lg p-4">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-medium text-white">Layout Editor</h3>
                <div className="text-sm text-white/60">
                  Total Capacity: {totalCapacity}
                </div>
              </div>

              <div className="mb-4 flex flex-wrap gap-2">
                <button
                  type="button"
                  onClick={() => addLayoutItem('table')}
                  className="px-3 py-1 bg-blue-600/20 text-blue-300 rounded-lg text-sm hover:bg-blue-600/30 transition-colors"
                >
                  Add Table
                </button>
                <button
                  type="button"
                  onClick={() => addLayoutItem('seat_row')}
                  className="px-3 py-1 bg-green-600/20 text-green-300 rounded-lg text-sm hover:bg-green-600/30 transition-colors"
                >
                  Add Seat Row
                </button>
                <button
                  type="button"
                  onClick={() => addLayoutItem('general_area')}
                  className="px-3 py-1 bg-purple-600/20 text-purple-300 rounded-lg text-sm hover:bg-purple-600/30 transition-colors"
                >
                  Add General Area
                </button>
              </div>

              <div className="bg-white/5 border border-white/10 rounded-lg p-4 min-h-[300px] relative">
                {layoutItems.map((item) => (
                  <div
                    key={item.id}
                    className={`absolute border-2 border-dashed border-white/40 rounded-lg p-2 cursor-move ${
                      item.type === 'table' ? 'bg-blue-500/20' :
                      item.type === 'seat_row' ? 'bg-green-500/20' :
                      'bg-purple-500/20'
                    }`}
                    style={{
                      left: `${item.x}px`,
                      top: `${item.y}px`,
                      width: `${item.width}px`,
                      height: `${item.height}px`
                    }}
                  >
                    <div className="text-xs text-white font-medium">{item.label}</div>
                    <div className="text-xs text-white/60">Cap: {item.capacity}</div>
                    <button
                      type="button"
                      onClick={() => removeLayoutItem(item.id)}
                      className="absolute top-1 right-1 w-4 h-4 bg-red-500/80 text-white rounded-full text-xs hover:bg-red-500 transition-colors"
                    >
                      ×
                    </button>
                  </div>
                ))}
                {layoutItems.length === 0 && (
                  <div className="absolute inset-0 flex items-center justify-center text-white/40">
                    Click "Add" buttons to start building your layout
                  </div>
                )}
              </div>
            </div>

            <div className="flex justify-end space-x-3 pt-4">
              <button
                type="button"
                onClick={onClose}
                className="px-6 py-3 text-white/80 hover:text-white transition-colors"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={loading}
                className="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white rounded-lg font-medium transition-all duration-200 disabled:opacity-50"
              >
                {loading ? 'Saving...' : seatingMap ? 'Update' : 'Create'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}