---
import SecureLayout from '../../layouts/SecureLayout.astro';
import ProtectedRoute from '../../components/ProtectedRoute.astro';
---

<ProtectedRoute>
  <SecureLayout title="Pending Approvals - Admin Dashboard" showBackLink={true} backLinkUrl="/admin">
    <div class="min-h-screen bg-gray-50">
      <div class="max-w-7xl mx-auto px-6 py-8">
        <!-- Header -->
        <div class="mb-8">
          <div class="bg-white rounded-lg shadow-sm border p-6">
            <div class="flex items-center justify-between">
              <div>
                <h1 class="text-2xl font-bold text-gray-900 mb-2">Pending Approvals</h1>
                <p class="text-gray-600">Review and approve new organization applications</p>
              </div>
              <div class="flex items-center space-x-4">
                <div class="bg-yellow-100 text-yellow-800 px-3 py-1 rounded-full text-sm font-medium">
                  <span id="pending-count">0</span> Pending
                </div>
                <button
                  id="refresh-btn"
                  class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md font-medium transition-colors"
                >
                  Refresh
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Auto-Approval Rules -->
        <div class="mb-8">
          <div class="bg-white rounded-lg shadow-sm border p-6">
            <div class="flex items-center justify-between mb-4">
              <h2 class="text-lg font-semibold text-gray-900">Auto-Approval Rules</h2>
              <button
                id="add-rule-btn"
                class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-md font-medium transition-colors"
              >
                Add Rule
              </button>
            </div>
            <div id="rules-container" class="space-y-3">
              <!-- Rules will be loaded here -->
            </div>
          </div>
        </div>

        <!-- Pending Applications -->
        <div class="bg-white rounded-lg shadow-sm border">
          <div class="p-6 border-b border-gray-200">
            <h2 class="text-lg font-semibold text-gray-900">Pending Applications</h2>
          </div>
          
          <div id="applications-container">
            <!-- Loading state -->
            <div id="loading-state" class="p-8 text-center">
              <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
              <p class="text-gray-500">Loading applications...</p>
            </div>
            
            <!-- Empty state -->
            <div id="empty-state" class="hidden p-8 text-center">
              <div class="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <svg class="w-6 h-6 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                </svg>
              </div>
              <h3 class="text-lg font-medium text-gray-900 mb-2">All caught up!</h3>
              <p class="text-gray-500">No pending applications to review</p>
            </div>
            
            <!-- Applications list -->
            <div id="applications-list" class="hidden divide-y divide-gray-200">
              <!-- Applications will be loaded here -->
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Approval Modal -->
    <div id="approval-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">
          <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100 mb-4">
            <svg class="h-6 w-6 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <h3 class="text-lg font-medium text-gray-900 text-center mb-4" id="modal-title">Approve Application</h3>
          <p class="text-sm text-gray-500 text-center mb-4" id="modal-description">
            This will approve the organization and send notification emails.
          </p>
          <textarea
            id="approval-message"
            placeholder="Optional welcome message for the applicant..."
            class="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-500 mb-4"
            rows="3"
          ></textarea>
          <div class="flex space-x-3">
            <button
              id="cancel-approval"
              class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-700 font-medium py-2 px-4 rounded-md transition-colors"
            >
              Cancel
            </button>
            <button
              id="confirm-approval"
              class="flex-1 bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-md transition-colors"
            >
              Approve
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Rejection Modal -->
    <div id="rejection-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">
          <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100 mb-4">
            <svg class="h-6 w-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </div>
          <h3 class="text-lg font-medium text-gray-900 text-center mb-4">Reject Application</h3>
          <p class="text-sm text-gray-500 text-center mb-4">
            Please provide a reason for rejection. This will be sent to the applicant.
          </p>
          <textarea
            id="rejection-reason"
            placeholder="Reason for rejection (required)..."
            class="w-full p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-red-500 mb-4"
            rows="3"
            required
          ></textarea>
          <div class="flex space-x-3">
            <button
              id="cancel-rejection"
              class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-700 font-medium py-2 px-4 rounded-md transition-colors"
            >
              Cancel
            </button>
            <button
              id="confirm-rejection"
              class="flex-1 bg-red-600 hover:bg-red-700 text-white font-medium py-2 px-4 rounded-md transition-colors"
            >
              Reject
            </button>
          </div>
        </div>
      </div>
    </div>
  </SecureLayout>
</ProtectedRoute>

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

  let currentApplicationId: string | null = null;
  
  // DOM elements
  const loadingState = document.getElementById('loading-state');
  const emptyState = document.getElementById('empty-state');
  const applicationsList = document.getElementById('applications-list');
  const pendingCount = document.getElementById('pending-count');
  const refreshBtn = document.getElementById('refresh-btn');
  
  // Modals
  const approvalModal = document.getElementById('approval-modal');
  const rejectionModal = document.getElementById('rejection-modal');
  const confirmApproval = document.getElementById('confirm-approval');
  const confirmRejection = document.getElementById('confirm-rejection');
  const cancelApproval = document.getElementById('cancel-approval');
  const cancelRejection = document.getElementById('cancel-rejection');
  const approvalMessage = document.getElementById('approval-message') as HTMLTextAreaElement;
  const rejectionReason = document.getElementById('rejection-reason') as HTMLTextAreaElement;

  // Load pending applications
  async function loadApplications() {
    try {
      loadingState?.classList.remove('hidden');
      emptyState?.classList.add('hidden');
      applicationsList?.classList.add('hidden');

      // For now, using a mock empty array since admin_pending_approvals table doesn't exist
      interface PendingApplication {
        id: string;
        name: string;
        owner_name: string;
        owner_email: string;
        business_type: string;
        business_description: string;
        current_score: number;
        can_auto_approve: boolean;
        created_at: string;
      }
      
      const applications: PendingApplication[] = [];
      const error = null;

      if (error) {
        throw error;
      }

      loadingState?.classList.add('hidden');

      if (!applications || applications.length === 0) {
        emptyState?.classList.remove('hidden');
        if (pendingCount) pendingCount.textContent = '0';
        return;
      }

      if (pendingCount) pendingCount.textContent = applications.length.toString();
      applicationsList?.classList.remove('hidden');

      // Render applications
      if (applicationsList) {
        applicationsList.innerHTML = applications.map(app => `
          <div class="p-6" data-app-id="${app.id}">
            <div class="flex items-start justify-between">
              <div class="flex-1">
                <div class="flex items-center space-x-3 mb-2">
                  <h3 class="text-lg font-semibold text-gray-900">${app.name}</h3>
                  <div class="px-2 py-1 rounded-full text-xs font-medium ${getScoreColor(app.current_score)}">
                    Score: ${app.current_score}/100
                  </div>
                  ${app.can_auto_approve ? '<div class="px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs font-medium">Auto-Approve Eligible</div>' : ''}
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                  <div>
                    <p class="text-sm text-gray-600">
                      <span class="font-medium">Owner:</span> ${app.owner_name} (${app.owner_email})
                    </p>
                    <p class="text-sm text-gray-600">
                      <span class="font-medium">Business Type:</span> ${app.business_type || 'Not specified'}
                    </p>
                    <p class="text-sm text-gray-600">
                      <span class="font-medium">Applied:</span> ${new Date(app.created_at).toLocaleDateString()}
                    </p>
                  </div>
                  <div>
                    ${app.business_description ? `
                      <p class="text-sm text-gray-600">
                        <span class="font-medium">Description:</span> ${app.business_description}
                      </p>
                    ` : ''}
                  </div>
                </div>
              </div>
              
              <div class="flex space-x-2 ml-6">
                <button
                  class="approve-btn bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-md font-medium transition-colors"
                  data-app-id="${app.id}"
                  data-app-name="${app.name}"
                >
                  Approve
                </button>
                <button
                  class="reject-btn bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md font-medium transition-colors"
                  data-app-id="${app.id}"
                  data-app-name="${app.name}"
                >
                  Reject
                </button>
              </div>
            </div>
          </div>
        `).join('');

        // Add event listeners to approve/reject buttons
        document.querySelectorAll('.approve-btn').forEach(btn => {
          btn.addEventListener('click', (e) => {
            const target = e.target as HTMLButtonElement;
            currentApplicationId = target.getAttribute('data-app-id');
            const appName = target.getAttribute('data-app-name');
            
            document.getElementById('modal-title')!.textContent = `Approve ${appName}`;
            approvalModal?.classList.remove('hidden');
          });
        });

        document.querySelectorAll('.reject-btn').forEach(btn => {
          btn.addEventListener('click', (e) => {
            const target = e.target as HTMLButtonElement;
            currentApplicationId = target.getAttribute('data-app-id');
            rejectionModal?.classList.remove('hidden');
          });
        });
      }

    } catch (error) {
      console.error('Error loading applications:', error);
      loadingState?.classList.add('hidden');
      // Show error state
    }
  }

  function getScoreColor(score: number): string {
    if (score >= 80) return 'bg-green-100 text-green-800';
    if (score >= 60) return 'bg-yellow-100 text-yellow-800';
    return 'bg-red-100 text-red-800';
  }

  // Approve application
  async function approveApplication(orgId: string, message: string) {
    try {
      const response = await fetch('/api/admin/approve-organization', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${(await supabase.auth.getSession()).data.session?.access_token}`
        },
        body: JSON.stringify({
          organization_id: orgId,
          welcome_message: message
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to approve application');
      }

      // Reload applications
      await loadApplications();
      
      // Show success message
      alert('Application approved successfully!');
      
    } catch (error) {
      console.error('Error approving application:', error);
      alert('Failed to approve application: ' + (error as Error).message);
    }
  }

  // Reject application
  async function rejectApplication(orgId: string, reason: string) {
    try {
      const response = await fetch('/api/admin/reject-organization', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${(await supabase.auth.getSession()).data.session?.access_token}`
        },
        body: JSON.stringify({
          organization_id: orgId,
          rejection_reason: reason
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to reject application');
      }

      // Reload applications
      await loadApplications();
      
      // Show success message
      alert('Application rejected successfully!');
      
    } catch (error) {
      console.error('Error rejecting application:', error);
      alert('Failed to reject application: ' + (error as Error).message);
    }
  }

  // Event listeners
  refreshBtn?.addEventListener('click', loadApplications);

  confirmApproval?.addEventListener('click', async () => {
    if (currentApplicationId) {
      await approveApplication(currentApplicationId, approvalMessage?.value || '');
      approvalModal?.classList.add('hidden');
      approvalMessage.value = '';
      currentApplicationId = null;
    }
  });

  confirmRejection?.addEventListener('click', async () => {
    if (currentApplicationId && rejectionReason?.value.trim()) {
      await rejectApplication(currentApplicationId, rejectionReason.value);
      rejectionModal?.classList.add('hidden');
      rejectionReason.value = '';
      currentApplicationId = null;
    } else {
      alert('Please provide a reason for rejection');
    }
  });

  cancelApproval?.addEventListener('click', () => {
    approvalModal?.classList.add('hidden');
    approvalMessage.value = '';
    currentApplicationId = null;
  });

  cancelRejection?.addEventListener('click', () => {
    rejectionModal?.classList.add('hidden');
    rejectionReason.value = '';
    currentApplicationId = null;
  });

  // Close modals on outside click
  [approvalModal, rejectionModal].forEach(modal => {
    modal?.addEventListener('click', (e) => {
      if (e.target === modal) {
        modal.classList.add('hidden');
        currentApplicationId = null;
      }
    });
  });

  // Load applications on page load
  loadApplications();

  // Auto-refresh every 30 seconds
  setInterval(loadApplications, 30000);
</script>

<style>
  .animate-spin {
    animation: spin 1s linear infinite;
  }
  
  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
</style>