<template>
  <AppLayout title="Academic Years">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Academic Years</h1>
          <p class="text-muted-foreground">
            Manage academic years and their schedules
          </p>
        </div>
        <Button @click="$inertia.visit(route('academic-years.create'))">
          <Plus class="mr-2 h-4 w-4" />
          Add Academic Year
        </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 -->
      <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 Years</CardTitle>
            <Calendar 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 Years</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">Inactive Years</CardTitle>
            <XCircle class="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div class="text-2xl font-bold">{{ 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">Current Year</CardTitle>
            <Clock class="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div class="text-2xl font-bold">{{ statistics.current }}</div>
          </CardContent>
        </Card>
      </div>

      <!-- Filters -->
      <Card>
        <CardHeader>
          <CardTitle>Filters</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="space-y-2">
              <Label for="search">Search</Label>
              <Input
                id="search"
                v-model="filters.search"
                placeholder="Search academic years..."
                @input="debouncedSearch"
              />
            </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 Years</SelectItem>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="inactive">Inactive</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div class="flex items-end">
              <Button variant="outline" @click="clearFilters" class="w-full">
                Clear Filters
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Academic Years Table -->
      <Card>
        <CardHeader>
          <CardTitle>Academic Years ({{ academicYears.total }})</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Duration</TableHead>
                  <TableHead>Classrooms</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead class="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                <TableRow v-for="year in academicYears.data" :key="year.id">
                  <TableCell>
                    <div>
                      <div class="font-medium">{{ year.name }}</div>
                      <div class="text-sm text-muted-foreground">{{ year.description }}</div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div class="text-sm">
                      <div>{{ formatDate(year.start_date) }} - {{ formatDate(year.end_date) }}</div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {{ year.classrooms_count || 0 }} classrooms
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <Badge :variant="year.is_active ? 'default' : 'secondary'">
                      {{ year.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('academic-years.show', year.id))">
                          <Eye class="mr-2 h-4 w-4" />
                          View
                        </DropdownMenuItem>
                        <DropdownMenuItem @click="$inertia.visit(route('academic-years.edit', year.id))">
                          <Edit class="mr-2 h-4 w-4" />
                          Edit
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem
                          @click="deleteAcademicYear(year.id)"
                          class="text-destructive"
                        >
                          <Trash2 class="mr-2 h-4 w-4" />
                          Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </div>

          <!-- Pagination -->
          <div class="flex items-center justify-between space-x-2 py-4" v-if="academicYears.last_page > 1">
            <div class="text-sm text-muted-foreground">
              Showing {{ academicYears.from }} to {{ academicYears.to }} of {{ academicYears.total }} results
            </div>
            <div class="flex space-x-2">
              <Button
                variant="outline"
                size="sm"
                :disabled="!academicYears.prev_page_url"
                @click="$inertia.visit(academicYears.prev_page_url)"
              >
                Previous
              </Button>
              <Button
                variant="outline"
                size="sm"
                :disabled="!academicYears.next_page_url"
                @click="$inertia.visit(academicYears.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, Calendar, CheckCircle, XCircle, Clock } from 'lucide-vue-next'

interface Props {
  academicYears: {
    data: Array<{
      id: number
      name: string
      description?: string
      start_date: string
      end_date: string
      is_active: boolean
      classrooms_count?: number
    }>
    total: number
    from: number
    to: number
    last_page: number
    prev_page_url?: string
    next_page_url?: string
  }
  statistics: {
    total: number
    active: number
    inactive: number
    current: 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 = () => {
  router.get(route('academic-years.index'), {
    search: filters.search || undefined,
    status: filters.status !== 'all' ? filters.status : undefined,
  }, {
    preserveState: true,
    replace: true
  })
}

const debouncedSearch = debounce(search, 300)

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

const deleteAcademicYear = (yearId: number) => {
  if (confirm('Are you sure you want to delete this academic year? This action cannot be undone.')) {
    router.delete(route('academic-years.destroy', yearId), {
      preserveScroll: true,
      onSuccess: () => {
        toast.success('Academic year deleted successfully!')
      },
      onError: (errors) => {
        let errorMessage = 'Failed to delete academic year. Please try again.'

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

        toast.error(errorMessage)
      }
    })
  }
}

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