<template>
  <AppLayout title="Exam Types">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Exam Types</h1>
          <p class="text-muted-foreground">
            Manage exam types and their configurations
          </p>
        </div>
        <Button @click="$inertia.visit(route('exam-types.create'))">
          <Plus class="mr-2 h-4 w-4" />
          Add Exam Type
        </Button>
      </div>

      <!-- Flash Messages -->
      <div v-if="$page.props.success" class="bg-green-50 border border-green-200 rounded-md p-4">
        <div class="flex">
          <div class="flex-shrink-0">
            <svg class="h-5 w-5 text-green-400" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
            </svg>
          </div>
          <div class="ml-3">
            <p class="text-sm font-medium text-green-800">{{ $page.props.success }}</p>
          </div>
        </div>
      </div>

      <!-- Error Messages -->
      <div v-if="$page.props.error" class="bg-red-50 border border-red-200 rounded-md p-4">
        <div class="flex">
          <div class="flex-shrink-0">
            <svg class="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
            </svg>
          </div>
          <div class="ml-3">
            <p class="text-sm font-medium text-red-800">{{ $page.props.error }}</p>
          </div>
        </div>
      </div>

      <!-- Statistics Cards -->
      <div class="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle class="text-sm font-medium">Total Exam Types</CardTitle>
            <FileText class="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div class="text-2xl font-bold">{{ statistics.total }}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle class="text-sm font-medium">Active</CardTitle>
            <CheckCircle class="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div class="text-2xl font-bold text-green-600">{{ statistics.active }}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle class="text-sm font-medium">Inactive</CardTitle>
            <XCircle class="h-4 w-4 text-red-600" />
          </CardHeader>
          <CardContent>
            <div class="text-2xl font-bold text-red-600">{{ statistics.inactive }}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle class="text-sm font-medium">With Results</CardTitle>
            <Trophy class="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div class="text-2xl font-bold text-blue-600">{{ statistics.with_results }}</div>
          </CardContent>
        </Card>
      </div>

      <!-- Filters -->
      <Card>
        <CardHeader>
          <CardTitle>Filters</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="flex flex-col sm:flex-row gap-4">
            <div class="flex-1">
              <Label for="search">Search</Label>
              <Input
                id="search"
                v-model="filters.search"
                placeholder="Search exam types..."
                @input="search"
              />
            </div>
            <div class="w-full sm:w-48">
              <Label for="status">Status</Label>
              <Select v-model="filters.status" @update:model-value="search">
                <SelectTrigger>
                  <SelectValue placeholder="All statuses" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Statuses</SelectItem>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="inactive">Inactive</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div class="flex items-end">
              <Button variant="outline" @click="clearFilters">
                Clear Filters
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Exam Types Table -->
      <Card>
        <CardHeader>
          <CardTitle>Exam Types ({{ examTypes.total }})</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Academic Year</TableHead>
                  <TableHead>Weight</TableHead>
                  <TableHead>Results</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead class="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                <TableRow v-for="examType in examTypes.data" :key="examType.id">
                  <TableCell>
                    <div>
                      <div class="font-medium">{{ examType.name }}</div>
                      <div v-if="examType.description" class="text-sm text-muted-foreground">
                        {{ examType.description }}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div v-if="examType.academic_year" class="text-sm">
                      <div class="font-medium">{{ examType.academic_year.name }}</div>
                      <div class="text-muted-foreground">
                        {{ formatDate(examType.academic_year.start_date) }} - {{ formatDate(examType.academic_year.end_date) }}
                      </div>
                    </div>
                    <div v-else class="text-sm text-muted-foreground">
                      No academic year
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {{ examType.weight }}%
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <Badge :variant="examType.results_count > 0 ? 'default' : 'secondary'">
                      {{ examType.results_count || 0 }} results
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <Badge :variant="examType.is_active ? 'default' : 'secondary'">
                      {{ examType.is_active ? 'Active' : 'Inactive' }}
                    </Badge>
                  </TableCell>
                  <TableCell class="text-right">
                    <DropdownMenu>
                      <DropdownMenuTrigger as-child>
                        <Button variant="ghost" class="h-8 w-8 p-0">
                          <MoreHorizontal class="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem @click="$inertia.visit(route('exam-types.show', examType.id))">
                          <Eye class="mr-2 h-4 w-4" />
                          View
                        </DropdownMenuItem>
                        <DropdownMenuItem @click="$inertia.visit(route('exam-types.edit', examType.id))">
                          <Edit class="mr-2 h-4 w-4" />
                          Edit
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem
                          @click="toggleStatus(examType)"
                          :class="examType.is_active ? 'text-orange-600' : 'text-green-600'"
                        >
                          <component :is="examType.is_active ? XCircle : CheckCircle" class="mr-2 h-4 w-4" />
                          {{ examType.is_active ? 'Deactivate' : 'Activate' }}
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          @click="deleteExamType(examType)"
                          class="text-red-600"
                          :disabled="examType.results_count > 0"
                        >
                          <Trash2 class="mr-2 h-4 w-4" />
                          Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </div>

          <!-- Empty State -->
          <div v-if="!examTypes.data.length" class="text-center py-8">
            <FileText class="mx-auto h-12 w-12 text-muted-foreground" />
            <h3 class="mt-2 text-sm font-semibold">No exam types found</h3>
            <p class="mt-1 text-sm text-muted-foreground">
              Get started by creating a new exam type.
            </p>
            <div class="mt-6">
              <Button @click="$inertia.visit(route('exam-types.create'))">
                <Plus class="mr-2 h-4 w-4" />
                Add Exam Type
              </Button>
            </div>
          </div>

          <!-- Pagination -->
          <div class="flex items-center justify-between space-x-2 py-4" v-if="examTypes.last_page > 1">
            <div class="text-sm text-muted-foreground">
              Showing {{ examTypes.from }} to {{ examTypes.to }} of {{ examTypes.total }} results
            </div>
            <div class="flex space-x-2">
              <Button
                variant="outline"
                size="sm"
                :disabled="!examTypes.prev_page_url"
                @click="$inertia.visit(examTypes.prev_page_url)"
              >
                Previous
              </Button>
              <Button
                variant="outline"
                size="sm"
                :disabled="!examTypes.next_page_url"
                @click="$inertia.visit(examTypes.next_page_url)"
              >
                Next
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { router, usePage } from '@inertiajs/vue3'
import { debounce } from 'lodash'
import { useToast } from '@/composables/useToast'
import AppLayout from '@/layouts/AppLayout.vue'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Plus, MoreHorizontal, Eye, Edit, Trash2, FileText, CheckCircle, XCircle, Trophy } from 'lucide-vue-next'

interface ExamType {
  id: number
  name: string
  description?: string
  weight: number
  is_active: boolean
  results_count: number
  academic_year?: {
    id: number
    name: string
    start_date: string
    end_date: string
  }
}

interface Props {
  examTypes: {
    data: ExamType[]
    total: number
    from: number
    to: number
    last_page: number
    prev_page_url?: string
    next_page_url?: string
  }
  statistics: {
    total: number
    active: number
    inactive: number
    with_results: number
  }
  filters: {
    search?: string
    status?: string
  }
}

const props = defineProps<Props>()
const page = usePage()
const toast = useToast()

const filters = reactive({
  search: props.filters.search || '',
  status: props.filters.status || 'all'
})

const search = debounce(() => {
  const params = { ...filters }
  if (params.status === 'all') {
    delete params.status
  }

  router.get(route('exam-types.index'), params, {
    preserveState: true,
    replace: true
  })
}, 300)

const clearFilters = () => {
  filters.search = ''
  filters.status = 'all'
  search()
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

const toggleStatus = (examType: ExamType) => {
  router.post(route('exam-types.toggle-status', examType.id), {}, {
    preserveScroll: true
  })
}

const deleteExamType = (examType: ExamType) => {
  if (examType.results_count > 0) {
    toast.error('Cannot delete exam type with existing results.')
    return
  }

  if (confirm(`Are you sure you want to delete "${examType.name}"? This action cannot be undone.`)) {
    router.delete(route('exam-types.destroy', examType.id), {
      preserveScroll: true,
      onSuccess: () => {
        toast.success('Exam type deleted successfully!')
      },
      onError: (errors) => {
        let errorMessage = 'Failed to delete exam type. Please try again.'

        if (errors.exam_type) {
          errorMessage = Array.isArray(errors.exam_type) ? errors.exam_type[0] : errors.exam_type
        } else if (errors.error) {
          errorMessage = Array.isArray(errors.error) ? errors.error[0] : errors.error
        }

        toast.error(errorMessage)
      }
    })
  }
}
</script>
