<template>
  <AppLayout title="Enrollments">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Enrollments</h1>
          <p class="text-muted-foreground">
            Manage student enrollments in classrooms
          </p>
        </div>
        <div class="flex gap-2">
          <Button variant="outline" @click="$inertia.visit(route('enrollment.bulk-enroll'))">
            <Users class="mr-2 h-4 w-4" />
            Bulk Enroll
          </Button>
          <Button @click="$inertia.visit(route('enrollment.create'))">
            <Plus class="mr-2 h-4 w-4" />
            New Enrollment
          </Button>
        </div>
      </div>

      <!-- Statistics -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle class="text-sm font-medium">Total Enrollments</CardTitle>
            <UserPlus 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 Enrollments</CardTitle>
            <CheckCircle class="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div class="text-2xl font-bold">{{ 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">This Year</CardTitle>
            <Calendar class="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div class="text-2xl font-bold">{{ statistics.current_year }}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle class="text-sm font-medium">Pending</CardTitle>
            <Clock class="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div class="text-2xl font-bold">{{ statistics.pending }}</div>
          </CardContent>
        </Card>
      </div>

      <!-- Filters -->
      <Card>
        <CardHeader>
          <CardTitle>Filters</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div class="space-y-2">
              <Label for="search">Search</Label>
              <Input
                id="search"
                v-model="filters.search"
                placeholder="Search students..."
                @input="debouncedSearch"
              />
            </div>
            <div class="space-y-2">
              <Label for="academic-year">Academic Year</Label>
              <Select v-model="filters.academic_year_id" @update:model-value="search">
                <SelectTrigger>
                  <SelectValue placeholder="All Academic Years" />
                </SelectTrigger>
                <SelectContent>
                  <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="space-y-2">
              <Label for="classroom">Classroom</Label>
              <Select v-model="filters.classroom_id" @update:model-value="search">
                <SelectTrigger>
                  <SelectValue placeholder="All Classrooms" />
                </SelectTrigger>
                <SelectContent>
                  <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="space-y-2">
              <Label for="status">Status</Label>
              <Select v-model="filters.status" @update:model-value="search">
                <SelectTrigger>
                  <SelectValue placeholder="All Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Enrollments</SelectItem>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="inactive">Inactive</SelectItem>
                  <SelectItem value="transferred">Transferred</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <div class="flex justify-end mt-4">
            <Button variant="outline" @click="clearFilters">
              Clear Filters
            </Button>
          </div>
        </CardContent>
      </Card>

      <!-- Enrollments Table -->
      <Card>
        <CardHeader>
          <CardTitle>Enrollments ({{ enrollments.total }})</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Student</TableHead>
                  <TableHead>Classroom</TableHead>
                  <TableHead>Academic Year</TableHead>
                  <TableHead>Enrolled Date</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead class="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                <TableRow v-for="enrollment in enrollments.data" :key="enrollment.id">
                  <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">
                          {{ (enrollment.student?.first_name || '').charAt(0) }}{{ (enrollment.student?.last_name || '').charAt(0) }}
                        </span>
                      </div>
                      <div>
                        <div class="font-medium">
                          {{ enrollment.student?.first_name }} {{ enrollment.student?.last_name }}
                        </div>
                        <div class="text-sm text-muted-foreground">
                          {{ enrollment.student?.student_id }}
                        </div>
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {{ enrollment.classroom?.name || 'N/A' }}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div class="text-sm">
                      {{ enrollment.academic_year?.name || 'N/A' }}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div class="text-sm">
                      {{ formatDate(enrollment.enrolled_at) }}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge :variant="getStatusVariant(enrollment.status)">
                      {{ enrollment.status || 'Active' }}
                    </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('enrollment.show', enrollment.id))">
                          <Eye class="mr-2 h-4 w-4" />
                          View
                        </DropdownMenuItem>
                        <DropdownMenuItem @click="$inertia.visit(route('enrollment.edit', enrollment.id))">
                          <Edit class="mr-2 h-4 w-4" />
                          Edit
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem>
                          <ArrowRightLeft class="mr-2 h-4 w-4" />
                          Transfer
                        </DropdownMenuItem>
                        <DropdownMenuItem class="text-destructive">
                          <Trash2 class="mr-2 h-4 w-4" />
                          Deactivate
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </div>

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

<script setup lang="ts">
import { reactive } from 'vue'
import { router } from '@inertiajs/vue3'
import { debounce } from 'lodash'
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,
  Users,
  UserPlus,
  CheckCircle,
  Calendar,
  Clock,
  ArrowRightLeft
} from 'lucide-vue-next'

interface Props {
  enrollments: {
    data: Array<{
      id: number
      status: string
      enrolled_at: string
      student?: {
        id: number
        first_name: string
        last_name: string
        student_id: string
      }
      classroom?: {
        id: number
        name: string
      }
      academic_year?: {
        id: number
        name: string
      }
    }>
    total: number
    from: number
    to: number
    last_page: number
    prev_page_url?: string
    next_page_url?: string
  }
  academicYears: Array<{
    id: number
    name: string
  }>
  classrooms: Array<{
    id: number
    name: string
  }>
  statistics: {
    total: number
    active: number
    current_year: number
    pending: number
  }
  filters: {
    search?: string
    academic_year_id?: string
    classroom_id?: string
    status?: string
  }
}

const props = defineProps<Props>()

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

const search = () => {
  router.get(route('enrollment.index'), {
    search: filters.search || undefined,
    academic_year_id: filters.academic_year_id !== 'all' ? filters.academic_year_id : undefined,
    classroom_id: filters.classroom_id !== 'all' ? filters.classroom_id : undefined,
    status: filters.status !== 'all' ? filters.status : undefined,
  }, {
    preserveState: true,
    replace: true
  })
}

const debouncedSearch = debounce(search, 300)

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

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

const getStatusVariant = (status: string) => {
  if (!status) {
    return 'secondary'
  }
  switch (status.toLowerCase()) {
    case 'active':
      return 'default'
    case 'inactive':
      return 'secondary'
    case 'transferred':
      return 'outline'
    default:
      return 'secondary'
  }
}
</script>
