<template>
  <AppLayout title="Classrooms">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Classrooms</h1>
          <p class="text-muted-foreground">
            Manage classrooms and their academic assignments
          </p>
        </div>
        <Button @click="$inertia.visit(route('classrooms.create'))">
          <Plus class="mr-2 h-4 w-4" />
          Add Classroom
        </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>

      <!-- 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 classrooms..."
                @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="flex items-end">
              <Button variant="outline" @click="clearFilters" class="w-full">
                Clear Filters
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Classrooms Table -->
      <Card>
        <CardHeader>
          <CardTitle>Classrooms ({{ classrooms.total }})</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Academic Year</TableHead>
                  <TableHead>Capacity</TableHead>
                  <TableHead>Subjects</TableHead>
                  <TableHead>Academic Year Status</TableHead>
                  <TableHead class="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                <TableRow v-for="classroom in classrooms.data" :key="classroom.id">
                  <TableCell>
                    <div>
                      <div class="font-medium">{{ classroom.name }}</div>
                      <div class="text-sm text-muted-foreground">{{ classroom.description }}</div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {{ classroom.academic_year?.name || 'N/A' }}
                    </Badge>
                  </TableCell>
                  <TableCell>{{ classroom.capacity || 'N/A' }}</TableCell>
                  <TableCell>
                    <div class="flex flex-wrap gap-1">
                      <Badge v-for="subject in classroom.subjects?.slice(0, 3)" :key="subject.id" variant="secondary" class="text-xs">
                        {{ subject.name }}
                      </Badge>
                      <Badge v-if="classroom.subjects?.length > 3" variant="outline" class="text-xs">
                        +{{ classroom.subjects.length - 3 }} more
                      </Badge>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge :variant="classroom.academic_year?.is_active ? 'default' : 'secondary'">
                      {{ classroom.academic_year?.is_active ? 'Active Year' : 'Inactive Year' }}
                    </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('classrooms.show', classroom.id))">
                          <Eye class="mr-2 h-4 w-4" />
                          View
                        </DropdownMenuItem>
                        <DropdownMenuItem @click="$inertia.visit(route('classrooms.edit', classroom.id))">
                          <Edit class="mr-2 h-4 w-4" />
                          Edit
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem
                          @click="deleteClassroom(classroom.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="classrooms.last_page > 1">
            <div class="text-sm text-muted-foreground">
              Showing {{ classrooms.from }} to {{ classrooms.to }} of {{ classrooms.total }} results
            </div>
            <div class="flex space-x-2">
              <Button
                variant="outline"
                size="sm"
                :disabled="!classrooms.prev_page_url"
                @click="$inertia.visit(classrooms.prev_page_url)"
              >
                Previous
              </Button>
              <Button
                variant="outline"
                size="sm"
                :disabled="!classrooms.next_page_url"
                @click="$inertia.visit(classrooms.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 } from 'lucide-vue-next'

interface Props {
  classrooms: {
    data: Array<{
      id: number
      name: string
      description?: string
      capacity?: number
      academic_year?: {
        id: number
        name: string
        is_active: boolean
      }
      subjects?: Array<{
        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
  }>
  filters: {
    search?: string
    academic_year_id?: string
  }
}

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

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

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

const debouncedSearch = debounce(search, 300)

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

const deleteClassroom = (classroomId: number) => {
  if (confirm('Are you sure you want to delete this classroom? This action cannot be undone.')) {
    router.delete(route('classrooms.destroy', classroomId), {
      preserveScroll: true,
      onSuccess: () => {
        toast.success('Classroom deleted successfully!')
      },
      onError: (errors) => {
        let errorMessage = 'Failed to delete classroom. Please try again.'

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

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