<template>
  <AppLayout title="Bulk Enrollment">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Bulk Enrollment</h1>
          <p class="text-muted-foreground">
            Enroll multiple students in a classroom at once
          </p>
        </div>
        <Button variant="outline" as-child>
          <Link :href="route('enrollment.index')">
            <ArrowLeft class="mr-2 h-4 w-4" />
            Back to Enrollments
          </Link>
        </Button>
      </div>

      <!-- Form Card -->
      <Card>
        <CardHeader>
          <CardTitle>Bulk Enrollment Setup</CardTitle>
          <CardDescription>
            Select the academic year and classroom, then choose students to enroll
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form @submit.prevent="submit" class="space-y-6">
            <!-- Step 1: Academic Year and Classroom Selection -->
            <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 }}
                      <span class="text-muted-foreground ml-2">
                        ({{ formatDate(academicYear.start_date) }} - {{ formatDate(academicYear.end_date) }})
                      </span>
                    </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" @update:model-value="onClassroomChange">
                  <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.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>
            </div>

            <!-- Classroom Info -->
            <div v-if="selectedClassroom" class="p-4 bg-blue-50 border border-blue-200 rounded-lg">
              <h3 class="font-medium text-blue-900 mb-2">Classroom Information</h3>
              <div class="text-sm text-blue-800 space-y-1">
                <p><strong>Name:</strong> {{ selectedClassroom.name }}</p>
                <p v-if="selectedClassroom.capacity">
                  <strong>Capacity:</strong> {{ selectedClassroom.capacity }} students
                </p>
                <p v-if="selectedClassroom.current_enrollments !== undefined">
                  <strong>Current Enrollments:</strong> {{ selectedClassroom.current_enrollments }}
                </p>
                <p v-if="selectedClassroom.capacity && selectedClassroom.current_enrollments !== undefined">
                  <strong>Available Slots:</strong> {{ selectedClassroom.capacity - selectedClassroom.current_enrollments }}
                </p>
              </div>
            </div>

            <!-- Step 2: Student Selection -->
            <div v-if="form.academic_year_id && form.classroom_id" class="space-y-4">
              <div class="flex items-center justify-between">
                <Label class="text-base font-medium">Select Students to Enroll</Label>
                <div class="flex gap-2">
                  <Button type="button" variant="outline" size="sm" @click="selectAllStudents">
                    Select All
                  </Button>
                  <Button type="button" variant="outline" size="sm" @click="clearStudentSelection">
                    Clear All
                  </Button>
                </div>
              </div>

              <!-- Student Search -->
              <div class="space-y-2">
                <Label for="student_search">Search Students</Label>
                <Input
                  id="student_search"
                  v-model="studentSearch"
                  placeholder="Search by name or student ID..."
                  @input="filterStudents"
                />
              </div>

              <!-- Students List -->
              <div class="border rounded-lg max-h-96 overflow-y-auto">
                <div v-if="loading" class="p-4 text-center text-muted-foreground">
                  Loading available students...
                </div>
                <div v-else-if="filteredStudents.length === 0" class="p-4 text-center text-muted-foreground">
                  No available students found for this academic year
                </div>
                <div v-else class="space-y-2 p-4">
                  <div
                    v-for="student in filteredStudents"
                    :key="student.id"
                    class="flex items-center space-x-3 p-2 hover:bg-muted rounded-md"
                  >
                    <Checkbox
                      :id="`student-${student.id}`"
                      :checked="form.student_ids.includes(student.id)"
                      @update:checked="toggleStudent(student.id, $event)"
                    />
                    <Label :for="`student-${student.id}`" class="flex-1 cursor-pointer">
                      <div class="font-medium">
                        {{ student.user?.name }}
                      </div>
                      <div class="text-sm text-muted-foreground">
                        ID: {{ student.student_id }}
                        <span v-if="student.user?.email"> • {{ student.user.email }}</span>
                      </div>
                    </Label>
                  </div>
                </div>
              </div>

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

            <!-- Enrollment Summary -->
            <div v-if="form.student_ids.length > 0" class="p-4 bg-green-50 border border-green-200 rounded-lg">
              <h3 class="font-medium text-green-900 mb-2">Enrollment Summary</h3>
              <div class="text-sm text-green-800 space-y-1">
                <p><strong>Academic Year:</strong> {{ getSelectedAcademicYearName() }}</p>
                <p><strong>Classroom:</strong> {{ getSelectedClassroomName() }}</p>
                <p><strong>Students Selected:</strong> {{ form.student_ids.length }}</p>
                <p v-if="selectedClassroom?.capacity">
                  <strong>Capacity Check:</strong>
                  <span :class="form.student_ids.length <= (selectedClassroom.capacity - (selectedClassroom.current_enrollments || 0)) ? 'text-green-600' : 'text-red-600'">
                    {{ form.student_ids.length <= (selectedClassroom.capacity - (selectedClassroom.current_enrollments || 0)) ? 'Within capacity' : 'Exceeds capacity' }}
                  </span>
                </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 || form.student_ids.length === 0"
              >
                <span v-if="form.processing">Enrolling...</span>
                <span v-else>Enroll {{ form.student_ids.length }} Student{{ form.student_ids.length !== 1 ? 's' : '' }}</span>
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { useForm, Link, router } from '@inertiajs/vue3'
import { computed, ref, watch } from 'vue'
import { debounce } from 'lodash'
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'
import { ArrowLeft } from 'lucide-vue-next'

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
  }
  current_enrollments?: number
}

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

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

const form = useForm({
  academic_year_id: '',
  classroom_id: '',
  student_ids: [] as number[]
})

const studentSearch = ref('')
const availableStudents = ref<Student[]>([])
const loading = ref(false)

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

const selectedClassroom = computed(() => {
  if (!form.classroom_id) return null
  return props.classrooms.find(c => c.id.toString() === form.classroom_id)
})

const filteredStudents = computed(() => {
  if (!studentSearch.value) return availableStudents.value

  const search = studentSearch.value.toLowerCase()
  return availableStudents.value.filter(student =>
    student.user?.first_name?.toLowerCase().includes(search) ||
    student.user?.last_name?.toLowerCase().includes(search) ||
    student.student_id.toLowerCase().includes(search) ||
    student.user?.email?.toLowerCase().includes(search)
  )
})

const onAcademicYearChange = () => {
  form.classroom_id = ''
  form.student_ids = []
  availableStudents.value = []
}

const onClassroomChange = () => {
  form.student_ids = []
  if (form.classroom_id && form.academic_year_id) {
    loadAvailableStudents()
  }
}

const loadAvailableStudents = async () => {
  if (!form.classroom_id || !form.academic_year_id) return

  loading.value = true
  try {
    const response = await fetch(`/api/enrollment/available-students?classroom_id=${form.classroom_id}&academic_year_id=${form.academic_year_id}`)
    const data = await response.json()
    availableStudents.value = data.students || []
  } catch (error) {
    console.error('Failed to load available students:', error)
    availableStudents.value = []
  } finally {
    loading.value = false
  }
}

const toggleStudent = (studentId: number, checked: boolean) => {
  if (checked) {
    if (!form.student_ids.includes(studentId)) {
      form.student_ids.push(studentId)
    }
  } else {
    const index = form.student_ids.indexOf(studentId)
    if (index > -1) {
      form.student_ids.splice(index, 1)
    }
  }
}

const selectAllStudents = () => {
  form.student_ids = filteredStudents.value.map(s => s.id)
}

const clearStudentSelection = () => {
  form.student_ids = []
}

const filterStudents = debounce(() => {
  // Filtering is handled by computed property
}, 300)

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

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

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

const submit = () => {
  form.post(route('enrollment.process-bulk-enroll'))
}
</script>
