<template>
  <AppLayout title="Edit Student">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Edit Student</h1>
          <p class="text-muted-foreground">
            Update student information and details
          </p>
        </div>
      </div>

      <!-- Form Card -->
      <Card>
        <CardHeader>
          <CardTitle>Student Information</CardTitle>
          <CardDescription>
            Update the student's personal and academic information
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form @submit.prevent="submit" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <!-- Personal Information -->
              <div class="space-y-2">
                <Label for="first_name">First Name *</Label>
                <Input
                  id="first_name"
                  v-model="form.first_name"
                  type="text"
                  :class="{ 'border-destructive': form.errors.first_name }"
                />
                <p v-if="form.errors.first_name" class="text-sm text-destructive">
                  {{ form.errors.first_name }}
                </p>
              </div>

              <div class="space-y-2">
                <Label for="last_name">Last Name *</Label>
                <Input
                  id="last_name"
                  v-model="form.last_name"
                  type="text"
                  :class="{ 'border-destructive': form.errors.last_name }"
                />
                <p v-if="form.errors.last_name" class="text-sm text-destructive">
                  {{ form.errors.last_name }}
                </p>
              </div>

              <div class="space-y-2">
                <Label for="email">Email *</Label>
                <Input
                  id="email"
                  v-model="form.email"
                  type="email"
                  :class="{ 'border-destructive': form.errors.email }"
                />
                <p v-if="form.errors.email" class="text-sm text-destructive">
                  {{ form.errors.email }}
                </p>
              </div>

              <div class="space-y-2">
                <Label for="student_id">Student ID *</Label>
                <Input
                  id="student_id"
                  v-model="form.student_id"
                  type="text"
                  :class="{ 'border-destructive': form.errors.student_id }"
                />
                <p v-if="form.errors.student_id" class="text-sm text-destructive">
                  {{ form.errors.student_id }}
                </p>
              </div>

              <div class="space-y-2">
                <Label for="date_of_birth">Date of Birth *</Label>
                <Input
                  id="date_of_birth"
                  v-model="form.date_of_birth"
                  type="date"
                  :class="{ 'border-destructive': form.errors.date_of_birth }"
                />
                <p v-if="form.errors.date_of_birth" class="text-sm text-destructive">
                  {{ form.errors.date_of_birth }}
                </p>
              </div>

              <div class="space-y-2">
                <Label for="gender">Gender *</Label>
                <Select v-model="form.gender">
                  <SelectTrigger :class="{ 'border-destructive': form.errors.gender }">
                    <SelectValue placeholder="Select gender" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="male">Male</SelectItem>
                    <SelectItem value="female">Female</SelectItem>
                    <SelectItem value="other">Other</SelectItem>
                  </SelectContent>
                </Select>
                <p v-if="form.errors.gender" class="text-sm text-destructive">
                  {{ form.errors.gender }}
                </p>
              </div>

              <div class="space-y-2">
                <Label for="phone">Phone</Label>
                <Input
                  id="phone"
                  v-model="form.phone"
                  type="tel"
                  :class="{ 'border-destructive': form.errors.phone }"
                />
                <p v-if="form.errors.phone" class="text-sm text-destructive">
                  {{ form.errors.phone }}
                </p>
              </div>

              <div class="space-y-2">
                <Label for="emergency_contact">Emergency Contact</Label>
                <Input
                  id="emergency_contact"
                  v-model="form.emergency_contact"
                  type="tel"
                  :class="{ 'border-destructive': form.errors.emergency_contact }"
                />
                <p v-if="form.errors.emergency_contact" class="text-sm text-destructive">
                  {{ form.errors.emergency_contact }}
                </p>
              </div>

              <div class="space-y-2 md:col-span-2">
                <Label for="address">Address</Label>
                <Textarea
                  id="address"
                  v-model="form.address"
                  rows="3"
                  :class="{ 'border-destructive': form.errors.address }"
                />
                <p v-if="form.errors.address" class="text-sm text-destructive">
                  {{ form.errors.address }}
                </p>
              </div>

              <div class="space-y-2">
                <Label for="admission_date">Admission Date *</Label>
                <Input
                  id="admission_date"
                  v-model="form.admission_date"
                  type="date"
                  :class="{ 'border-destructive': form.errors.admission_date }"
                />
                <p v-if="form.errors.admission_date" class="text-sm text-destructive">
                  {{ form.errors.admission_date }}
                </p>
              </div>

              <div class="space-y-2">
                <Label>Status</Label>
                <div class="flex items-center space-x-2">
                  <Checkbox
                    id="is_active"
                    v-model:checked="form.is_active"
                  />
                  <Label for="is_active" class="text-sm font-normal">
                    Active student
                  </Label>
                </div>
              </div>
            </div>

            <!-- Guardian Management Section -->
            <div class="space-y-4 pt-6 border-t">
              <div class="flex items-center justify-between">
                <div>
                  <h3 class="text-lg font-medium">Guardian Information</h3>
                  <p class="text-sm text-muted-foreground">
                    Manage guardians and their relationships to this student
                  </p>
                </div>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  @click="addGuardian"
                  :disabled="form.guardians.length >= 4"
                >
                  Add Guardian
                </Button>
              </div>

              <div v-if="form.guardians.length === 0" class="text-center py-8 text-muted-foreground">
                No guardians assigned. Click "Add Guardian" to assign guardians to this student.
              </div>

              <div v-else class="space-y-4">
                <div
                  v-for="(guardian, index) in form.guardians"
                  :key="index"
                  class="p-4 border rounded-lg space-y-4"
                >
                  <div class="flex items-center justify-between">
                    <h4 class="font-medium">Guardian {{ index + 1 }}</h4>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      @click="removeGuardian(index)"
                    >
                      Remove
                    </Button>
                  </div>

                  <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="space-y-2">
                      <Label :for="`guardian_${index}`">Guardian *</Label>
                      <Select v-model="guardian.guardian_id">
                        <SelectTrigger :class="{ 'border-destructive': form.errors[`guardians.${index}.guardian_id`] }">
                          <SelectValue placeholder="Select guardian" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem
                            v-for="availableGuardian in guardians"
                            :key="availableGuardian.id"
                            :value="availableGuardian.id.toString()"
                          >
                            {{ availableGuardian.user?.first_name }} {{ availableGuardian.user?.last_name }}
                            ({{ availableGuardian.user?.email }})
                          </SelectItem>
                        </SelectContent>
                      </Select>
                      <p v-if="form.errors[`guardians.${index}.guardian_id`]" class="text-sm text-destructive">
                        {{ form.errors[`guardians.${index}.guardian_id`] }}
                      </p>
                    </div>

                    <div class="space-y-2">
                      <Label :for="`relationship_${index}`">Relationship *</Label>
                      <Select v-model="guardian.relationship">
                        <SelectTrigger :class="{ 'border-destructive': form.errors[`guardians.${index}.relationship`] }">
                          <SelectValue placeholder="Select relationship" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="father">Father</SelectItem>
                          <SelectItem value="mother">Mother</SelectItem>
                          <SelectItem value="guardian">Guardian</SelectItem>
                          <SelectItem value="other">Other</SelectItem>
                        </SelectContent>
                      </Select>
                      <p v-if="form.errors[`guardians.${index}.relationship`]" class="text-sm text-destructive">
                        {{ form.errors[`guardians.${index}.relationship`] }}
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              <p v-if="form.errors.guardians" class="text-sm text-destructive">
                {{ form.errors.guardians }}
              </p>
            </div>

            <!-- Form Actions -->
            <div class="flex items-center justify-end space-x-3 pt-6 border-t">
              <Button variant="outline" type="button" as-child>
                <Link :href="route('students.index')">
                  Cancel
                </Link>
              </Button>
              <Button type="submit" :disabled="form.processing">
                <span v-if="form.processing">Updating...</span>
                <span v-else>Update Student</span>
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { useForm, Link } from '@inertiajs/vue3'
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 { Checkbox } from '@/components/ui/checkbox'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'

interface Student {
  id: number
  student_id: string
  first_name: string
  last_name: string
  date_of_birth: string
  gender: string
  address?: string
  phone?: string
  emergency_contact?: string
  admission_date: string
  is_active: boolean
  user?: {
    email: string
  }
  guardians?: Array<{
    id: number
    pivot: {
      relationship: string
    }
    user?: {
      first_name: string
      last_name: string
      email: string
    }
  }>
}

interface Guardian {
  id: number
  user?: {
    first_name: string
    last_name: string
    email: string
  }
}

interface GuardianForm {
  guardian_id: string
  relationship: string
}

const props = defineProps<{
  student: Student
  academicYears?: any[]
  guardians?: Guardian[]
}>()

const form = useForm({
  first_name: props.student.first_name || '',
  last_name: props.student.last_name || '',
  email: props.student.user?.email || '',
  student_id: props.student.student_id,
  date_of_birth: props.student.date_of_birth,
  gender: props.student.gender,
  address: props.student.address || '',
  phone: props.student.phone || '',
  emergency_contact: props.student.emergency_contact || '',
  admission_date: props.student.admission_date,
  is_active: props.student.is_active,
  guardians: (props.student.guardians || []).map(guardian => ({
    guardian_id: guardian.id.toString(),
    relationship: guardian.pivot.relationship
  })) as GuardianForm[]
})

const addGuardian = () => {
  if (form.guardians.length < 4) {
    form.guardians.push({
      guardian_id: '',
      relationship: ''
    })
  }
}

const removeGuardian = (index: number) => {
  form.guardians.splice(index, 1)
}

const submit = () => {
  form.put(route('students.update', props.student.id))
}
</script>
