<template>
  <AppLayout title="Create Enrollment">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Create Enrollment</h1>
          <p class="text-muted-foreground">
            Enroll a student in a classroom for an academic year
          </p>
        </div>
      </div>

      <!-- Form Card -->
      <Card>
        <CardHeader>
          <CardTitle>Enrollment Information</CardTitle>
          <CardDescription>
            Select the student, classroom, and academic year for this enrollment
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form @submit.prevent="submit" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <!-- Academic Year -->
              <div class="space-y-2">
                <Label for="academic_year_id">Academic Year *</Label>
                <Select v-model="form.academic_year_id" @update:model-value="onAcademicYearChange">
                  <SelectTrigger :class="{ 'border-destructive': form.errors.academic_year_id }">
                    <SelectValue placeholder="Select academic year" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem
                      v-for="academicYear in academicYears"
                      :key="academicYear.id"
                      :value="academicYear.id.toString()"
                    >
                      {{ academicYear.name }} ({{ formatDate(academicYear.start_date) }} - {{ formatDate(academicYear.end_date) }})
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p v-if="form.errors.academic_year_id" class="text-sm text-destructive">
                  {{ form.errors.academic_year_id }}
                </p>
              </div>

              <!-- Classroom -->
              <div class="space-y-2">
                <Label for="classroom_id">Classroom *</Label>
                <Select v-model="form.classroom_id">
                  <SelectTrigger :class="{ 'border-destructive': form.errors.classroom_id }">
                    <SelectValue placeholder="Select classroom" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem
                      v-for="classroom in filteredClassrooms"
                      :key="classroom.id"
                      :value="classroom.id.toString()"
                    >
                      {{ classroom.name }}
                      <span v-if="classroom.academic_year" class="text-muted-foreground ml-2">
                        ({{ classroom.academic_year.name }})
                      </span>
                      <span v-if="classroom.capacity" class="text-muted-foreground ml-2">
                        - Capacity: {{ classroom.capacity }}
                      </span>
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p v-if="form.errors.classroom_id" class="text-sm text-destructive">
                  {{ form.errors.classroom_id }}
                </p>
                <p v-if="!filteredClassrooms.length && form.academic_year_id" class="text-sm text-muted-foreground">
                  No classrooms available for the selected academic year
                </p>
              </div>

              <!-- Student -->
              <div class="col-span-2 space-y-2">
                <Label for="student_id">Student *</Label>
                <Select v-model="form.student_id">
                  <SelectTrigger :class="{ 'border-destructive': form.errors.student_id }">
                    <SelectValue placeholder="Select student" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem
                      v-for="student in students"
                      :key="student.id"
                      :value="student.id.toString()"
                    >
                      {{ student.user?.name }}
                      <span class="text-muted-foreground ml-2">({{ student.student_id }})</span>
                      <span v-if="student.user?.email" class="text-muted-foreground ml-2">
                        - {{ student.user.email }}
                      </span>
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p v-if="form.errors.student_id" class="text-sm text-destructive">
                  {{ form.errors.student_id }}
                </p>
              </div>

              <!-- Enrollment Date -->
              <div class="space-y-2">
                <Label for="enrolled_at">Enrollment Date</Label>
                <Input
                  id="enrolled_at"
                  v-model="form.enrolled_at"
                  type="date"
                  :max="today"
                  :class="{ 'border-destructive': form.errors.enrolled_at }"
                />
                <p v-if="form.errors.enrolled_at" class="text-sm text-destructive">
                  {{ form.errors.enrolled_at }}
                </p>
                <p class="text-sm text-muted-foreground">
                  Leave empty to use today's date
                </p>
              </div>

              <!-- Status -->
              <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"
                    :class="{ 'border-destructive': form.errors.is_active }"
                  />
                  <Label for="is_active" class="text-sm font-normal">
                    Active enrollment
                  </Label>
                </div>
                <p v-if="form.errors.is_active" class="text-sm text-destructive">
                  {{ form.errors.is_active }}
                </p>
                <p class="text-sm text-muted-foreground">
                  Inactive enrollments won't appear in active student lists
                </p>
              </div>
            </div>

            <!-- Enrollment Summary -->
            <div v-if="form.student_id && form.classroom_id && form.academic_year_id" class="mt-6 p-4 bg-muted rounded-lg">
              <h3 class="font-medium mb-2">Enrollment Summary</h3>
              <div class="space-y-1 text-sm">
                <p><strong>Student:</strong> {{ getSelectedStudentName() }}</p>
                <p><strong>Classroom:</strong> {{ getSelectedClassroomName() }}</p>
                <p><strong>Academic Year:</strong> {{ getSelectedAcademicYearName() }}</p>
                <p><strong>Enrollment Date:</strong> {{ form.enrolled_at || 'Today' }}</p>
                <p><strong>Status:</strong> {{ form.is_active ? 'Active' : 'Inactive' }}</p>
              </div>
            </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('enrollment.index')">
                  Cancel
                </Link>
              </Button>
              <Button type="submit" :disabled="form.processing">
                <span v-if="form.processing">Creating...</span>
                <span v-else>Create Enrollment</span>
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { useForm, Link } from '@inertiajs/vue3'
import { computed } from 'vue'
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 { 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
  user?: {
    first_name: string
    last_name: string
    email?: string
  }
}

interface Classroom {
  id: number
  name: string
  capacity?: number
  academic_year_id: number
  academic_year?: {
    id: number
    name: string
  }
}

interface AcademicYear {
  id: number
  name: string
  start_date: string
  end_date: string
}

const props = defineProps<{
  academicYears: AcademicYear[]
  classrooms: Classroom[]
  students: Student[]
}>()

const form = useForm({
  student_id: '',
  classroom_id: '',
  academic_year_id: '',
  enrolled_at: '',
  is_active: true
})

const today = new Date().toISOString().split('T')[0]

const filteredClassrooms = computed(() => {
  if (!form.academic_year_id) return []
  return props.classrooms.filter(classroom =>
    classroom.academic_year_id.toString() === form.academic_year_id
  )
})

const onAcademicYearChange = () => {
  // Reset classroom when academic year changes
  form.classroom_id = ''
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

const getSelectedStudentName = () => {
  const student = props.students.find(s => s.id.toString() === form.student_id)
  return student ? student.user?.name || '' : ''
}

const getSelectedClassroomName = () => {
  const classroom = props.classrooms.find(c => c.id.toString() === form.classroom_id)
  return classroom?.name || ''
}

const getSelectedAcademicYearName = () => {
  const academicYear = props.academicYears.find(ay => ay.id.toString() === form.academic_year_id)
  return academicYear?.name || ''
}

const submit = () => {
  form.post(route('enrollment.store'))
}
</script>
