<template>
  <AppLayout title="Guardians">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Guardians</h1>
          <p class="text-muted-foreground">
            Manage student guardians and emergency contacts
          </p>
        </div>
        <div class="flex gap-2">
          <Button variant="outline" @click="exportGuardians">
            <Download class="w-4 h-4 mr-2" />
            Export
          </Button>
          <Button as-child>
            <Link :href="route('guardians.create')">
              <Plus class="w-4 h-4 mr-2" />
              Add Guardian
            </Link>
          </Button>
        </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 guardians 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 guardians..."
                  class="pl-10"
                  @input="search"
                />
              </div>
              <Select v-model="filters.relationship" @update:model-value="search">
                <SelectTrigger>
                  <SelectValue placeholder="All Relationships" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Relationships</SelectItem>
                  <SelectItem value="father">Father</SelectItem>
                  <SelectItem value="mother">Mother</SelectItem>
                  <SelectItem value="guardian">Guardian</SelectItem>
                  <SelectItem value="other">Other</SelectItem>
                </SelectContent>
              </Select>
              <Select v-model="filters.status" @update:model-value="search">
                <SelectTrigger>
                  <SelectValue placeholder="All Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Guardians</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>

        <!-- Guardians Table -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center justify-between">
              <div class="flex items-center gap-2">
                <UserCheck class="w-5 h-5" />
                Guardians List
              </div>
              <Badge variant="secondary">{{ guardians.total }} total</Badge>
            </CardTitle>
            <CardDescription>
              Manage and view all guardian records
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div v-if="guardians.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 guardians 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>Guardian</TableHead>
                    <TableHead>Contact</TableHead>
                    <TableHead>Relationship</TableHead>
                    <TableHead>Students</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Emergency Contact</TableHead>
                    <TableHead class="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  <TableRow v-for="guardian in guardians.data" :key="guardian.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">
                            {{ (guardian.first_name || '').charAt(0) }}{{ (guardian.last_name || '').charAt(0) }}
                          </span>
                        </div>
                        <div>
                          <div class="font-medium">
                            {{ guardian.first_name }} {{ guardian.last_name }}
                          </div>
                          <div class="text-sm text-muted-foreground">
                            {{ guardian.user?.email }}
                          </div>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div>{{ guardian.phone || 'N/A' }}</div>
                      <div v-if="guardian.work_phone" class="text-xs text-muted-foreground">
                        Work: {{ guardian.work_phone }}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline" class="capitalize">
                        {{ guardian.relationship || 'N/A' }}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div v-if="guardian.students && guardian.students.length > 0">
                        <div v-for="student in guardian.students.slice(0, 2)" :key="student.id" class="text-sm">
                          {{ student.user?.first_name }} {{ student.user?.last_name }}
                        </div>
                        <div v-if="guardian.students.length > 2" class="text-xs text-muted-foreground">
                          +{{ guardian.students.length - 2 }} more
                        </div>
                      </div>
                      <span v-else class="text-muted-foreground text-sm">No students</span>
                    </TableCell>
                    <TableCell>
                      <Badge :variant="guardian.is_active ? 'default' : 'secondary'">
                        {{ guardian.is_active ? 'Active' : 'Inactive' }}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge
                        v-if="guardian.is_emergency_contact"
                        variant="destructive"
                        class="text-xs"
                      >
                        Emergency
                      </Badge>
                      <span v-else class="text-muted-foreground text-xs">No</span>
                    </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('guardians.show', guardian.id)">
                              <Eye class="w-4 h-4 mr-2" />
                              View Details
                            </Link>
                          </DropdownMenuItem>
                          <DropdownMenuItem as-child>
                            <Link :href="route('guardians.edit', guardian.id)">
                              <Edit class="w-4 h-4 mr-2" />
                              Edit Guardian
                            </Link>
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            class="text-destructive"
                            @click="deleteGuardian(guardian.id)"
                          >
                            <Trash2 class="w-4 h-4 mr-2" />
                            Delete Guardian
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </div>

            <!-- Pagination -->
            <div v-if="guardians.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="guardians.prev_page_url">
                    <Link :href="guardians.prev_page_url">Previous</Link>
                  </Button>
                  <Button variant="outline" as-child v-if="guardians.next_page_url">
                    <Link :href="guardians.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 {{ guardians.from }} to {{ guardians.to }} of {{ guardians.total }} results
                    </p>
                  </div>
                  <div class="flex gap-1">
                    <template v-for="(link, index) in guardians.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 } from '@inertiajs/vue3'
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({
  guardians: {
    type: Object,
    required: true
  },
  filters: {
    type: Object,
    default: () => ({})
  }
})

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

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

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

const exportGuardians = () => {
  window.open('/guardians/export', '_blank')
}

const deleteGuardian = (guardianId: number) => {
  if (confirm('Are you sure you want to delete this guardian?')) {
    router.delete(route('guardians.destroy', guardianId), {
      onSuccess: () => {
        router.reload({ only: ['guardians'] })
      }
    })
  }
}
</script>
