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

<ProtectedRoute>
  <SecureLayout title="Territory Manager Applications - Admin">
    <div class="min-h-screen bg-gradient-to-br from-purple-900 via-blue-900 to-indigo-900 p-6">
      <div class="container mx-auto">
        <!-- Header -->
        <div class="mb-8">
          <h1 class="text-4xl font-bold text-white mb-2">Territory Manager Applications</h1>
          <p class="text-blue-100">Review and manage Territory Manager applications</p>
        </div>

        <!-- Stats Cards -->
        <div class="grid md:grid-cols-4 gap-6 mb-8">
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
            <div class="text-3xl font-bold text-white" id="pending-count">0</div>
            <div class="text-blue-100">Pending Applications</div>
          </div>
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
            <div class="text-3xl font-bold text-green-400" id="approved-count">0</div>
            <div class="text-blue-100">Approved This Month</div>
          </div>
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
            <div class="text-3xl font-bold text-red-400" id="rejected-count">0</div>
            <div class="text-blue-100">Rejected This Month</div>
          </div>
          <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20">
            <div class="text-3xl font-bold text-purple-400" id="total-tm-count">0</div>
            <div class="text-blue-100">Active TMs</div>
          </div>
        </div>

        <!-- Filters -->
        <div class="bg-white/10 backdrop-blur-sm rounded-lg p-6 border border-white/20 mb-8">
          <div class="flex flex-wrap gap-4 items-center">
            <div>
              <label class="block text-white text-sm font-medium mb-2">Status</label>
              <select id="status-filter" class="px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-2">
                <option value="">All Applications</option>
                <option value="pending">Pending</option>
                <option value="approved">Approved</option>
                <option value="rejected">Rejected</option>
              </select>
            </div>
            <div>
              <label class="block text-white text-sm font-medium mb-2">Territory</label>
              <select id="territory-filter" class="px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-2">
                <option value="">All Territories</option>
                <option value="denver-metro">Denver Metro</option>
                <option value="colorado-springs">Colorado Springs</option>
                <option value="boulder-county">Boulder County</option>
                <option value="fort-collins">Fort Collins</option>
                <option value="grand-junction">Grand Junction</option>
              </select>
            </div>
            <div>
              <label class="block text-white text-sm font-medium mb-2">Date Range</label>
              <select id="date-filter" class="px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-2">
                <option value="">All Time</option>
                <option value="today">Today</option>
                <option value="week">This Week</option>
                <option value="month">This Month</option>
                <option value="quarter">This Quarter</option>
              </select>
            </div>
            <div class="flex-1">
              <label class="block text-white text-sm font-medium mb-2">Search</label>
              <input type="text" id="search-input" placeholder="Search by name or email..." class="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-2">
            </div>
          </div>
        </div>

        <!-- Applications Table -->
        <div class="bg-white/10 backdrop-blur-sm rounded-lg border border-white/20 overflow-hidden">
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-white/5">
                <tr>
                  <th class="text-left p-4 text-white font-medium">Applicant</th>
                  <th class="text-left p-4 text-white font-medium">Territory</th>
                  <th class="text-left p-4 text-white font-medium">Experience</th>
                  <th class="text-left p-4 text-white font-medium">Applied</th>
                  <th class="text-left p-4 text-white font-medium">Status</th>
                  <th class="text-left p-4 text-white font-medium">Actions</th>
                </tr>
              </thead>
              <tbody id="applications-table-body">
                <!-- Applications will be loaded here -->
              </tbody>
            </table>
          </div>
        </div>

        <!-- Pagination -->
        <div class="flex justify-between items-center mt-8">
          <div class="text-white">
            Showing <span id="showing-start">1</span> to <span id="showing-end">10</span> of <span id="total-applications">0</span> applications
          </div>
          <div class="flex space-x-2">
            <button id="prev-page" class="px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white hover:bg-white/20 transition-colors duration-200" disabled>
              Previous
            </button>
            <button id="next-page" class="px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white hover:bg-white/20 transition-colors duration-200" disabled>
              Next
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Application Review Modal -->
    <div id="review-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center hidden z-50">
      <div class="bg-white/10 backdrop-blur-sm rounded-lg border border-white/20 max-w-4xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        <div class="p-6">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold text-white">Review Application</h2>
            <button id="close-modal" class="text-white hover:text-red-400 transition-colors duration-200">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <div id="application-details" class="space-y-6">
            <!-- Application details will be loaded here -->
          </div>

          <div class="flex justify-end space-x-4 mt-8">
            <button id="reject-btn" class="px-6 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors duration-200">
              Reject
            </button>
            <button id="approve-btn" class="px-6 py-3 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors duration-200">
              Approve
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Rejection Reason Modal -->
    <div id="rejection-modal" class="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center hidden z-50">
      <div class="bg-white/10 backdrop-blur-sm rounded-lg border border-white/20 max-w-md w-full mx-4">
        <div class="p-6">
          <h2 class="text-2xl font-bold text-white mb-4">Rejection Reason</h2>
          <textarea id="rejection-reason" rows="4" class="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-2" placeholder="Please provide a reason for rejection..."></textarea>
          <div class="flex justify-end space-x-4 mt-6">
            <button id="cancel-rejection" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors duration-200">
              Cancel
            </button>
            <button id="confirm-rejection" class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors duration-200">
              Confirm Rejection
            </button>
          </div>
        </div>
      </div>
    </div>

    <script>
      let currentPage = 1;
      const pageSize = 10;
      let totalApplications = 0;
      let applications = [];
      let selectedApplication = null;

      // DOM elements
      const statusFilter = document.getElementById('status-filter');
      const territoryFilter = document.getElementById('territory-filter');
      const dateFilter = document.getElementById('date-filter');
      const searchInput = document.getElementById('search-input');
      const applicationsTableBody = document.getElementById('applications-table-body');
      const prevPageBtn = document.getElementById('prev-page');
      const nextPageBtn = document.getElementById('next-page');
      const reviewModal = document.getElementById('review-modal');
      const rejectionModal = document.getElementById('rejection-modal');
      const closeModalBtn = document.getElementById('close-modal');
      const approveBtn = document.getElementById('approve-btn');
      const rejectBtn = document.getElementById('reject-btn');
      const confirmRejectionBtn = document.getElementById('confirm-rejection');
      const cancelRejectionBtn = document.getElementById('cancel-rejection');

      // Load applications
      async function loadApplications() {
        try {
          const params = new URLSearchParams({
            page: currentPage,
            limit: pageSize,
            status: statusFilter.value,
            territory: territoryFilter.value,
            date: dateFilter.value,
            search: searchInput.value
          });

          const response = await fetch(`/api/admin/territory-manager/applications?${params}`);
          const data = await response.json();

          applications = data.applications;
          totalApplications = data.total;

          renderApplicationsTable();
          updatePagination();
          updateStats();
        } catch (error) {
          console.error('Error loading applications:', error);
        }
      }

      // Render applications table
      function renderApplicationsTable() {
        applicationsTableBody.innerHTML = applications.map(app => {
          const statusColor = app.status === 'pending' ? 'text-yellow-400' : 
                             app.status === 'approved' ? 'text-green-400' : 'text-red-400';
          
          return `
            <tr class="border-b border-white/10 hover:bg-white/5 transition-colors duration-200">
              <td class="p-4">
                <div class="text-white font-medium">${app.full_name}</div>
                <div class="text-blue-100 text-sm">${app.email}</div>
                <div class="text-blue-200 text-xs">${app.phone}</div>
              </td>
              <td class="p-4">
                <div class="text-white">${app.desired_territory}</div>
                <div class="text-blue-100 text-sm">${app.has_transportation ? 'Has transport' : 'No transport'}</div>
              </td>
              <td class="p-4">
                <div class="text-white">${app.has_event_experience ? 'Has experience' : 'No experience'}</div>
              </td>
              <td class="p-4">
                <div class="text-white">${new Date(app.created_at).toLocaleDateString()}</div>
                <div class="text-blue-100 text-sm">${new Date(app.created_at).toLocaleTimeString()}</div>
              </td>
              <td class="p-4">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${statusColor}">
                  ${app.status}
                </span>
              </td>
              <td class="p-4">
                <button onclick="reviewApplication('${app.id}')" class="px-3 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded text-sm transition-colors duration-200">
                  Review
                </button>
              </td>
            </tr>
          `;
        }).join('');
      }

      // Update pagination
      function updatePagination() {
        const totalPages = Math.ceil(totalApplications / pageSize);
        prevPageBtn.disabled = currentPage === 1;
        nextPageBtn.disabled = currentPage === totalPages;

        const start = (currentPage - 1) * pageSize + 1;
        const end = Math.min(currentPage * pageSize, totalApplications);

        document.getElementById('showing-start').textContent = start;
        document.getElementById('showing-end').textContent = end;
        document.getElementById('total-applications').textContent = totalApplications;
      }

      // Update stats
      function updateStats() {
        const pendingCount = applications.filter(app => app.status === 'pending').length;
        // In a real implementation, these would come from the API
        document.getElementById('pending-count').textContent = pendingCount;
        // These would be actual counts from the database
        document.getElementById('approved-count').textContent = '12';
        document.getElementById('rejected-count').textContent = '3';
        document.getElementById('total-tm-count').textContent = '45';
      }

      // Review application
      window.reviewApplication = function(applicationId) {
        selectedApplication = applications.find(app => app.id === applicationId);
        if (!selectedApplication) return;

        const detailsContainer = document.getElementById('application-details');
        detailsContainer.innerHTML = `
          <div class="grid md:grid-cols-2 gap-6">
            <div class="space-y-4">
              <h3 class="text-lg font-semibold text-white">Personal Information</h3>
              <div class="bg-white/5 rounded-lg p-4 space-y-2">
                <div><span class="text-blue-100">Name:</span> <span class="text-white">${selectedApplication.full_name}</span></div>
                <div><span class="text-blue-100">Email:</span> <span class="text-white">${selectedApplication.email}</span></div>
                <div><span class="text-blue-100">Phone:</span> <span class="text-white">${selectedApplication.phone}</span></div>
                <div><span class="text-blue-100">Address:</span> <span class="text-white">${selectedApplication.address ? JSON.stringify(selectedApplication.address) : 'N/A'}</span></div>
              </div>
            </div>
            
            <div class="space-y-4">
              <h3 class="text-lg font-semibold text-white">Preferences</h3>
              <div class="bg-white/5 rounded-lg p-4 space-y-2">
                <div><span class="text-blue-100">Desired Territory:</span> <span class="text-white">${selectedApplication.desired_territory}</span></div>
                <div><span class="text-blue-100">Has Transportation:</span> <span class="text-white">${selectedApplication.has_transportation ? 'Yes' : 'No'}</span></div>
                <div><span class="text-blue-100">Has Experience:</span> <span class="text-white">${selectedApplication.has_event_experience ? 'Yes' : 'No'}</span></div>
              </div>
            </div>
          </div>
          
          <div class="space-y-4">
            <h3 class="text-lg font-semibold text-white">Motivation</h3>
            <div class="bg-white/5 rounded-lg p-4">
              <p class="text-white">${selectedApplication.motivation || 'No motivation provided'}</p>
            </div>
          </div>
          
          <div class="space-y-4">
            <h3 class="text-lg font-semibold text-white">Documents</h3>
            <div class="bg-white/5 rounded-lg p-4">
              <p class="text-blue-100">Documents would be displayed here</p>
            </div>
          </div>
          
          <div class="space-y-4">
            <h3 class="text-lg font-semibold text-white">Consent</h3>
            <div class="bg-white/5 rounded-lg p-4 space-y-2">
              <div><span class="text-blue-100">Background Check:</span> <span class="text-white">${selectedApplication.consent?.background_check ? 'Agreed' : 'Not agreed'}</span></div>
              <div><span class="text-blue-100">Data Processing:</span> <span class="text-white">${selectedApplication.consent?.data_processing ? 'Agreed' : 'Not agreed'}</span></div>
              <div><span class="text-blue-100">Terms of Service:</span> <span class="text-white">${selectedApplication.consent?.terms_of_service ? 'Agreed' : 'Not agreed'}</span></div>
            </div>
          </div>
        `;

        reviewModal.classList.remove('hidden');
      };

      // Approve application
      approveBtn.addEventListener('click', async () => {
        if (!selectedApplication) return;

        try {
          const response = await fetch(`/api/admin/territory-manager/applications/${selectedApplication.id}/approve`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
          });

          if (response.ok) {
            reviewModal.classList.add('hidden');
            loadApplications();
          }
        } catch (error) {
          console.error('Error approving application:', error);
        }
      });

      // Reject application
      rejectBtn.addEventListener('click', () => {
        reviewModal.classList.add('hidden');
        rejectionModal.classList.remove('hidden');
      });

      // Confirm rejection
      confirmRejectionBtn.addEventListener('click', async () => {
        if (!selectedApplication) return;

        const reason = document.getElementById('rejection-reason').value;
        
        try {
          const response = await fetch(`/api/admin/territory-manager/applications/${selectedApplication.id}/reject`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ reason })
          });

          if (response.ok) {
            rejectionModal.classList.add('hidden');
            loadApplications();
          }
        } catch (error) {
          console.error('Error rejecting application:', error);
        }
      });

      // Event listeners
      statusFilter.addEventListener('change', () => {
        currentPage = 1;
        loadApplications();
      });

      territoryFilter.addEventListener('change', () => {
        currentPage = 1;
        loadApplications();
      });

      dateFilter.addEventListener('change', () => {
        currentPage = 1;
        loadApplications();
      });

      searchInput.addEventListener('input', debounce(() => {
        currentPage = 1;
        loadApplications();
      }, 300));

      prevPageBtn.addEventListener('click', () => {
        if (currentPage > 1) {
          currentPage--;
          loadApplications();
        }
      });

      nextPageBtn.addEventListener('click', () => {
        currentPage++;
        loadApplications();
      });

      closeModalBtn.addEventListener('click', () => {
        reviewModal.classList.add('hidden');
      });

      cancelRejectionBtn.addEventListener('click', () => {
        rejectionModal.classList.add('hidden');
        reviewModal.classList.remove('hidden');
      });

      // Utility function
      function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
          const later = () => {
            clearTimeout(timeout);
            func(...args);
          };
          clearTimeout(timeout);
          timeout = setTimeout(later, wait);
        };
      }

      // Initialize
      loadApplications();
    </script>
  </SecureLayout>
</ProtectedRoute>