<template>
  <Layout>
    <div class="py-6">
      <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <AdminNavigation title="Manual Certificate Records" />
        
        <Breadcrumb :breadcrumbs="[
          { name: 'Admin', icon: 'fas fa-user-shield', url: '/admin' },
          { name: 'Enrollments', icon: 'fas fa-graduation-cap' },
          { name: 'Manual Records', icon: 'fas fa-upload' }
        ]" />

        <!-- Certificate Limit Counter -->
        <div v-if="showCounter" class="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <i class="fas fa-exclamation-triangle text-yellow-600 text-xl"></i>
            </div>
            <div class="ml-3">
              <h3 class="text-sm font-medium text-yellow-800">Certificate Record Limit</h3>
              <div class="mt-1 text-sm text-yellow-700">
                <p><strong>{{ totalCertificates }}/{{ maxRecords }}</strong> certificate records used</p>
                <p v-if="remainingSlots > 0" class="text-green-700">{{ remainingSlots }} slots remaining</p>
                <p v-else class="text-red-700 font-semibold">Limit reached - No more certificates can be added</p>
              </div>
            </div>
          </div>
        </div>

        <!-- Add Record Button -->
        <div class="mb-6">
          <button @click="showAddModal = true" :disabled="showCounter && remainingSlots <= 0" 
                  :class="(showCounter && remainingSlots <= 0) ? 'bg-gray-400 cursor-not-allowed' : 'bg-blue-600 hover:bg-blue-700'" 
                  class="text-white font-bold py-2 px-4 rounded">
            <i class="fas fa-plus mr-2"></i>Add Manual Record
          </button>
        </div>

        <!-- Filters -->
        <div class="bg-white shadow mb-6">
          <div class="px-6 py-4">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Search</label>
                <input v-model="filterForm.search" @input="applyFilters" type="text" placeholder="Student name, certificate number, or course" class="w-full border-gray-300 rounded-md">
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Filter by Center</label>
                <select v-model="filterForm.center_id" @change="applyFilters" class="w-full border-gray-300 rounded-md">
                  <option value="">All Centers</option>
                  <option v-for="center in centers" :key="center.id" :value="center.id">
                    {{ center.name }}
                  </option>
                </select>
              </div>
              
              <div class="flex items-end">
                <button @click="clearFilters" class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded">
                  <i class="fas fa-refresh mr-1"></i>Clear Filters
                </button>
              </div>
            </div>
          </div>
        </div>

        <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
          <div class="p-6">
            <h2 class="text-xl font-bold text-gray-900 mb-6">Manual Certificate Records</h2>

            <div class="overflow-x-auto">
              <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                  <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Certificate Number</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Student Name</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Course</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Center</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Issuance Date</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Uploaded By</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Upload Date</th>
                  </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                  <tr v-for="record in records.data" :key="record.id">
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-mono text-purple-600">
                      {{ record.certificate_number }}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                      {{ record.student_name }}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.course_name }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ record.center?.name || 'N/A' }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ formatDate(record.issuance_date) }}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      <div class="flex items-center">
                        <i :class="record.uploaded_by_type === 'admin' ? 'fas fa-user-shield text-blue-500' : 'fas fa-user-tie text-orange-500'" class="mr-1"></i>
                        {{ record.uploaded_by_name }}
                      </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ formatDate(record.created_at) }}</td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- Pagination -->
            <div v-if="records.links && records.links.length > 3" class="mt-6">
              <nav class="flex justify-center">
                <div class="flex space-x-1">
                  <template v-for="link in records.links" :key="link.label">
                    <Link v-if="link.url" :href="link.url" 
                          :class="link.active ? 'bg-blue-500 text-white' : 'bg-white text-gray-700 hover:bg-gray-50'" 
                          class="px-3 py-2 text-sm border border-gray-300 rounded"
                          v-html="link.label">
                    </Link>
                    <span v-else 
                          class="px-3 py-2 text-sm border border-gray-300 rounded bg-gray-100 text-gray-400"
                          v-html="link.label">
                    </span>
                  </template>
                </div>
              </nav>
            </div>
          </div>
        </div>

        <!-- Add Record Modal -->
        <div v-if="showAddModal" class="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">Add Manual Certificate Record</h3>
              <form @submit.prevent="submitRecord">
                <div class="mb-4">
                  <label class="block text-sm font-medium text-gray-700 mb-2">Certificate Number</label>
                  <input v-model="recordForm.certificate_number" type="text" class="w-full border-gray-300 rounded-md" required>
                </div>
                <div class="mb-4">
                  <label class="block text-sm font-medium text-gray-700 mb-2">Student Name</label>
                  <input v-model="recordForm.student_name" type="text" class="w-full border-gray-300 rounded-md" required>
                </div>
                <div class="mb-4">
                  <label class="block text-sm font-medium text-gray-700 mb-2">Course</label>
                  <select v-model="recordForm.course_id" class="w-full border-gray-300 rounded-md" required>
                    <option value="">Select Course</option>
                    <option v-for="course in courses" :key="course.id" :value="course.id">
                      {{ course.name }}
                    </option>
                  </select>
                </div>
                <div class="mb-4">
                  <label class="block text-sm font-medium text-gray-700 mb-2">Center (Optional)</label>
                  <select v-model="recordForm.center_id" class="w-full border-gray-300 rounded-md">
                    <option value="">Select Center</option>
                    <option v-for="center in centers" :key="center.id" :value="center.id">
                      {{ center.name }}
                    </option>
                  </select>
                </div>
                <div class="mb-4">
                  <label class="block text-sm font-medium text-gray-700 mb-2">Issuance Date</label>
                  <input v-model="recordForm.issuance_date" type="date" class="w-full border-gray-300 rounded-md" required>
                </div>
                <div class="mb-4">
                  <label class="block text-sm font-medium text-gray-700 mb-2">Notes (Optional)</label>
                  <textarea v-model="recordForm.notes" class="w-full border-gray-300 rounded-md" rows="3"></textarea>
                </div>
                <div class="flex justify-end space-x-2">
                  <button type="button" @click="closeAddModal" class="bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded">Cancel</button>
                  <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Add Record</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import Layout from '@/Components/Layout.vue'
import AdminNavigation from '@/Components/AdminNavigation.vue'
import Breadcrumb from '@/Components/Breadcrumb.vue'
import { Link, router } from '@inertiajs/vue3'
import { ref } from 'vue'

const props = defineProps({
  records: Object,
  centers: Array,
  courses: Array,
  totalCertificates: Number,
  maxRecords: Number,
  remainingSlots: Number,
  showCounter: Boolean,
  showWarnings: Boolean,
  filters: Object
})

const showAddModal = ref(false)
const filterForm = ref({
  search: props.filters?.search || '',
  center_id: props.filters?.center_id || ''
})

const recordForm = ref({
  certificate_number: '',
  student_name: '',
  course_id: '',
  center_id: '',
  issuance_date: '',
  notes: ''
})

const applyFilters = () => {
  router.get('/admin/manual-certificates', filterForm.value, {
    preserveState: true,
    preserveScroll: true
  })
}

const clearFilters = () => {
  filterForm.value = { search: '', center_id: '' }
  router.get('/admin/manual-certificates')
}

const submitRecord = () => {
  if (props.showCounter && props.remainingSlots <= 0) {
    Swal.fire({
      icon: 'error',
      title: 'Limit Reached',
      text: `Certificate limit reached (${props.maxRecords} records maximum). Cannot add more certificates.`
    })
    return
  }
  
  if (props.showWarnings) {
    Swal.fire({
      title: 'Confirm Certificate Addition',
      text: 'This certificate record will be permanent and cannot be removed. Continue?',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, add it!'
    }).then((result) => {
      if (result.isConfirmed) {
        submitCertificate()
      }
    })
  } else {
    submitCertificate()
  }
}

const submitCertificate = () => {
  router.post('/admin/manual-certificates', recordForm.value, {
    onSuccess: () => {
      closeAddModal()
      const successText = props.showWarnings 
        ? 'Manual certificate record added successfully! This record is permanent and cannot be removed.'
        : 'Manual certificate record added successfully!'
      Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: successText
      })
    },
    onError: (errors) => {
      const errorMessage = Object.values(errors).flat().join('\n')
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: errorMessage
      })
    }
  })
}

const closeAddModal = () => {
  showAddModal.value = false
  recordForm.value = {
    certificate_number: '',
    student_name: '',
    course_id: '',
    center_id: '',
    issuance_date: '',
    notes: ''
  }
}

const formatDate = (dateString) => {
  if (!dateString) return 'N/A'
  return new Date(dateString).toLocaleDateString()
}
</script>