<template>
  <AppLayout title="Results">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Results</h1>
          <p class="text-muted-foreground">
            Manage student examination results and grades
          </p>
          <div v-if="currentExamType && currentAcademicYear" class="mt-2">
            <Badge variant="outline" class="mr-2">
              {{ currentAcademicYear.name }}
            </Badge>
            <Badge variant="secondary">
              {{ currentExamType.name }}
            </Badge>
          </div>
        </div>
        <div class="flex gap-2">
          <Button
            v-if="selectedResults.length > 0"
            variant="destructive"
            size="sm"
            @click="bulkDelete"
          >
            <Trash2 class="mr-2 h-4 w-4" />
            Delete Selected ({{ selectedResults.length }})
          </Button>
          <Button variant="outline" @click="exportResults">
            <Download class="w-4 h-4 mr-2" />
            Export
          </Button>
          <Button as-child>
            <Link :href="route('results.create-multiple')">
              <Plus class="w-4 h-4 mr-2" />
              Add Result
            </Link>
          </Button>
        </div>
      </div>

    <div class="py-6">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- Search and Filters Card -->
        <Card class="mb-6">
          <CardHeader>
            <CardTitle class="flex items-center gap-2">
              <Filter class="w-5 h-5" />
              Filters & Search
            </CardTitle>
            <CardDescription>
              Search and filter results by various criteria
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4 space-y-2 sm:space-y-0">
              <div class="relative min-w-0">
                <Search class="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                <Input
                  v-model="filters.search"
                  placeholder="Search results..."
                  class="pl-10 w-full"
                  @input="search"
                />
              </div>
              <div class="relative min-w-0">
                <Select v-model="filters.academic_year_id" @update:model-value="search">
                  <SelectTrigger class="w-full">
                    <SelectValue placeholder="Academic Year" />
                  </SelectTrigger>
                  <SelectContent class="z-50">
                    <SelectItem value="all">All Academic Years</SelectItem>
                    <SelectItem v-for="year in academicYears" :key="year.id" :value="year.id.toString()">
                      {{ year.name }}
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div class="relative min-w-0">
                <Select v-model="filters.exam_type_id" @update:model-value="search">
                  <SelectTrigger class="w-full">
                    <SelectValue placeholder="Exam Type" />
                  </SelectTrigger>
                  <SelectContent class="z-50">
                    <SelectItem value="all">All Exam Types</SelectItem>
                    <SelectItem v-for="examType in examTypes" :key="examType.id" :value="examType.id.toString()">
                      {{ examType.name }}
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div class="relative min-w-0">
                <Select v-model="filters.classroom_id" @update:model-value="search">
                  <SelectTrigger class="w-full">
                    <SelectValue placeholder="Classroom" />
                  </SelectTrigger>
                  <SelectContent class="z-50">
                    <SelectItem value="all">All Classrooms</SelectItem>
                    <SelectItem v-for="classroom in classrooms" :key="classroom.id" :value="classroom.id.toString()">
                      {{ classroom.name }}
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div class="relative min-w-0">
                <Select v-model="filters.subject_id" @update:model-value="search">
                  <SelectTrigger class="w-full">
                    <SelectValue placeholder="Subject" />
                  </SelectTrigger>
                  <SelectContent class="z-50">
                    <SelectItem value="all">All Subjects</SelectItem>
                    <SelectItem v-for="subject in subjects" :key="subject.id" :value="subject.id.toString()">
                      {{ subject.name }}
                    </SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div class="relative min-w-0">
                <Button variant="outline" @click="clearFilters" class="w-full">
                  Clear Filters
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        <!-- Results Table -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center justify-between">
              <div class="flex items-center gap-2">
                <Trophy class="w-5 h-5" />
                Results List
              </div>
              <Badge variant="secondary">{{ results.total }} total</Badge>
            </CardTitle>
            <CardDescription>
              View and manage all examination results
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div v-if="results.data.length === 0" class="text-center py-12">
              <Trophy class="w-12 h-12 text-gray-400 mx-auto mb-4" />
              <p class="text-gray-500 text-lg">No results found</p>
              <p class="text-gray-400 text-sm">Try adjusting your search criteria</p>
            </div>
            <div v-else>
              <Table class="table-compact text-xs w-full table-fixed">
                <TableHeader>
                  <TableRow>
                    <TableHead class="w-[40px]">
                      <Checkbox
                        :checked="selectedResults.length === results.data.length && results.data.length > 0"
                        @update:checked="toggleSelectAll"
                      />
                    </TableHead>
                    <TableHead class="w-[20%]">Student</TableHead>
                    <!-- Dynamic subject columns -->
                    <TableHead
                      v-for="subject in allSubjects"
                      :key="subject.id"
                      class="text-center"
                      :class="`w-[${Math.floor(60 / allSubjects.length)}%]`"
                      :title="subject.name"
                    >
                      <div class="text-xs font-medium">{{ subject.code }}</div>
                    </TableHead>
                    <TableHead class="text-center w-[6%]">TOTAL</TableHead>
                    <TableHead class="text-center w-[6%]">AVG</TableHead>
                    <TableHead class="text-center w-[5%]">PTS</TableHead>
                    <TableHead class="text-center w-[4%]">DIV</TableHead>
                    <TableHead class="text-center w-[5%]">RANK</TableHead>
                    <TableHead class="text-right w-[6%]">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  <TableRow v-for="result in results.data" :key="result.id">
                    <!-- Checkbox -->
                    <TableCell>
                      <Checkbox
                        :checked="isSelected(result)"
                        @update:checked="(checked) => toggleSelect(result, checked)"
                      />
                    </TableCell>
                    <!-- Student Info -->
                    <TableCell>
                      <div class="flex items-center gap-3">
                        <div class="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center">
                          <span class="text-xs font-medium text-primary">
                            {{ getStudentInitials(result.student) }}
                          </span>
                        </div>
                        <div>
                          <div class="font-medium text-sm">
                            {{ getStudentName(result.student) }}
                          </div>
                          <div class="text-xs text-muted-foreground">
                            {{ result.student?.student_id || 'N/A' }}
                          </div>
                        </div>
                      </div>
                    </TableCell>

                    <!-- Subject Results -->
                    <TableCell
                      v-for="subject in allSubjects"
                      :key="subject.id"
                      class="text-center"
                    >
                      <div v-if="result.subjects_data[subject.id]" class="space-y-1">
                        <div class="font-mono text-sm font-medium">
                          {{ result.subjects_data[subject.id].marks }}
                        </div>
                        <div class="text-xs text-muted-foreground">
                          {{ result.subjects_data[subject.id].points }}pts
                        </div>
                        <Badge
                          :variant="getGradeVariant(result.subjects_data[subject.id].grade)"
                          class="text-xs"
                        >
                          {{ result.subjects_data[subject.id].grade }}
                        </Badge>
                      </div>
                      <div v-else class="text-muted-foreground text-xs">-</div>
                    </TableCell>

                    <!-- Summary Data -->
                    <TableCell class="text-center p-2">
                      <div class="font-mono font-medium text-xs">{{ result.total_marks }}</div>
                    </TableCell>
                    <TableCell class="text-center p-2">
                      <div class="font-mono text-xs">{{ result.average_marks }}</div>
                    </TableCell>
                    <TableCell class="text-center p-2">
                      <div class="font-mono font-medium text-xs">{{ result.total_points }}</div>
                    </TableCell>
                    <TableCell class="text-center p-2">
                      <Badge variant="secondary" class="text-xs px-1 py-0">{{ result.division }}</Badge>
                    </TableCell>
                    <TableCell class="text-center p-2">
                      <div class="font-medium text-xs">{{ result.rank }}</div>
                    </TableCell>

                    <!-- Actions -->
                    <TableCell class="text-right p-1">
                      <DropdownMenu>
                        <DropdownMenuTrigger as-child>
                          <Button variant="ghost" size="sm" class="h-6 w-6 p-0">
                            <MoreHorizontal class="w-3 h-3" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem @click="viewStudentResults(result)">
                            <Eye class="w-4 h-4 mr-2" />
                            View
                          </DropdownMenuItem>
                          <DropdownMenuItem @click="editStudentResults(result)">
                            <Edit class="w-4 h-4 mr-2" />
                            Edit
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            @click="deleteStudentResults(result)"
                            class="text-destructive focus:text-destructive"
                          >
                            <Trash2 class="w-4 h-4 mr-2" />
                            Delete
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </div>

            <!-- Pagination -->
            <div v-if="results.last_page > 1" class="flex items-center justify-between px-2 py-4">
              <div class="text-sm text-muted-foreground">
                Showing {{ results.from }} to {{ results.to }} of {{ results.total }} results
              </div>
              <div class="flex items-center space-x-2">
                <Button
                  variant="outline"
                  size="sm"
                  :disabled="Number(results.current_page) === 1"
                  @click="goToPage(Number(results.current_page) - 1)"
                >
                  Previous
                </Button>

                <div class="flex items-center space-x-1">
                  <template v-for="page in getVisiblePages()" :key="page">
                    <Button
                      v-if="page !== '...'"
                      :variant="Number(page) === Number(results.current_page) ? 'default' : 'outline'"
                      size="sm"
                      class="w-8 h-8 p-0"
                      @click="goToPage(page)"
                    >
                      {{ page }}
                    </Button>
                    <span v-else class="px-2 text-muted-foreground">...</span>
                  </template>
                </div>

                <Button
                  variant="outline"
                  size="sm"
                  :disabled="Number(results.current_page) === Number(results.last_page)"
                  @click="goToPage(Number(results.current_page) + 1)"
                >
                  Next
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>

    <!-- Student Results Detail Modal -->
    <Dialog v-model:open="showDetailModal">
      <DialogContent class="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {{ selectedResult ? getStudentName(selectedResult.student) : '' }} -
            {{ selectedResult?.exam_type?.name || '' }} Results
          </DialogTitle>
          <DialogDescription>
            Academic Year: {{ selectedResult?.academic_year?.name || '' }} |
            Classroom: {{ selectedResult?.classroom?.name || 'N/A' }}
          </DialogDescription>
        </DialogHeader>

        <div v-if="selectedResult" id="print-content">
          <div class="space-y-6">
            <!-- Student Info Header -->
            <div class="text-center border-b pb-4">
              <h2 class="text-xl font-bold">{{ getStudentName(selectedResult.student) }}</h2>
              <p class="text-muted-foreground">
                {{ selectedResult.exam_type.name }} - {{ selectedResult.academic_year.name }}
              </p>
              <p class="text-sm text-muted-foreground">
                Classroom: {{ selectedResult.classroom?.name || 'N/A' }}
              </p>
            </div>

            <!-- Subject Results Table -->
            <div>
              <h3 class="text-lg font-semibold mb-3">Subject Results</h3>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Subject</TableHead>
                    <TableHead class="text-center">Marks</TableHead>
                    <TableHead class="text-center">Grade</TableHead>
                    <TableHead class="text-center">Points</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  <TableRow v-for="(subjectData, subjectId) in selectedResult.subjects_data" :key="subjectId">
                    <TableCell class="font-medium">{{ subjectData.subject.name }}</TableCell>
                    <TableCell class="text-center">{{ subjectData.marks }}</TableCell>
                    <TableCell class="text-center">
                      <Badge :variant="getGradeVariant(subjectData.grade)">
                        {{ subjectData.grade }}
                      </Badge>
                    </TableCell>
                    <TableCell class="text-center">{{ subjectData.points }}</TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </div>

            <!-- Summary -->
            <div class="summary bg-muted p-4 rounded-lg">
              <h3 class="text-lg font-semibold mb-3">Summary</h3>
              <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
                <div class="text-center">
                  <p class="text-sm text-muted-foreground">Total Marks</p>
                  <p class="text-xl font-bold">{{ selectedResult.total_marks }}</p>
                </div>
                <div class="text-center">
                  <p class="text-sm text-muted-foreground">Average</p>
                  <p class="text-xl font-bold">{{ selectedResult.average_marks }}</p>
                </div>
                <div class="text-center">
                  <p class="text-sm text-muted-foreground">Total Points</p>
                  <p class="text-xl font-bold">{{ selectedResult.total_points }}</p>
                </div>
                <div class="text-center">
                  <p class="text-sm text-muted-foreground">Division</p>
                  <Badge variant="secondary" class="text-lg">{{ selectedResult.division }}</Badge>
                </div>
                <div class="text-center">
                  <p class="text-sm text-muted-foreground">Rank</p>
                  <p class="text-xl font-bold">{{ selectedResult.rank }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Modal Actions -->
        <div class="flex justify-end space-x-2 mt-6 no-print">
          <Button variant="outline" @click="printResults()">
            <Printer class="w-4 h-4 mr-2" />
            Print
          </Button>
          <Button variant="outline" @click="showDetailModal = false">
            Close
          </Button>
        </div>
      </DialogContent>
    </Dialog>

    <!-- Delete Confirmation Dialog -->
    <AlertDialog v-model:open="showDeleteDialog">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete Student Results</AlertDialogTitle>
          <AlertDialogDescription>
            Are you sure you want to delete all results for
            <strong>{{ resultToDelete ? getStudentName(resultToDelete.student) : '' }}</strong>
            in <strong>{{ resultToDelete?.exam_type?.name || '' }}</strong>
            ({{ resultToDelete?.academic_year?.name || '' }})?
            <br><br>
            This action cannot be undone and will remove all subject results for this student and exam type.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel @click="showDeleteDialog = false">Cancel</AlertDialogCancel>
          <AlertDialogAction
            @click="confirmDelete"
            class="bg-destructive text-destructive-foreground hover:bg-destructive/90"
          >
            Delete Results
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>

    <!-- Bulk Delete Confirmation Dialog -->
    <AlertDialog v-model:open="showBulkDeleteDialog">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete Multiple Results</AlertDialogTitle>
          <AlertDialogDescription>
            Are you sure you want to delete <strong>{{ selectedResults.length }}</strong> selected result(s)?
            <br><br>
            This will permanently remove all subject results for the selected students and exam types.
            This action cannot be undone.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel @click="showBulkDeleteDialog = false">Cancel</AlertDialogCancel>
          <AlertDialogAction
            @click="confirmBulkDelete"
            class="bg-destructive text-destructive-foreground hover:bg-destructive/90"
          >
            Delete {{ selectedResults.length }} Result(s)
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { Link, router } from '@inertiajs/vue3'
import AppLayout from '@/layouts/AppLayout.vue'
import { debounce } from 'lodash'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'
import { Plus, Download, Search, Filter, MoreHorizontal, Eye, Edit, Trash2, Trophy, Printer } from 'lucide-vue-next'

const props = defineProps({
  results: {
    type: Object,
    required: true
  },
  allSubjects: {
    type: Array,
    default: () => []
  },
  academicYears: {
    type: Array,
    default: () => []
  },
  examTypes: {
    type: Array,
    default: () => []
  },
  classrooms: {
    type: Array,
    default: () => []
  },
  subjects: {
    type: Array,
    default: () => []
  },
  filters: {
    type: Object,
    default: () => ({})
  },
  currentAcademicYear: {
    type: Object,
    default: null
  },
  currentExamType: {
    type: Object,
    default: null
  }
})

const filters = reactive({
  search: props.filters.search || '',
  academic_year_id: props.filters.academic_year_id || 'all',
  exam_type_id: props.filters.exam_type_id || 'all',
  classroom_id: props.filters.classroom_id || 'all',
  subject_id: props.filters.subject_id || 'all'
})

// Modal state for detailed view
const showDetailModal = ref(false)
const selectedResult = ref(null)

// Delete confirmation state
const showDeleteDialog = ref(false)
const resultToDelete = ref(null)

// Bulk selection state
const selectedResults = ref([])
const showBulkDeleteDialog = ref(false)

const search = debounce(() => {
  router.get(route('results.index'), {
    search: filters.search || undefined,
    academic_year_id: filters.academic_year_id !== 'all' ? filters.academic_year_id : undefined,
    exam_type_id: filters.exam_type_id !== 'all' ? filters.exam_type_id : undefined,
    classroom_id: filters.classroom_id !== 'all' ? filters.classroom_id : undefined,
    subject_id: filters.subject_id !== 'all' ? filters.subject_id : undefined,
  }, {
    preserveState: true,
    replace: true
  })
}, 300)

const clearFilters = () => {
  filters.search = ''
  filters.academic_year_id = 'all'
  filters.exam_type_id = 'all'
  filters.classroom_id = 'all'
  filters.subject_id = 'all'
  search()
}

const exportResults = () => {
  window.open('/results/export', '_blank')
}

const deleteResult = (resultId: number) => {
  if (confirm('Are you sure you want to delete this result?')) {
    router.delete(route('results.destroy', resultId), {
      onSuccess: () => {
        router.reload({ only: ['results'] })
      }
    })
  }
}

const getGradeVariant = (grade: string) => {
  switch (grade) {
    case 'A': return 'default'
    case 'B': return 'secondary'
    case 'C': return 'outline'
    case 'D': return 'outline'
    case 'F': return 'destructive'
    default: return 'secondary'
  }
}

const getStudentName = (student: any) => {
  if (student?.user?.name) {
    return student.user.name
  }
  const firstName = student?.user?.first_name || student?.first_name || 'Unknown'
  const lastName = student?.user?.last_name || student?.last_name || 'Student'
  return `${firstName} ${lastName}`
}

const getStudentInitials = (student: any) => {
  const name = getStudentName(student)
  const parts = name.split(' ')
  if (parts.length >= 2) {
    return `${parts[0].charAt(0)}${parts[1].charAt(0)}`
  }
  return name.charAt(0) + (name.charAt(1) || 'A')
}

const viewStudentResults = (result: any) => {
  selectedResult.value = result
  showDetailModal.value = true
}

const printResults = () => {
  if (!selectedResult.value) return

  const result = selectedResult.value
  const studentName = getStudentName(result.student)

  // Create print content
  let printHTML = `
    <html>
      <head>
        <title>${studentName} - ${result.exam_type.name} Results</title>
        <style>
          body {
            font-family: Arial, sans-serif;
            margin: 20px;
            color: #333;
          }
          .header {
            text-align: center;
            border-bottom: 2px solid #333;
            padding-bottom: 20px;
            margin-bottom: 30px;
          }
          .header h1 {
            margin: 0;
            font-size: 24px;
          }
          .header p {
            margin: 5px 0;
            color: #666;
          }
          table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
          }
          th, td {
            border: 1px solid #ddd;
            padding: 12px 8px;
            text-align: left;
          }
          th {
            background-color: #f5f5f5;
            font-weight: bold;
          }
          .text-center {
            text-align: center;
          }
          .summary {
            background-color: #f9f9f9;
            padding: 20px;
            border-radius: 5px;
            margin-top: 30px;
          }
          .summary h3 {
            margin-top: 0;
            margin-bottom: 15px;
          }
          .summary-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 20px;
          }
          .summary-item {
            text-align: center;
          }
          .summary-item .label {
            font-size: 12px;
            color: #666;
            margin-bottom: 5px;
          }
          .summary-item .value {
            font-size: 18px;
            font-weight: bold;
          }
          @media print {
            body { margin: 0; }
            .no-print { display: none !important; }
          }
        </style>
      </head>
      <body>
        <div class="header">
          <h1>${studentName}</h1>
          <p>${result.exam_type.name} - ${result.academic_year.name}</p>
          <p>Classroom: ${result.classroom?.name || 'N/A'}</p>
        </div>

        <h3>Subject Results</h3>
        <table>
          <thead>
            <tr>
              <th>Subject</th>
              <th class="text-center">Marks</th>
              <th class="text-center">Grade</th>
              <th class="text-center">Points</th>
            </tr>
          </thead>
          <tbody>
  `

  // Add subject results
  Object.values(result.subjects_data).forEach((subjectData: any) => {
    printHTML += `
      <tr>
        <td>${subjectData.subject.name}</td>
        <td class="text-center">${subjectData.marks}</td>
        <td class="text-center">${subjectData.grade}</td>
        <td class="text-center">${subjectData.points}</td>
      </tr>
    `
  })

  printHTML += `
          </tbody>
        </table>

        <div class="summary">
          <h3>Summary</h3>
          <div class="summary-grid">
            <div class="summary-item">
              <div class="label">Total Marks</div>
              <div class="value">${result.total_marks}</div>
            </div>
            <div class="summary-item">
              <div class="label">Average</div>
              <div class="value">${result.average_marks}</div>
            </div>
            <div class="summary-item">
              <div class="label">Total Points</div>
              <div class="value">${result.total_points}</div>
            </div>
            <div class="summary-item">
              <div class="label">Division</div>
              <div class="value">${result.division}</div>
            </div>
            <div class="summary-item">
              <div class="label">Rank</div>
              <div class="value">${result.rank}</div>
            </div>
          </div>
        </div>

        <div style="margin-top: 30px; text-align: center; page-break-inside: avoid;" class="no-print">
          <button onclick="window.print()" style="padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; margin-right: 10px;">Print</button>
          <button onclick="window.close()" style="padding: 10px 20px; background-color: #6c757d; color: white; border: none; border-radius: 5px; cursor: pointer;">Close</button>
        </div>
      </body>
    </html>
  `

  // Open print window
  const printWindow = window.open('', '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes')
  if (printWindow) {
    printWindow.document.write(printHTML)
    printWindow.document.close()
    printWindow.focus()
  }
}

const editStudentResults = (result: any) => {
  // Navigate to edit multiple results page
  router.get(route('results.edit-multiple', [
    result.student.id,
    result.exam_type.id,
    result.academic_year.id
  ]))
}

const deleteStudentResults = (result: any) => {
  resultToDelete.value = result
  showDeleteDialog.value = true
}

const confirmDelete = () => {
  if (!resultToDelete.value) return

  // Get the first subject result to get a result ID for deletion
  const firstSubjectResult = Object.values(resultToDelete.value.subjects_data)[0] as any
  if (firstSubjectResult) {
    // For now, we'll delete all results for this student-exam combination
    // We need to implement a bulk delete endpoint
    router.delete(route('results.delete-multiple'), {
      data: {
        student_id: resultToDelete.value.student.id,
        exam_type_id: resultToDelete.value.exam_type.id,
        academic_year_id: resultToDelete.value.academic_year.id
      },
      onSuccess: () => {
        showDeleteDialog.value = false
        resultToDelete.value = null
      },
      onError: (errors) => {
        console.error('Delete failed:', errors)
      }
    })
  }
}

// Pagination methods
const goToPage = (page: number | string) => {
  const pageNumber = Number(page)
  if (pageNumber < 1 || pageNumber > Number(props.results.last_page)) return

  router.get(route('results.index'), {
    page: pageNumber,
    search: filters.search || undefined,
    academic_year_id: filters.academic_year_id !== 'all' ? filters.academic_year_id : undefined,
    exam_type_id: filters.exam_type_id !== 'all' ? filters.exam_type_id : undefined,
    classroom_id: filters.classroom_id !== 'all' ? filters.classroom_id : undefined,
    subject_id: filters.subject_id !== 'all' ? filters.subject_id : undefined,
  }, {
    preserveState: true,
    replace: true
  })
}

const getVisiblePages = () => {
  const current = props.results.current_page
  const last = props.results.last_page
  const pages = []

  if (last <= 5) {
    // Show all pages if there are 5 or fewer
    for (let i = 1; i <= last; i++) {
      pages.push(i)
    }
  } else {
    // Always show first page
    pages.push(1)

    if (current <= 3) {
      // Near beginning: show 1, 2, 3, 4, ..., last
      for (let i = 2; i <= 4; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(last)
    } else if (current >= last - 2) {
      // Near end: show 1, ..., last-3, last-2, last-1, last
      pages.push('...')
      for (let i = last - 3; i <= last; i++) {
        pages.push(i)
      }
    } else {
      // Middle: show 1, ..., current-1, current, current+1, ..., last
      pages.push('...')
      pages.push(current - 1)
      pages.push(current)
      pages.push(current + 1)
      pages.push('...')
      pages.push(last)
    }
  }

  return pages
}

// Selection functions
const isSelected = (result: any): boolean => {
  return selectedResults.value.some(selected =>
    selected.student.id === result.student.id &&
    selected.exam_type.id === result.exam_type.id &&
    selected.academic_year.id === result.academic_year.id
  )
}

const toggleSelect = (result: any, checked: boolean) => {
  if (checked) {
    selectedResults.value.push(result)
  } else {
    selectedResults.value = selectedResults.value.filter(selected =>
      !(selected.student.id === result.student.id &&
        selected.exam_type.id === result.exam_type.id &&
        selected.academic_year.id === result.academic_year.id)
    )
  }
}

const toggleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedResults.value = [...props.results.data]
  } else {
    selectedResults.value = []
  }
}

const bulkDelete = () => {
  if (selectedResults.value.length === 0) return
  showBulkDeleteDialog.value = true
}

const confirmBulkDelete = () => {
  if (selectedResults.value.length === 0) return

  // Delete each selected result
  const deletePromises = selectedResults.value.map(result => {
    return router.delete(route('results.delete-multiple'), {
      data: {
        student_id: result.student.id,
        exam_type_id: result.exam_type.id,
        academic_year_id: result.academic_year.id
      },
      preserveState: true,
      preserveScroll: true
    })
  })

  Promise.all(deletePromises).then(() => {
    selectedResults.value = []
    showBulkDeleteDialog.value = false
    // Refresh the page
    router.reload()
  }).catch((error) => {
    console.error('Bulk delete failed:', error)
  })
}
</script>

<style scoped>
.table-compact {
  font-size: 0.75rem;
}

.table-compact th,
.table-compact td {
  padding: 0.25rem 0.5rem;
  white-space: nowrap;
}

.table-compact .badge {
  font-size: 0.625rem;
  padding: 0.125rem 0.25rem;
}

/* Table layout improvements */
.table-fixed {
  table-layout: fixed;
}

.table-compact th,
.table-compact td {
  padding: 0.25rem 0.5rem;
  word-wrap: break-word;
}

.table-compact .text-xs {
  font-size: 0.75rem;
}

.table-compact th {
  white-space: nowrap;
  line-height: 1.2;
  overflow: visible;
  text-overflow: unset;
}

.table-compact td {
  white-space: nowrap;
}
</style>
