<template>
  <AppLayout title="Create Multiple Results">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Create Student Results</h1>
          <p class="text-muted-foreground">
            Enter examination results for multiple subjects for a student
          </p>
        </div>
        <Button variant="outline" as-child>
          <Link :href="route('results.index')">
            <ArrowLeft class="mr-2 h-4 w-4" />
            Back to Results
          </Link>
        </Button>
      </div>

      <!-- Form Card -->
      <Card>
        <CardHeader>
          <CardTitle>Student Information</CardTitle>
          <CardDescription>
            Select the student and exam details first
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form @submit.prevent="submit" class="space-y-6">
            <!-- Student Selection Section -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 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 }}
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p v-if="form.errors.academic_year_id" class="text-sm text-destructive">
                  {{ form.errors.academic_year_id }}
                </p>
              </div>

              <!-- Exam Type -->
              <div class="space-y-2">
                <Label for="exam_type_id">Exam Type *</Label>
                <Select v-model="form.exam_type_id">
                  <SelectTrigger :class="{ 'border-destructive': form.errors.exam_type_id }">
                    <SelectValue placeholder="Select exam type" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem
                      v-for="examType in filteredExamTypes"
                      :key="examType.id"
                      :value="examType.id.toString()"
                    >
                      {{ examType.name }}
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p v-if="form.errors.exam_type_id" class="text-sm text-destructive">
                  {{ form.errors.exam_type_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 }}
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p v-if="form.errors.classroom_id" class="text-sm text-destructive">
                  {{ form.errors.classroom_id }}
                </p>
              </div>

              <!-- Student -->
              <div class="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 filteredStudents"
                      :key="student.id"
                      :value="student.id.toString()"
                    >
                      {{ student.first_name }} {{ student.last_name }} ({{ student.student_id }})
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p v-if="form.errors.student_id" class="text-sm text-destructive">
                  {{ form.errors.student_id }}
                </p>
              </div>
            </div>

            <!-- Subject Results Section -->
            <div class="space-y-4">
              <div class="flex items-center justify-between">
                <div>
                  <Label class="text-lg font-semibold">Subject Results</Label>
                  <p class="text-sm text-muted-foreground">Enter marks for each subject (0-100)</p>
                </div>
                <Button type="button" variant="outline" size="sm" @click="addSubject">
                  <Plus class="w-4 h-4 mr-2" />
                  Add Subject
                </Button>
              </div>

              <div v-if="form.subjects.length === 0" class="text-center py-12 border-2 border-dashed border-gray-200 rounded-lg">
                <BookOpen class="w-12 h-12 mx-auto mb-4 text-gray-300" />
                <p class="text-gray-500">No subjects added yet</p>
                <p class="text-sm text-gray-400">Click "Add Subject" to start entering results</p>
              </div>

              <div v-else class="space-y-4">
                <div
                  v-for="(subjectResult, index) in form.subjects"
                  :key="index"
                  class="border rounded-lg p-4 bg-gray-50"
                >
                  <div class="flex items-center justify-between mb-4">
                    <h4 class="font-medium text-gray-900">Subject {{ index + 1 }}</h4>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      @click="removeSubject(index)"
                      class="text-red-600 hover:text-red-700 hover:bg-red-50"
                    >
                      <Trash2 class="w-4 h-4" />
                    </Button>
                  </div>

                  <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <!-- Subject Selection -->
                    <div class="space-y-2">
                      <Label>Subject *</Label>
                      <Select v-model="subjectResult.subject_id">
                        <SelectTrigger :class="{ 'border-destructive': form.errors[`subjects.${index}.subject_id`] }">
                          <SelectValue placeholder="Select subject" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem
                            v-for="subject in availableSubjects(index)"
                            :key="subject.id"
                            :value="subject.id.toString()"
                          >
                            {{ subject.name }}
                          </SelectItem>
                        </SelectContent>
                      </Select>
                      <p v-if="form.errors[`subjects.${index}.subject_id`]" class="text-sm text-destructive">
                        {{ form.errors[`subjects.${index}.subject_id`] }}
                      </p>
                    </div>

                    <!-- Marks Input -->
                    <div class="space-y-2">
                      <Label>Marks *</Label>
                      <Input
                        v-model="subjectResult.marks"
                        type="number"
                        min="0"
                        max="100"
                        placeholder="0-100"
                        :class="{ 'border-destructive': form.errors[`subjects.${index}.marks`] }"
                        @input="updateCalculations(index)"
                      />
                      <p v-if="form.errors[`subjects.${index}.marks`]" class="text-sm text-destructive">
                        {{ form.errors[`subjects.${index}.marks`] }}
                      </p>
                    </div>

                    <!-- Auto-calculated Grade -->
                    <div class="space-y-2">
                      <Label>Grade</Label>
                      <div class="flex items-center h-10">
                        <Badge
                          v-if="subjectResult.marks !== ''"
                          :variant="getGradeVariant(subjectResult.grade)"
                          class="text-sm"
                        >
                          {{ subjectResult.grade }}
                        </Badge>
                        <span v-else class="text-sm text-gray-400">Auto-calculated</span>
                      </div>
                    </div>

                    <!-- Auto-calculated Points -->
                    <div class="space-y-2">
                      <Label>Points</Label>
                      <div class="flex items-center h-10">
                        <span v-if="subjectResult.marks !== ''" class="text-sm font-medium">
                          {{ subjectResult.points }} points
                        </span>
                        <span v-else class="text-sm text-gray-400">Auto-calculated</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Submit Section -->
            <div class="flex items-center justify-between pt-6 border-t">
              <div class="text-sm text-gray-600">
                <span v-if="form.subjects.length > 0">
                  {{ form.subjects.length }} subject(s) added
                </span>
              </div>
              <div class="flex space-x-3">
                <Button type="button" variant="outline" as-child>
                  <Link :href="route('results.index')">Cancel</Link>
                </Button>
                <Button
                  type="submit"
                  :disabled="form.processing || form.subjects.length === 0"
                  class="min-w-[120px]"
                >
                  <span v-if="form.processing">Creating...</span>
                  <span v-else>Create Results</span>
                </Button>
              </div>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { Link, useForm, router } 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 { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { ArrowLeft, Plus, Trash2, BookOpen } from 'lucide-vue-next'

const props = defineProps<{
  academicYears: any[]
  examTypes: any[]
  classrooms: any[]
  subjects: any[]
  students: any[]
}>()

const form = useForm({
  academic_year_id: '',
  exam_type_id: '',
  classroom_id: '',
  student_id: '',
  subjects: [] as Array<{
    subject_id: string
    marks: string
    grade: string
    points: number
  }>
})

// Computed properties for filtering
const filteredExamTypes = computed(() => {
  if (!form.academic_year_id) return []
  return props.examTypes.filter(et => et.academic_year_id.toString() === form.academic_year_id)
})

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

const filteredStudents = computed(() => {
  if (!form.classroom_id) return []
  return props.students.filter(s =>
    s.enrollments?.some(e => e.classroom_id.toString() === form.classroom_id)
  )
})

// Methods
const onAcademicYearChange = () => {
  form.exam_type_id = ''
  form.classroom_id = ''
  form.student_id = ''
}

const onClassroomChange = () => {
  form.student_id = ''
}

const addSubject = () => {
  form.subjects.push({
    subject_id: '',
    marks: '',
    grade: '',
    points: 0
  })
}

const removeSubject = (index: number) => {
  form.subjects.splice(index, 1)
}

const availableSubjects = (currentIndex: number) => {
  const usedSubjectIds = form.subjects
    .map((s, index) => index !== currentIndex ? s.subject_id : null)
    .filter(id => id !== null)

  return props.subjects.filter(subject =>
    !usedSubjectIds.includes(subject.id.toString())
  )
}

const calculateGrade = (marks: string | number): string => {
  const marksNum = Number(marks)
  if (marksNum >= 81) return 'A'
  if (marksNum >= 61) return 'B'
  if (marksNum >= 41) return 'C'
  if (marksNum >= 21) return 'D'
  return 'F'
}

const calculatePoints = (marks: string | number): number => {
  const marksNum = Number(marks)
  if (marksNum >= 81) return 1
  if (marksNum >= 61) return 2
  if (marksNum >= 41) return 3
  if (marksNum >= 21) return 4
  return 5
}

const updateCalculations = (index: number) => {
  const subject = form.subjects[index]
  if (subject.marks !== '') {
    subject.grade = calculateGrade(subject.marks)
    subject.points = calculatePoints(subject.marks)
  }
}

const getGradeVariant = (grade: string) => {
  if (grade === 'A') return 'default'
  if (grade === 'B') return 'secondary'
  if (grade === 'C') return 'outline'
  return 'destructive'
}

const submit = () => {
  // Transform data for submission
  const resultsData = form.subjects.map(subject => ({
    academic_year_id: form.academic_year_id,
    exam_type_id: form.exam_type_id,
    classroom_id: form.classroom_id,
    student_id: form.student_id,
    subject_id: subject.subject_id,
    marks: subject.marks,
    grade: subject.grade,
    points: subject.points
  }))

  router.post(route('results.store-multiple'), {
    results: resultsData
  }, {
    onSuccess: () => {
      router.visit(route('results.index'))
    }
  })
}
</script>
