<template>
    <AppLayout title="Students">
        <div class="space-y-6">
            <!-- Header -->
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold tracking-tight">Students</h1>
                    <p class="text-muted-foreground">
                        Manage student records and information
                    </p>
                </div>
                <div class="flex gap-2">
                    <Button variant="outline" @click="exportStudents">
                        <Download class="w-4 h-4 mr-2" />
                        Export
                    </Button>
                    <Button as-child>
                        <Link :href="route('students.create')">
                            <Plus class="w-4 h-4 mr-2" />
                            Add Student
                        </Link>
                    </Button>
                </div>
            </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>

        <div class="py-6">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <!-- Search and Filters Card -->
                <Card class="mb-6">
                    <CardHeader>
                        <CardTitle class="flex items-center gap-2">
                            <Filter class="w-5 h-5" />
                            Filters & Search
                        </CardTitle>
                        <CardDescription>
                            Search and filter students by various criteria
                        </CardDescription>
                    </CardHeader>
                    <CardContent>
                        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                            <div class="relative">
                                <Search class="absolute left-3 top-3 h-4 w-4 text-gray-400" />
                                <Input
                                    v-model="filters.search"
                                    placeholder="Search students..."
                                    class="pl-10"
                                    @input="search"
                                />
                            </div>
                            <Select v-model="filters.status" @update:model-value="search">
                                <SelectTrigger>
                                    <SelectValue placeholder="All Status" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">All Students</SelectItem>
                                    <SelectItem value="active">Active</SelectItem>
                                    <SelectItem value="inactive">Inactive</SelectItem>
                                </SelectContent>
                            </Select>
                            <Select v-model="filters.class" @update:model-value="search">
                                <SelectTrigger>
                                    <SelectValue placeholder="All Classes" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">All Classes</SelectItem>
                                    <SelectItem value="grade-1">Grade 1</SelectItem>
                                    <SelectItem value="grade-2">Grade 2</SelectItem>
                                    <SelectItem value="grade-3">Grade 3</SelectItem>
                                </SelectContent>
                            </Select>
                            <Button variant="outline" @click="clearFilters" class="w-full">
                                Clear Filters
                            </Button>
                        </div>
                    </CardContent>
                </Card>

                <!-- Students Table -->
                <Card>
                    <CardHeader>
                        <CardTitle class="flex items-center justify-between">
                            <div class="flex items-center gap-2">
                                <UserCheck class="w-5 h-5" />
                                Students List
                            </div>
                            <Badge variant="secondary">{{ students.total }} total</Badge>
                        </CardTitle>
                        <CardDescription>
                            Manage and view all student records
                        </CardDescription>
                    </CardHeader>
                    <CardContent>
                        <div v-if="students.data.length === 0" class="text-center py-12">
                            <UserCheck class="w-12 h-12 text-gray-400 mx-auto mb-4" />
                            <p class="text-gray-500 text-lg">No students found</p>
                            <p class="text-gray-400 text-sm">Try adjusting your search criteria</p>
                        </div>
                        <div v-else class="overflow-x-auto">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Student</TableHead>
                                        <TableHead>Student ID</TableHead>
                                        <TableHead>Contact</TableHead>
                                        <TableHead>Status</TableHead>
                                        <TableHead>Admission Date</TableHead>
                                        <TableHead class="text-right">Actions</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    <TableRow v-for="student in students.data" :key="student.id">
                                        <TableCell>
                                            <div class="flex items-center gap-3">
                                                <div class="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center">
                          <span class="text-sm font-medium text-primary">
                            {{ (student.first_name || '').charAt(0) }}{{ (student.last_name || '').charAt(0) }}
                          </span>
                                                </div>
                                                <div>
                                                    <div class="font-medium">
                                                        {{ student.first_name }} {{ student.last_name }}
                                                    </div>
                                                    <div class="text-sm text-muted-foreground">
                                                        {{ student.user?.email || 'No email' }}
                                                    </div>
                                                </div>
                                            </div>
                                        </TableCell>
                                        <TableCell class="font-mono">{{ student.student_id }}</TableCell>
                                        <TableCell>{{ student.phone || 'N/A' }}</TableCell>
                                        <TableCell>
                                            <Badge :variant="student.is_active ? 'default' : 'secondary'">
                                                {{ student.is_active ? 'Active' : 'Inactive' }}
                                            </Badge>
                                        </TableCell>
                                        <TableCell>{{ formatDate(student.admission_date) }}</TableCell>
                                        <TableCell class="text-right">
                                            <DropdownMenu>
                                                <DropdownMenuTrigger as-child>
                                                    <Button variant="ghost" size="sm">
                                                        <MoreHorizontal class="w-4 h-4" />
                                                    </Button>
                                                </DropdownMenuTrigger>
                                                <DropdownMenuContent align="end">
                                                    <DropdownMenuItem as-child>
                                                        <Link :href="route('students.show', student.id)">
                                                            <Eye class="w-4 h-4 mr-2" />
                                                            View Details
                                                        </Link>
                                                    </DropdownMenuItem>
                                                    <DropdownMenuItem as-child>
                                                        <Link :href="route('students.edit', student.id)">
                                                            <Edit class="w-4 h-4 mr-2" />
                                                            Edit Student
                                                        </Link>
                                                    </DropdownMenuItem>
                                                    <DropdownMenuItem
                                                        class="text-destructive"
                                                        @click="deleteStudent(student.id)"
                                                    >
                                                        <Trash2 class="w-4 h-4 mr-2" />
                                                        Delete Student
                                                    </DropdownMenuItem>
                                                </DropdownMenuContent>
                                            </DropdownMenu>
                                        </TableCell>
                                    </TableRow>
                                </TableBody>
                            </Table>
                        </div>

                        <!-- Pagination -->
                        <div v-if="students.links.length > 3" class="mt-6">
                            <nav class="flex items-center justify-between">
                                <div class="flex-1 flex justify-between sm:hidden">
                                    <Button variant="outline" as-child v-if="students.prev_page_url">
                                        <Link :href="students.prev_page_url">Previous</Link>
                                    </Button>
                                    <Button variant="outline" as-child v-if="students.next_page_url">
                                        <Link :href="students.next_page_url">Next</Link>
                                    </Button>
                                </div>
                                <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                                    <div>
                                        <p class="text-sm text-muted-foreground">
                                            Showing {{ students.from }} to {{ students.to }} of {{ students.total }} results
                                        </p>
                                    </div>
                                    <div class="flex gap-1">
                                        <template v-for="(link, index) in students.links" :key="index">
                                            <Button
                                                v-if="link.url"
                                                :variant="link.active ? 'default' : 'outline'"
                                                size="sm"
                                                as-child
                                            >
                                                <Link :href="link.url" v-html="link.label" />
                                            </Button>
                                            <Button
                                                v-else
                                                variant="outline"
                                                size="sm"
                                                disabled
                                                v-html="link.label"
                                            />
                                        </template>
                                    </div>
                                </div>
                            </nav>
                        </div>
                    </CardContent>
                </Card>
            </div>
        </div>
        </div>
    </AppLayout>
</template>

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

const props = defineProps({
    students: {
        type: Object,
        required: true
    },
    filters: {
        type: Object,
        default: () => ({})
    }
})

const page = usePage()
const toast = useToast()

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

const search = debounce(() => {
    router.get(route('students.index'), filters, {
        preserveState: true,
        replace: true
    })
}, 300)

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

const exportStudents = () => {
    // Implementation for exporting students data
    window.open('/students/export', '_blank')
}

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

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

                toast.error(errorMessage)
            }
        })
    }
}

const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    })
}
</script>
