<template>
    <AppLayout title="Subjects">
        <div class="space-y-6">
            <!-- Header -->
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold tracking-tight">Subjects</h1>
                    <p class="text-muted-foreground">
                        Manage subjects and their assignments
                    </p>
                </div>
                <Button @click="$inertia.visit(route('subjects.create'))">
                    <Plus class="mr-2 h-4 w-4" />
                    Add Subject
                </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 Subjects</CardTitle>
                        <BookOpen 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 Subjects</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">Assigned Teachers</CardTitle>
                        <Users class="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div class="text-2xl font-bold">{{ statistics.assigned_teachers }}</div>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle class="text-sm font-medium">Classrooms</CardTitle>
                        <School class="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div class="text-2xl font-bold">{{ statistics.classrooms }}</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 subjects..."
                                @input="debouncedSearch"
                            />
                        </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="teacher">Teacher</Label>
                            <Select v-model="filters.teacher_id" @update:model-value="search">
                                <SelectTrigger>
                                    <SelectValue placeholder="All Teachers" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">All Teachers</SelectItem>
                                    <SelectItem v-for="teacher in teachers" :key="teacher.id" :value="teacher.id.toString()">
                                        {{ teacher.first_name }} {{ teacher.last_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 Subjects</SelectItem>
                                    <SelectItem value="active">Active</SelectItem>
                                    <SelectItem value="inactive">Inactive</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                    <div class="flex justify-end mt-4">
                        <Button variant="outline" @click="clearFilters">
                            Clear Filters
                        </Button>
                    </div>
                </CardContent>
            </Card>

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

interface Props {
    subjects: {
        data: Array<{
            id: number
            name: string
            code: string
            description?: string
            is_active: boolean
            classrooms?: Array<{
                id: number
                name: string
            }>
            teachers_count?: number
        }>
        total: number
        from: number
        to: number
        last_page: number
        prev_page_url?: string
        next_page_url?: string
    }
    classrooms: Array<{
        id: number
        name: string
    }>
    teachers: Array<{
        id: number
        first_name: string
        last_name: string
    }>
    statistics: {
        total: number
        active: number
        assigned_teachers: number
        classrooms: number
    }
    filters: {
        search?: string
        classroom_id?: string
        teacher_id?: string
        status?: string
    }
}

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

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

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

const debouncedSearch = debounce(search, 300)

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

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

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

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