---
import Layout from '../layouts/Layout.astro';
---

<Layout title="Venue Management - Black Canyon Tickets">
  <style>
    .bg-grid-pattern {
      background-image: 
        linear-gradient(rgba(255, 255, 255, 0.1) 1px, transparent 1px),
        linear-gradient(90deg, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
      background-size: 20px 20px;
    }
  </style>
  <div class="min-h-screen bg-gradient-to-br from-indigo-900 via-purple-900 to-slate-900">
    <!-- Animated background elements -->
    <div class="fixed inset-0 overflow-hidden pointer-events-none">
      <div class="absolute -top-40 -right-40 w-80 h-80 bg-gradient-to-br from-purple-600/20 to-pink-600/20 rounded-full blur-3xl animate-pulse"></div>
      <div class="absolute -bottom-40 -left-40 w-80 h-80 bg-gradient-to-br from-blue-600/20 to-cyan-600/20 rounded-full blur-3xl animate-pulse"></div>
      <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-96 h-96 bg-gradient-to-br from-indigo-600/10 to-purple-600/10 rounded-full blur-3xl animate-pulse"></div>
    </div>
    
    <!-- Grid pattern overlay -->
    <div class="absolute inset-0 bg-grid-pattern opacity-5"></div>
    <!-- Elegant Navigation -->
    <nav class="bg-white/90 backdrop-blur-lg shadow-xl border-b border-slate-200/50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-20">
          <div class="flex items-center space-x-8">
            <a href="/dashboard" class="text-2xl font-light text-slate-800 tracking-wide">
              Black Canyon <span class="font-semibold">Tickets</span>
            </a>
            <div class="hidden md:flex items-center space-x-6">
              <a href="/dashboard" class="text-slate-600 hover:text-slate-900 font-medium transition-colors duration-200">Dashboard</a>
              <a href="/venues" class="text-slate-900 border-b-2 border-slate-800 pb-1 font-medium">Venues</a>
              <a href="/events/new" class="text-slate-600 hover:text-slate-900 font-medium transition-colors duration-200">Create Event</a>
            </div>
          </div>
          <div class="flex items-center space-x-4">
            <span id="user-name" class="text-sm text-slate-700 font-medium"></span>
            <button
              id="logout-btn"
              class="bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 hover:shadow-md"
            >
              Sign Out
            </button>
          </div>
        </div>
      </div>
    </nav>

    <main class="max-w-7xl mx-auto py-12 px-4 sm:px-6 lg:px-8">
      <!-- Header Section -->
      <div class="mb-12">
        <div class="text-center mb-8">
          <h1 class="text-4xl font-light text-slate-900 mb-4 tracking-wide">
            Venue Management
          </h1>
          <p class="text-xl text-slate-600 max-w-2xl mx-auto leading-relaxed">
            Create and manage elegant venues for your distinguished events
          </p>
        </div>
        
        <div class="flex justify-center">
          <button
            id="create-venue-btn"
            class="bg-gradient-to-r from-slate-800 to-slate-900 hover:from-slate-900 hover:to-black text-white px-8 py-4 rounded-2xl font-medium text-lg shadow-xl hover:shadow-2xl transition-all duration-300 transform hover:-translate-y-1"
          >
            <svg class="w-5 h-5 inline-block mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
            Create New Venue
          </button>
        </div>
      </div>

      <!-- Venues Grid -->
      <div id="venues-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        <!-- Venues will be loaded here -->
      </div>

      <!-- Empty State -->
      <div id="empty-state" class="text-center py-16 hidden">
        <div class="mx-auto h-24 w-24 text-slate-400 mb-4">
          <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" 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"></path>
          </svg>
        </div>
        <h3 class="text-2xl font-light text-slate-900 mb-2">No venues created yet</h3>
        <p class="text-slate-600 mb-6">Create your first venue to start hosting distinguished events</p>
        <button
          onclick="showCreateVenueModal()"
          class="bg-slate-800 hover:bg-slate-900 text-white px-6 py-3 rounded-xl font-medium transition-colors duration-200"
        >
          Create Your First Venue
        </button>
      </div>
    </main>

    <!-- Create/Edit Venue Modal -->
    <div id="venue-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm hidden z-50">
      <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-3xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
          <form id="venue-form" class="p-8">
            <div class="mb-8">
              <h2 id="modal-title" class="text-3xl font-light text-slate-900 mb-2">Create New Venue</h2>
              <p class="text-slate-600">Define the perfect setting for your distinguished events</p>
            </div>

            <div class="space-y-6">
              <!-- Basic Information -->
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label for="venue-name" class="block text-sm font-semibold text-slate-700 mb-2">Venue Name</label>
                  <input
                    type="text"
                    id="venue-name"
                    name="name"
                    required
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="Grand Ballroom"
                  />
                </div>
                
                <div>
                  <label for="venue-type" class="block text-sm font-semibold text-slate-700 mb-2">Venue Type</label>
                  <select
                    id="venue-type"
                    name="type"
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                  >
                    <option value="hotel">Luxury Hotel</option>
                    <option value="resort">Resort</option>
                    <option value="private_club">Private Club</option>
                    <option value="restaurant">Fine Dining</option>
                    <option value="gallery">Gallery</option>
                    <option value="theater">Theater</option>
                    <option value="outdoor">Outdoor Venue</option>
                    <option value="private_residence">Private Residence</option>
                    <option value="other">Other</option>
                  </select>
                </div>
              </div>

              <!-- Location -->
              <div>
                <label for="venue-address" class="block text-sm font-semibold text-slate-700 mb-2">Address</label>
                <textarea
                  id="venue-address"
                  name="address"
                  rows="3"
                  required
                  class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                  placeholder="123 Main Street, City, State 12345"
                ></textarea>
              </div>

              <!-- Capacity & Details -->
              <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                  <label for="venue-capacity" class="block text-sm font-semibold text-slate-700 mb-2">Max Capacity</label>
                  <input
                    type="number"
                    id="venue-capacity"
                    name="capacity"
                    min="1"
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="150"
                  />
                </div>
                
                <div>
                  <label for="venue-phone" class="block text-sm font-semibold text-slate-700 mb-2">Phone</label>
                  <input
                    type="tel"
                    id="venue-phone"
                    name="phone"
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="(555) 123-4567"
                  />
                </div>
                
                <div>
                  <label for="venue-website" class="block text-sm font-semibold text-slate-700 mb-2">Website</label>
                  <input
                    type="url"
                    id="venue-website"
                    name="website"
                    class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                    placeholder="https://example.com"
                  />
                </div>
              </div>

              <!-- Description -->
              <div>
                <label for="venue-description" class="block text-sm font-semibold text-slate-700 mb-2">Description</label>
                <textarea
                  id="venue-description"
                  name="description"
                  rows="4"
                  class="w-full px-4 py-3 border border-slate-300 rounded-xl focus:ring-2 focus:ring-slate-500 focus:border-transparent transition-all duration-200"
                  placeholder="An elegant venue perfect for sophisticated events..."
                ></textarea>
              </div>

              <!-- Amenities -->
              <div>
                <label class="block text-sm font-semibold text-slate-700 mb-3">Amenities</label>
                <div class="grid grid-cols-2 md:grid-cols-3 gap-3">
                  <label class="flex items-center space-x-2 text-sm">
                    <input type="checkbox" name="amenities" value="parking" class="rounded border-slate-300">
                    <span>Valet Parking</span>
                  </label>
                  <label class="flex items-center space-x-2 text-sm">
                    <input type="checkbox" name="amenities" value="catering" class="rounded border-slate-300">
                    <span>In-house Catering</span>
                  </label>
                  <label class="flex items-center space-x-2 text-sm">
                    <input type="checkbox" name="amenities" value="av" class="rounded border-slate-300">
                    <span>A/V Equipment</span>
                  </label>
                  <label class="flex items-center space-x-2 text-sm">
                    <input type="checkbox" name="amenities" value="wifi" class="rounded border-slate-300">
                    <span>High-Speed WiFi</span>
                  </label>
                  <label class="flex items-center space-x-2 text-sm">
                    <input type="checkbox" name="amenities" value="climate" class="rounded border-slate-300">
                    <span>Climate Control</span>
                  </label>
                  <label class="flex items-center space-x-2 text-sm">
                    <input type="checkbox" name="amenities" value="accessible" class="rounded border-slate-300">
                    <span>Accessibility</span>
                  </label>
                </div>
              </div>
            </div>

            <!-- Modal Actions -->
            <div class="flex justify-end space-x-4 mt-8 pt-6 border-t border-slate-200">
              <button
                type="button"
                onclick="closeVenueModal()"
                class="px-6 py-3 border border-slate-300 text-slate-700 rounded-xl hover:bg-slate-50 font-medium transition-colors duration-200"
              >
                Cancel
              </button>
              <button
                type="submit"
                class="px-8 py-3 bg-gradient-to-r from-slate-800 to-slate-900 text-white rounded-xl hover:from-slate-900 hover:to-black font-medium transition-all duration-200"
              >
                <span id="submit-text">Create Venue</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Seating Maps Modal -->
    <div id="seating-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm hidden z-50">
      <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-3xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
          <div class="p-8">
            <h2 class="text-3xl font-light text-slate-900 mb-6">Seating Maps</h2>
            <div id="seating-maps-content">
              <!-- Seating maps will be loaded here -->
            </div>
            <div class="flex justify-end mt-6">
              <button
                onclick="closeSeatingModal()"
                class="px-6 py-3 border border-slate-300 text-slate-700 rounded-xl hover:bg-slate-50 font-medium transition-colors duration-200"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</Layout>

<script>
  import { supabase } from '../lib/supabase';

  const venuesContainer = document.getElementById('venues-container');
  const emptyState = document.getElementById('empty-state');
  const venueModal = document.getElementById('venue-modal');
  const venueForm = document.getElementById('venue-form');
  const createVenueBtn = document.getElementById('create-venue-btn');
  const userNameSpan = document.getElementById('user-name');
  const logoutBtn = document.getElementById('logout-btn');

  let currentVenueId = null;
  let currentOrganizationId = null;

  // Check authentication
  async function checkAuth() {
    const { data: { session } } = await supabase.auth.getSession();
    if (!session) {
      window.location.href = '/';
      return null;
    }

    // Get user details
    const { data: user } = await supabase
      .from('users')
      .select('name, email, organization_id')
      .eq('id', session.user.id)
      .single();

    if (user) {
      userNameSpan.textContent = user.name || user.email;
      currentOrganizationId = user.organization_id;
      
      // If user doesn't have an organization, create one
      if (!currentOrganizationId) {
        try {
          const { data: org, error: orgError } = await supabase
            .from('organizations')
            .insert([
              { name: `${user.name || user.email}'s Organization` }
            ])
            .select()
            .single();
            
          if (!orgError) {
            currentOrganizationId = org.id;
            
            // Update user with organization_id
            await supabase
              .from('users')
              .update({ organization_id: currentOrganizationId })
              .eq('id', session.user.id);
          }
        } catch (error) {
          console.error('Error creating organization:', error);
        }
      }
    }

    return session;
  }

  // Load venues
  async function loadVenues() {
    try {
      const { data: venues, error } = await supabase
        .from('venues')
        .select(`
          *,
          seating_maps(count)
        `)
        .eq('organization_id', currentOrganizationId)
        .order('created_at', { ascending: false });

      if (error) throw error;

      if (venues.length === 0) {
        venuesContainer.classList.add('hidden');
        emptyState.classList.remove('hidden');
        return;
      }

      venuesContainer.classList.remove('hidden');
      emptyState.classList.add('hidden');

      venuesContainer.innerHTML = venues.map(venue => `
        <div class="bg-white rounded-2xl shadow-lg hover:shadow-xl hover:-translate-y-0.5 transition-all duration-200 ease-out overflow-hidden border border-slate-200/50">
          <div class="p-6">
            <div class="flex justify-between items-start mb-4">
              <div>
                <h3 class="text-xl font-semibold text-slate-900 mb-1">${venue.name}</h3>
                <p class="text-sm text-slate-600 capitalize">${venue.type?.replace('_', ' ') || 'Venue'}</p>
              </div>
              <span class="px-3 py-1 bg-slate-100 text-slate-700 rounded-full text-xs font-medium">
                ${venue.capacity || 'No limit'} ${venue.capacity ? 'guests' : ''}
              </span>
            </div>
            
            <p class="text-slate-600 text-sm mb-4 line-clamp-2">
              ${venue.description || 'No description available'}
            </p>
            
            <div class="text-xs text-slate-500 mb-4">
              <p>${venue.address || 'No address specified'}</p>
              ${venue.phone ? `<p class="mt-1">${venue.phone}</p>` : ''}
            </div>
            
            ${venue.amenities ? `
              <div class="flex flex-wrap gap-1 mb-4">
                ${JSON.parse(venue.amenities).slice(0, 3).map(amenity => `
                  <span class="px-2 py-1 bg-slate-50 text-slate-600 rounded text-xs">${amenity}</span>
                `).join('')}
                ${JSON.parse(venue.amenities).length > 3 ? `<span class="text-xs text-slate-500">+${JSON.parse(venue.amenities).length - 3} more</span>` : ''}
              </div>
            ` : ''}
            
            <div class="flex items-center justify-between pt-4 border-t border-slate-100">
              <div class="text-xs text-slate-500">
                ${venue.seating_maps?.[0]?.count || 0} seating map${venue.seating_maps?.[0]?.count !== 1 ? 's' : ''}
              </div>
              <div class="flex space-x-2">
                <button
                  onclick="viewSeatingMaps('${venue.id}')"
                  class="text-slate-600 hover:text-slate-900 text-sm font-medium transition-colors duration-200"
                >
                  Seating
                </button>
                <button
                  onclick="editVenue('${venue.id}')"
                  class="text-slate-600 hover:text-slate-900 text-sm font-medium transition-colors duration-200"
                >
                  Edit
                </button>
                <button
                  onclick="deleteVenue('${venue.id}')"
                  class="text-red-600 hover:text-red-800 text-sm font-medium transition-colors duration-200"
                >
                  Delete
                </button>
              </div>
            </div>
          </div>
        </div>
      `).join('');

    } catch (error) {
      console.error('Error loading venues:', error);
    }
  }

  // Show create venue modal
  function showCreateVenueModal() {
    currentVenueId = null;
    document.getElementById('modal-title').textContent = 'Create New Venue';
    document.getElementById('submit-text').textContent = 'Create Venue';
    venueForm.reset();
    venueModal.classList.remove('hidden');
  }

  // Edit venue
  async function editVenue(venueId) {
    try {
      currentVenueId = venueId;
      
      const { data: venue, error } = await supabase
        .from('venues')
        .select('*')
        .eq('id', venueId)
        .single();

      if (error) throw error;

      // Populate form
      document.getElementById('venue-name').value = venue.name || '';
      document.getElementById('venue-type').value = venue.type || '';
      document.getElementById('venue-address').value = venue.address || '';
      document.getElementById('venue-capacity').value = venue.capacity || '';
      document.getElementById('venue-phone').value = venue.phone || '';
      document.getElementById('venue-website').value = venue.website || '';
      document.getElementById('venue-description').value = venue.description || '';

      // Set amenities
      if (venue.amenities) {
        const amenities = JSON.parse(venue.amenities);
        document.querySelectorAll('input[name="amenities"]').forEach(checkbox => {
          checkbox.checked = amenities.includes(checkbox.value);
        });
      }

      document.getElementById('modal-title').textContent = 'Edit Venue';
      document.getElementById('submit-text').textContent = 'Update Venue';
      venueModal.classList.remove('hidden');

    } catch (error) {
      console.error('Error loading venue:', error);
      alert('Error loading venue data');
    }
  }

  // Close venue modal
  function closeVenueModal() {
    venueModal.classList.add('hidden');
    currentVenueId = null;
  }

  // Save venue
  venueForm.addEventListener('submit', async (e) => {
    e.preventDefault();

    try {
      const formData = new FormData(venueForm);
      const amenities = Array.from(document.querySelectorAll('input[name="amenities"]:checked'))
        .map(cb => cb.value);

      const venueData = {
        name: formData.get('name'),
        type: formData.get('type'),
        address: formData.get('address'),
        capacity: formData.get('capacity') ? parseInt(formData.get('capacity')) : null,
        phone: formData.get('phone') || null,
        website: formData.get('website') || null,
        description: formData.get('description') || null,
        amenities: JSON.stringify(amenities),
        organization_id: currentOrganizationId
      };

      let error;
      if (currentVenueId) {
        ({ error } = await supabase
          .from('venues')
          .update(venueData)
          .eq('id', currentVenueId));
      } else {
        ({ error } = await supabase
          .from('venues')
          .insert([venueData]));
      }

      if (error) throw error;

      closeVenueModal();
      await loadVenues();

    } catch (error) {
      console.error('Error saving venue:', error);
      alert('Error saving venue: ' + error.message);
    }
  });

  // Delete venue
  async function deleteVenue(venueId) {
    if (!confirm('Are you sure you want to delete this venue? This action cannot be undone.')) {
      return;
    }

    try {
      const { error } = await supabase
        .from('venues')
        .delete()
        .eq('id', venueId);

      if (error) throw error;

      await loadVenues();
    } catch (error) {
      console.error('Error deleting venue:', error);
      alert('Error deleting venue: ' + error.message);
    }
  }

  // View seating maps
  async function viewSeatingMaps(venueId) {
    // TODO: Implement seating maps view
    alert('Seating maps management coming soon!');
  }

  // Close seating modal
  function closeSeatingModal() {
    document.getElementById('seating-modal').classList.add('hidden');
  }

  // Event listeners
  createVenueBtn.addEventListener('click', showCreateVenueModal);
  logoutBtn.addEventListener('click', async () => {
    await supabase.auth.signOut();
    window.location.href = '/';
  });

  // Make functions globally available
  window.showCreateVenueModal = showCreateVenueModal;
  window.editVenue = editVenue;
  window.deleteVenue = deleteVenue;
  window.viewSeatingMaps = viewSeatingMaps;
  window.closeVenueModal = closeVenueModal;
  window.closeSeatingModal = closeSeatingModal;

  // Initialize
  checkAuth().then(session => {
    if (session && currentOrganizationId) {
      loadVenues();
    }
  });
</script>

<style>
  .line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
</style>