---
export const prerender = false;

import Layout from '../layouts/Layout.astro';
import { supabase } from '../lib/supabase';

// Check authentication
const { data: { session } } = await Astro.request.headers.get('cookie') 
  ? await supabase.auth.getSession()
  : { data: { session: null } };

if (!session) {
  return Astro.redirect('/');
}

// Get user profile to check organization
const { data: userProfile } = await supabase
  .from('users')
  .select('organization_id, role')
  .eq('id', session.user.id)
  .single();

if (!userProfile?.organization_id && userProfile?.role !== 'admin') {
  return Astro.redirect('/dashboard');
}

// Load inventory pools for the organization
const { data: inventoryPools } = await supabase
  .from('inventory_pools')
  .select(`
    *,
    ticket_type_pool_allocations (
      allocated_quantity,
      ticket_types (
        name,
        event_id,
        events (
          title
        )
      )
    )
  `)
  .eq('organization_id', userProfile.organization_id);
---

<Layout title="Inventory Pools - Black Canyon Tickets">
  <div class="min-h-screen bg-gradient-to-br from-slate-50 to-gray-100">
    <!-- Sticky Navigation -->
    <nav class="sticky top-0 z-50 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">
            <a href="/dashboard" class="text-xl font-medium text-gray-900">
              Black Canyon Tickets
            </a>
          </div>
          <div class="flex items-center space-x-4">
            <a href="/dashboard" class="text-slate-600 hover:text-slate-900 font-medium transition-colors">Dashboard</a>
            <span class="text-sm text-slate-700 font-medium">{session.user.email}</span>
          </div>
        </div>
      </div>
    </nav>

    <main class="max-w-7xl mx-auto py-8 sm:px-6 lg:px-8">
      <div class="px-4 sm:px-0">
        <div class="mb-8">
          <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div>
              <h1 class="text-3xl font-bold text-gray-900">Inventory Pools</h1>
              <p class="text-gray-600 mt-1">Manage ticket inventory across events</p>
            </div>
            <button
              id="create-pool-btn"
              class="inline-flex items-center gap-2 bg-indigo-600 hover:bg-indigo-700 text-white px-6 py-3 rounded-xl font-semibold transition-colors shadow-lg hover:shadow-xl"
            >
              <svg class="w-5 h-5" 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" />
              </svg>
              Create Pool
            </button>
          </div>
        </div>

        <div class="bg-white shadow overflow-hidden sm:rounded-md">
          <div class="px-4 py-5 sm:p-6">
            <div class="grid gap-6">
              {inventoryPools?.length === 0 ? (
                <div class="text-center py-12">
                  <div class="text-gray-400">
                    <svg class="mx-auto h-12 w-12" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
                    </svg>
                  </div>
                  <h3 class="mt-2 text-sm font-medium text-gray-900">No inventory pools</h3>
                  <p class="mt-1 text-sm text-gray-500">Get started by creating your first inventory pool.</p>
                  <div class="mt-6">
                    <button
                      id="create-first-pool-btn"
                      class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700"
                    >
                      Create Inventory Pool
                    </button>
                  </div>
                </div>
              ) : (
                inventoryPools?.map(pool => (
                  <div class="border border-gray-200 rounded-lg p-6">
                    <div class="flex justify-between items-start mb-4">
                      <div>
                        <h3 class="text-lg font-medium text-gray-900">{pool.name}</h3>
                        {pool.description && (
                          <p class="text-gray-600 mt-1">{pool.description}</p>
                        )}
                      </div>
                      <div class="text-right">
                        <span class={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                          pool.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                        }`}>
                          {pool.is_active ? 'Active' : 'Inactive'}
                        </span>
                      </div>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                      <div class="bg-gray-50 rounded-lg p-4">
                        <div class="text-sm font-medium text-gray-500">Total Capacity</div>
                        <div class="text-2xl font-semibold text-gray-900">{pool.total_capacity}</div>
                      </div>
                      <div class="bg-gray-50 rounded-lg p-4">
                        <div class="text-sm font-medium text-gray-500">Allocated</div>
                        <div class="text-2xl font-semibold text-gray-900">{pool.allocated_capacity}</div>
                      </div>
                      <div class="bg-gray-50 rounded-lg p-4">
                        <div class="text-sm font-medium text-gray-500">Available</div>
                        <div class="text-2xl font-semibold text-green-600">{pool.total_capacity - pool.allocated_capacity}</div>
                      </div>
                    </div>

                    {pool.ticket_type_pool_allocations?.length > 0 && (
                      <div>
                        <h4 class="text-sm font-medium text-gray-900 mb-3">Allocations</h4>
                        <div class="space-y-2">
                          {pool.ticket_type_pool_allocations.map(allocation => (
                            <div class="flex justify-between items-center py-2 px-3 bg-gray-50 rounded">
                              <div>
                                <span class="font-medium">{allocation.ticket_types.events.title}</span>
                                <span class="text-gray-500 ml-2">- {allocation.ticket_types.name}</span>
                              </div>
                              <span class="font-medium">{allocation.allocated_quantity} tickets</span>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                ))
              )}
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>

  <!-- Create Pool Modal -->
  <div id="create-pool-modal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
      <div class="mt-3">
        <h3 class="text-lg font-medium text-gray-900 mb-4">Create Inventory Pool</h3>
        
        <form id="create-pool-form" class="space-y-4">
          <div>
            <label for="pool-name" class="block text-sm font-medium text-gray-700">Pool Name</label>
            <input
              type="text"
              id="pool-name"
              name="name"
              required
              class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              placeholder="e.g., VIP Pool, General Admission Pool"
            />
          </div>

          <div>
            <label for="pool-description" class="block text-sm font-medium text-gray-700">Description (optional)</label>
            <textarea
              id="pool-description"
              name="description"
              rows="3"
              class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              placeholder="Describe this inventory pool..."
            ></textarea>
          </div>

          <div>
            <label for="pool-capacity" class="block text-sm font-medium text-gray-700">Total Capacity</label>
            <input
              type="number"
              id="pool-capacity"
              name="total_capacity"
              required
              min="1"
              class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              placeholder="e.g., 1000"
            />
          </div>

          <div class="flex justify-end space-x-3 pt-4">
            <button
              type="button"
              id="cancel-create-pool"
              class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-200 rounded-md hover:bg-gray-300"
            >
              Cancel
            </button>
            <button
              type="submit"
              class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-md hover:bg-indigo-700"
            >
              Create Pool
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</Layout>

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

  const createPoolBtn = document.getElementById('create-pool-btn');
  const createFirstPoolBtn = document.getElementById('create-first-pool-btn');
  const createPoolModal = document.getElementById('create-pool-modal');
  const createPoolForm = document.getElementById('create-pool-form');
  const cancelCreatePool = document.getElementById('cancel-create-pool');

  // Show modal
  function showCreateModal() {
    createPoolModal.classList.remove('hidden');
  }

  // Hide modal
  function hideCreateModal() {
    createPoolModal.classList.add('hidden');
    createPoolForm.reset();
  }

  // Event listeners
  createPoolBtn?.addEventListener('click', showCreateModal);
  createFirstPoolBtn?.addEventListener('click', showCreateModal);
  cancelCreatePool?.addEventListener('click', hideCreateModal);

  // Close modal on outside click
  createPoolModal?.addEventListener('click', (e) => {
    if (e.target === createPoolModal) {
      hideCreateModal();
    }
  });

  // Handle form submission
  createPoolForm?.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const formData = new FormData(createPoolForm);
    const poolData = {
      name: formData.get('name'),
      description: formData.get('description') || null,
      total_capacity: parseInt(formData.get('total_capacity')),
      organization_id: window.userOrgId // This would be set from the server-side data
    };

    try {
      const { data, error } = await supabase
        .from('inventory_pools')
        .insert(poolData)
        .select()
        .single();

      if (error) throw error;

      hideCreateModal();
      location.reload(); // Refresh to show new pool
    } catch (error) {
      console.error('Error creating pool:', error);
      alert('Error creating inventory pool. Please try again.');
    }
  });

  // Store organization ID for form submission
  window.userOrgId = '{userProfile?.organization_id}';
</script>