---
export const prerender = false;

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

<Layout title="Admin Dashboard - Black Canyon Tickets">
  <div class="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100">
    <Navigation 
      title="Admin Dashboard" 
      showBackLink={true} 
      backLinkUrl="/dashboard" 
      backLinkText="← Dashboard" 
    />

    <main class="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
      <!-- Admin Header -->
      <div class="bg-gradient-to-r from-red-600 to-red-700 rounded-3xl shadow-2xl mb-8 overflow-hidden">
        <div class="px-8 py-12 text-white">
          <div class="flex justify-between items-center">
            <div>
              <h1 class="text-4xl font-light mb-3 tracking-wide">Admin Dashboard</h1>
              <p class="text-red-100 text-lg">Platform management and oversight</p>
            </div>
            <div class="text-right">
              <div class="text-3xl font-semibold" id="total-platform-revenue">$0</div>
              <div class="text-sm text-red-100">Total Platform Revenue</div>
            </div>
          </div>
        </div>
      </div>

      <!-- Admin Navigation Tabs -->
      <div class="bg-white rounded-2xl shadow-lg border border-slate-200/50 mb-8">
        <div class="border-b border-slate-200">
          <nav class="flex space-x-8 px-8">
            <button 
              onclick="showTab('tickets')" 
              class="tab-btn py-4 px-2 border-b-2 border-transparent text-slate-600 hover:text-slate-900 hover:border-slate-300 font-medium transition-colors duration-200 active"
            >
              Ticket Management
            </button>
            <button 
              onclick="showTab('subscriptions')" 
              class="tab-btn py-4 px-2 border-b-2 border-transparent text-slate-600 hover:text-slate-900 hover:border-slate-300 font-medium transition-colors duration-200"
            >
              Subscriptions
            </button>
            <button 
              onclick="showTab('organizations')" 
              class="tab-btn py-4 px-2 border-b-2 border-transparent text-slate-600 hover:text-slate-900 hover:border-slate-300 font-medium transition-colors duration-200"
            >
              Organizations
            </button>
            <button 
              onclick="showTab('analytics')" 
              class="tab-btn py-4 px-2 border-b-2 border-transparent text-slate-600 hover:text-slate-900 hover:border-slate-300 font-medium transition-colors duration-200"
            >
              Platform Analytics
            </button>
          </nav>
        </div>

        <div class="p-8">
          <!-- Ticket Management Tab -->
          <div id="content-tickets" class="tab-content">
            <div class="flex justify-between items-center mb-6">
              <div>
                <h2 class="text-2xl font-light text-slate-900 mb-2">Ticket Management</h2>
                <p class="text-slate-600">Manage all tickets across the platform</p>
              </div>
              <div class="flex space-x-3">
                <select id="ticket-filter-status" class="border border-slate-300 rounded-lg px-3 py-2 text-sm">
                  <option value="">All Statuses</option>
                  <option value="none">Active</option>
                  <option value="completed">Refunded</option>
                  <option value="requested">Refund Requested</option>
                </select>
                <input 
                  type="text" 
                  id="ticket-filter-email" 
                  placeholder="Filter by email..." 
                  class="border border-slate-300 rounded-lg px-3 py-2 text-sm w-48"
                >
                <button 
                  onclick="loadTickets()" 
                  class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg font-medium transition-colors"
                >
                  Filter
                </button>
              </div>
            </div>
            
            <div id="tickets-content">
              <!-- Tickets will be loaded here -->
            </div>
          </div>

          <!-- Subscriptions Tab -->
          <div id="content-subscriptions" class="tab-content hidden">
            <div class="flex justify-between items-center mb-6">
              <div>
                <h2 class="text-2xl font-light text-slate-900 mb-2">Subscription Management</h2>
                <p class="text-slate-600">Manage organization subscriptions and billing</p>
              </div>
              <div class="flex space-x-3">
                <select id="subscription-filter-status" class="border border-slate-300 rounded-lg px-3 py-2 text-sm">
                  <option value="">All Statuses</option>
                  <option value="active">Active</option>
                  <option value="inactive">Inactive</option>
                  <option value="suspended">Suspended</option>
                </select>
                <button 
                  onclick="loadSubscriptions()" 
                  class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg font-medium transition-colors"
                >
                  Refresh
                </button>
              </div>
            </div>
            
            <div id="subscriptions-content">
              <!-- Subscriptions will be loaded here -->
            </div>
          </div>

          <!-- Organizations Tab -->
          <div id="content-organizations" class="tab-content hidden">
            <div class="flex justify-between items-center mb-6">
              <div>
                <h2 class="text-2xl font-light text-slate-900 mb-2">Organizations</h2>
                <p class="text-slate-600">Manage all organizations on the platform</p>
              </div>
            </div>
            
            <div id="organizations-content">
              <!-- Organizations will be loaded here -->
            </div>
          </div>

          <!-- Analytics Tab -->
          <div id="content-analytics" class="tab-content hidden">
            <div class="flex justify-between items-center mb-6">
              <div>
                <h2 class="text-2xl font-light text-slate-900 mb-2">Platform Analytics</h2>
                <p class="text-slate-600">Platform-wide metrics and insights</p>
              </div>
            </div>
            
            <div id="analytics-content">
              <!-- Analytics will be loaded here -->
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</Layout>

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

  let currentPage = 1;
  const pageSize = 50;

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

    // Check if user is admin
    const { data: userRole } = await supabase
      .from('user_roles')
      .select('role')
      .eq('user_id', session.user.id)
      .eq('role', 'admin')
      .single();

    if (!userRole) {
      alert('Admin access required');
      window.location.href = '/dashboard';
      return null;
    }

    return session;
  }

  function showTab(tabName) {
    // Hide all tabs
    document.querySelectorAll('.tab-content').forEach(tab => {
      tab.classList.add('hidden');
    });
    
    // Remove active class from all tab buttons
    document.querySelectorAll('.tab-btn').forEach(btn => {
      btn.classList.remove('active', 'border-red-600', 'text-red-600');
      btn.classList.add('border-transparent', 'text-slate-600');
    });
    
    // Show selected tab
    const targetTab = document.getElementById(`content-${tabName}`);
    if (targetTab) {
      targetTab.classList.remove('hidden');
    }
    
    // Mark button as active
    const activeBtn = event?.target || document.querySelector(`[onclick="showTab('${tabName}')"]`);
    if (activeBtn) {
      activeBtn.classList.add('active', 'border-red-600', 'text-red-600');
      activeBtn.classList.remove('border-transparent', 'text-slate-600');
    }
    
    // Load content for the tab
    switch (tabName) {
      case 'tickets':
        loadTickets();
        break;
      case 'subscriptions':
        loadSubscriptions();
        break;
      case 'organizations':
        loadOrganizations();
        break;
      case 'analytics':
        loadAnalytics();
        break;
    }
  }

  async function loadTickets() {
    try {
      const statusFilter = document.getElementById('ticket-filter-status').value;
      const emailFilter = document.getElementById('ticket-filter-email').value;
      
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: pageSize.toString()
      });
      
      if (statusFilter) params.append('refund_status', statusFilter);
      if (emailFilter) params.append('email', emailFilter);

      const response = await fetch(`/api/admin/tickets?${params}`);
      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Failed to load tickets');
      }

      renderTickets(result.tickets, result.pagination);
    } catch (error) {
      console.error('Error loading tickets:', error);
      document.getElementById('tickets-content').innerHTML = `
        <div class="text-red-600 bg-red-50 p-4 rounded-lg">
          <p class="font-medium">Error loading tickets</p>
          <p class="text-sm">${error.message}</p>
        </div>
      `;
    }
  }

  function renderTickets(tickets, pagination) {
    if (tickets.length === 0) {
      document.getElementById('tickets-content').innerHTML = `
        <div class="text-center py-12">
          <p class="text-slate-500 text-lg">No tickets found</p>
        </div>
      `;
      return;
    }

    const ticketsHtml = `
      <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
        <div class="overflow-x-auto">
          <table class="w-full">
            <thead class="bg-slate-50 border-b border-slate-200">
              <tr>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Ticket ID</th>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Event</th>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Customer</th>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Organization</th>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Price</th>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Status</th>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Actions</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-slate-200">
              ${tickets.map(ticket => `
                <tr class="hover:bg-slate-50">
                  <td class="py-3 px-4 font-mono text-sm">${ticket.uuid?.substring(0, 8) || 'N/A'}...</td>
                  <td class="py-3 px-4">
                    <div class="text-sm">
                      <div class="font-medium text-slate-900">${ticket.events?.title || 'Unknown Event'}</div>
                      <div class="text-slate-500">${ticket.events?.venue || ''}</div>
                    </div>
                  </td>
                  <td class="py-3 px-4">
                    <div class="text-sm">
                      <div class="font-medium text-slate-900">${ticket.purchaser_name || 'Not provided'}</div>
                      <div class="text-slate-500">${ticket.purchaser_email}</div>
                    </div>
                  </td>
                  <td class="py-3 px-4">
                    <div class="text-sm text-slate-700">${ticket.events?.organizations?.name || 'Unknown'}</div>
                  </td>
                  <td class="py-3 px-4">
                    <span class="text-sm font-medium text-slate-900">$${ticket.price}</span>
                  </td>
                  <td class="py-3 px-4">
                    <div class="flex flex-col space-y-1">
                      <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${ticket.checked_in ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}">
                        ${ticket.checked_in ? 'Checked In' : 'Not Checked In'}
                      </span>
                      ${ticket.refund_status !== 'none' ? `
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                          ${ticket.refund_status.replace('_', ' ')}
                        </span>
                      ` : ''}
                    </div>
                  </td>
                  <td class="py-3 px-4">
                    <div class="flex space-x-2">
                      ${!ticket.checked_in ? `
                        <button 
                          onclick="adminCheckInTicket('${ticket.id}')"
                          class="text-green-600 hover:text-green-900 text-sm font-medium"
                        >
                          Check In
                        </button>
                      ` : ''}
                      ${ticket.refund_status === 'none' ? `
                        <button 
                          onclick="adminCancelTicket('${ticket.id}')"
                          class="text-red-600 hover:text-red-900 text-sm font-medium"
                        >
                          Cancel
                        </button>
                      ` : ''}
                    </div>
                  </td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>
        <div class="px-6 py-4 border-t border-slate-200 bg-slate-50">
          <div class="flex justify-between items-center">
            <div class="text-sm text-slate-700">
              Showing ${((pagination.page - 1) * pagination.limit) + 1} to ${Math.min(pagination.page * pagination.limit, pagination.total)} of ${pagination.total} tickets
            </div>
            <div class="flex space-x-2">
              ${pagination.page > 1 ? `
                <button onclick="changePage(${pagination.page - 1})" class="px-3 py-2 border border-slate-300 rounded-lg text-sm hover:bg-slate-50">
                  Previous
                </button>
              ` : ''}
              ${pagination.page < pagination.pages ? `
                <button onclick="changePage(${pagination.page + 1})" class="px-3 py-2 border border-slate-300 rounded-lg text-sm hover:bg-slate-50">
                  Next
                </button>
              ` : ''}
            </div>
          </div>
        </div>
      </div>
    `;

    document.getElementById('tickets-content').innerHTML = ticketsHtml;
  }

  async function loadSubscriptions() {
    try {
      const statusFilter = document.getElementById('subscription-filter-status').value;
      
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: pageSize.toString()
      });
      
      if (statusFilter) params.append('status', statusFilter);

      const response = await fetch(`/api/admin/subscriptions?${params}`);
      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Failed to load subscriptions');
      }

      renderSubscriptions(result.organizations, result.pagination);
    } catch (error) {
      console.error('Error loading subscriptions:', error);
      document.getElementById('subscriptions-content').innerHTML = `
        <div class="text-red-600 bg-red-50 p-4 rounded-lg">
          <p class="font-medium">Error loading subscriptions</p>
          <p class="text-sm">${error.message}</p>
        </div>
      `;
    }
  }

  function renderSubscriptions(organizations, pagination) {
    if (organizations.length === 0) {
      document.getElementById('subscriptions-content').innerHTML = `
        <div class="text-center py-12">
          <p class="text-slate-500 text-lg">No subscriptions found</p>
        </div>
      `;
      return;
    }

    const subscriptionsHtml = `
      <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
        <div class="overflow-x-auto">
          <table class="w-full">
            <thead class="bg-slate-50 border-b border-slate-200">
              <tr>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Organization</th>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Users</th>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Stripe Account</th>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Status</th>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Created</th>
                <th class="text-left py-3 px-4 font-medium text-slate-700">Actions</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-slate-200">
              ${organizations.map(org => `
                <tr class="hover:bg-slate-50">
                  <td class="py-3 px-4">
                    <div class="font-medium text-slate-900">${org.name}</div>
                  </td>
                  <td class="py-3 px-4">
                    <div class="text-sm text-slate-600">${org.users?.length || 0} users</div>
                  </td>
                  <td class="py-3 px-4">
                    <div class="text-sm">
                      ${org.subscription ? `
                        <div class="font-mono text-xs text-slate-600">${org.subscription.stripe_account_id?.substring(0, 12) || 'N/A'}...</div>
                        <div class="text-xs text-slate-500">${org.subscription.country || 'Unknown'}</div>
                      ` : 'Not connected'}
                    </div>
                  </td>
                  <td class="py-3 px-4">
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                      org.subscription?.account_status === 'active' ? 'bg-green-100 text-green-800' : 
                      org.subscription?.account_status === 'inactive' ? 'bg-yellow-100 text-yellow-800' : 
                      'bg-red-100 text-red-800'
                    }">
                      ${org.subscription?.account_status || 'inactive'}
                    </span>
                  </td>
                  <td class="py-3 px-4">
                    <div class="text-sm text-slate-600">${new Date(org.created_at).toLocaleDateString()}</div>
                  </td>
                  <td class="py-3 px-4">
                    <div class="flex space-x-2">
                      ${org.subscription?.account_status === 'active' ? `
                        <button 
                          onclick="suspendAccount('${org.id}')"
                          class="text-red-600 hover:text-red-900 text-sm font-medium"
                        >
                          Suspend
                        </button>
                      ` : `
                        <button 
                          onclick="reactivateAccount('${org.id}')"
                          class="text-green-600 hover:text-green-900 text-sm font-medium"
                        >
                          Reactivate
                        </button>
                      `}
                    </div>
                  </td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>
      </div>
    `;

    document.getElementById('subscriptions-content').innerHTML = subscriptionsHtml;
  }

  async function loadOrganizations() {
    document.getElementById('organizations-content').innerHTML = '<p class="text-slate-500">Organizations management coming soon...</p>';
  }

  async function loadAnalytics() {
    document.getElementById('analytics-content').innerHTML = '<p class="text-slate-500">Platform analytics coming soon...</p>';
  }

  // Action functions
  async function adminCheckInTicket(ticketId) {
    try {
      const response = await fetch('/api/admin/tickets', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          action: 'check_in',
          ticket_id: ticketId
        })
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Failed to check in ticket');
      }

      alert('Ticket checked in successfully');
      loadTickets();
    } catch (error) {
      console.error('Error checking in ticket:', error);
      alert('Error checking in ticket: ' + error.message);
    }
  }

  async function adminCancelTicket(ticketId) {
    if (!confirm('Cancel this ticket? This will mark it as refunded.')) {
      return;
    }

    try {
      const response = await fetch('/api/admin/tickets', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          action: 'cancel_ticket',
          ticket_id: ticketId
        })
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Failed to cancel ticket');
      }

      alert('Ticket cancelled successfully');
      loadTickets();
    } catch (error) {
      console.error('Error cancelling ticket:', error);
      alert('Error cancelling ticket: ' + error.message);
    }
  }

  async function suspendAccount(organizationId) {
    if (!confirm('Suspend this organization account?')) {
      return;
    }

    try {
      const response = await fetch('/api/admin/subscriptions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          action: 'suspend_account',
          organization_id: organizationId
        })
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Failed to suspend account');
      }

      alert('Account suspended successfully');
      loadSubscriptions();
    } catch (error) {
      console.error('Error suspending account:', error);
      alert('Error suspending account: ' + error.message);
    }
  }

  async function reactivateAccount(organizationId) {
    try {
      const response = await fetch('/api/admin/subscriptions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          action: 'reactivate_account',
          organization_id: organizationId
        })
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Failed to reactivate account');
      }

      alert('Account reactivated successfully');
      loadSubscriptions();
    } catch (error) {
      console.error('Error reactivating account:', error);
      alert('Error reactivating account: ' + error.message);
    }
  }

  function changePage(page) {
    currentPage = page;
    loadTickets();
  }

  // Global functions
  window.showTab = showTab;
  window.loadTickets = loadTickets;
  window.loadSubscriptions = loadSubscriptions;
  window.adminCheckInTicket = adminCheckInTicket;
  window.adminCancelTicket = adminCancelTicket;
  window.suspendAccount = suspendAccount;
  window.reactivateAccount = reactivateAccount;
  window.changePage = changePage;

  // Initialize
  checkAuth().then(session => {
    if (session) {
      showTab('tickets');
    }
  });
</script>

<style>
  .tab-btn.active {
    border-color: #dc2626 !important;
    color: #dc2626 !important;
  }
</style>