<template>
  <AppLayout title="Teachers">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Teachers</h1>
          <p class="text-muted-foreground">
            Manage teaching staff and their assignments
          </p>
        </div>
        <div class="flex gap-2">
          <Button variant="outline" @click="exportTeachers">
            <Download class="w-4 h-4 mr-2" />
            Export
          </Button>
          <Button as-child>
            <Link :href="route('teachers.create')">
              <Plus class="w-4 h-4 mr-2" />
              Add Teacher
            </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 teachers 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 teachers..."
                  class="pl-10"
                  @input="search"
                />
              </div>
              <Select v-model="filters.subject_id" @update:model-value="search">
                <SelectTrigger>
                  <SelectValue placeholder="All Subjects" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Subjects</SelectItem>
                  <SelectItem v-for="subject in subjects" :key="subject.id" :value="subject.id.toString()">
                    {{ subject.name }}
                  </SelectItem>
                </SelectContent>
              </Select>
              <Select v-model="filters.status" @update:model-value="search">
                <SelectTrigger>
                  <SelectValue placeholder="All Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Teachers</SelectItem>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="inactive">Inactive</SelectItem>
                </SelectContent>
              </Select>
              <Button variant="outline" @click="clearFilters" class="w-full">
                Clear Filters
              </Button>
            </div>
          </CardContent>
        </Card>

        <!-- Teachers Table -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center justify-between">
              <div class="flex items-center gap-2">
                <Users class="w-5 h-5" />
                Teachers List
              </div>
              <Badge variant="secondary">{{ teachers.total }} total</Badge>
            </CardTitle>
            <CardDescription>
              Manage and view all teaching staff records
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div v-if="teachers.data.length === 0" class="text-center py-12">
              <Users class="w-12 h-12 text-gray-400 mx-auto mb-4" />
              <p class="text-gray-500 text-lg">No teachers 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>Teacher</TableHead>
                    <TableHead>Employee ID</TableHead>
                    <TableHead>Contact</TableHead>
                    <TableHead>Subjects</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Hire Date</TableHead>
                    <TableHead class="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  <TableRow v-for="teacher in teachers.data" :key="teacher.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">
                            {{ (teacher.first_name || '').charAt(0) }}{{ (teacher.last_name || '').charAt(0) }}
                          </span>
                        </div>
                        <div>
                          <div class="font-medium">
                            {{ teacher.first_name }} {{ teacher.last_name }}
                          </div>
                          <div class="text-sm text-muted-foreground">
                            {{ teacher.user?.email }}
                          </div>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell class="font-mono">{{ teacher.employee_id }}</TableCell>
                    <TableCell>{{ teacher.phone || 'N/A' }}</TableCell>
                    <TableCell>
                      <div v-if="teacher.subjects && teacher.subjects.length > 0" class="flex flex-wrap gap-1">
                        <Badge
                          v-for="subject in teacher.subjects.slice(0, 2)"
                          :key="subject.id"
                          variant="outline"
                          class="text-xs"
                        >
                          {{ subject.name }}
                        </Badge>
                        <Badge
                          v-if="teacher.subjects.length > 2"
                          variant="secondary"
                          class="text-xs"
                        >
                          +{{ teacher.subjects.length - 2 }} more
                        </Badge>
                      </div>
                      <span v-else class="text-muted-foreground text-sm">No subjects assigned</span>
                    </TableCell>
                    <TableCell>
                      <Badge :variant="teacher.is_active ? 'default' : 'secondary'">
                        {{ teacher.is_active ? 'Active' : 'Inactive' }}
                      </Badge>
                    </TableCell>
                    <TableCell>{{ formatDate(teacher.hire_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('teachers.show', teacher.id)">
                              <Eye class="w-4 h-4 mr-2" />
                              View Details
                            </Link>
                          </DropdownMenuItem>
                          <DropdownMenuItem as-child>
                            <Link :href="route('teachers.edit', teacher.id)">
                              <Edit class="w-4 h-4 mr-2" />
                              Edit Teacher
                            </Link>
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            class="text-destructive"
                            @click="deleteTeacher(teacher.id)"
                          >
                            <Trash2 class="w-4 h-4 mr-2" />
                            Delete Teacher
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </div>

            <!-- Pagination -->
            <div v-if="teachers.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="teachers.prev_page_url">
                    <Link :href="teachers.prev_page_url">Previous</Link>
                  </Button>
                  <Button variant="outline" as-child v-if="teachers.next_page_url">
                    <Link :href="teachers.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 {{ teachers.from }} to {{ teachers.to }} of {{ teachers.total }} results
                    </p>
                  </div>
                  <div class="flex gap-1">
                    <template v-for="(link, index) in teachers.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 { 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, Users } from 'lucide-vue-next'

const props = defineProps({
  teachers: {
    type: Object,
    required: true
  },
  subjects: {
    type: Array,
    default: () => []
  },
  filters: {
    type: Object,
    default: () => ({})
  }
})

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

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

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

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

const exportTeachers = () => {
  window.open('/teachers/export', '_blank')
}

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

        if (errors.teacher) {
          errorMessage = Array.isArray(errors.teacher) ? errors.teacher[0] : errors.teacher
        } 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>
