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

      <!-- Form Card -->
      <Card>
        <CardHeader>
          <CardTitle>Result Information</CardTitle>
          <CardDescription>
            Update the student's result for the selected subject and exam type
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form @submit.prevent="submit" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <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>

              <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>

              <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.user?.first_name }} {{ student.user?.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 class="space-y-2">
                <Label for="subject_id">Subject *</Label>
                <Select v-model="form.subject_id">
                  <SelectTrigger :class="{ 'border-destructive': form.errors.subject_id }">
                    <SelectValue placeholder="Select subject" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem 
                      v-for="subject in filteredSubjects" 
                      :key="subject.id" 
                      :value="subject.id.toString()"
                    >
                      {{ subject.name }} ({{ subject.code }})
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p v-if="form.errors.subject_id" class="text-sm text-destructive">
                  {{ form.errors.subject_id }}
                </p>
              </div>

              <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 }} ({{ examType.weight }}%)
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p v-if="form.errors.exam_type_id" class="text-sm text-destructive">
                  {{ form.errors.exam_type_id }}
                </p>
              </div>

              <div class="space-y-2">
                <Label for="marks">Marks *</Label>
                <Input
                  id="marks"
                  v-model="form.marks"
                  type="number"
                  min="0"
                  max="100"
                  step="0.01"
                  placeholder="e.g., 85"
                  :class="{ 'border-destructive': form.errors.marks }"
                  @input="calculateGradeAndPoints"
                />
                <p v-if="form.errors.marks" class="text-sm text-destructive">
                  {{ form.errors.marks }}
                </p>
                <p class="text-sm text-muted-foreground">
                  Enter marks out of 100
                </p>
              </div>

              <div class="space-y-2">
                <Label for="grade">Grade</Label>
                <Input
                  id="grade"
                  v-model="form.grade"
                  type="text"
                  readonly
                  :class="{ 'border-destructive': form.errors.grade }"
                />
                <p v-if="form.errors.grade" class="text-sm text-destructive">
                  {{ form.errors.grade }}
                </p>
                <p class="text-sm text-muted-foreground">
                  Auto-calculated based on marks
                </p>
              </div>

              <div class="space-y-2">
                <Label for="points">Points</Label>
                <Input
                  id="points"
                  v-model="form.points"
                  type="number"
                  readonly
                  :class="{ 'border-destructive': form.errors.points }"
                />
                <p v-if="form.errors.points" class="text-sm text-destructive">
                  {{ form.errors.points }}
                </p>
                <p class="text-sm text-muted-foreground">
                  Auto-calculated based on marks
                </p>
              </div>
            </div>

            <!-- Result Preview -->
            <div v-if="form.student_id && form.subject_id && form.marks" class="mt-6 p-4 bg-muted rounded-lg">
              <h3 class="font-medium mb-2">Result Preview</h3>
              <div class="space-y-1 text-sm">
                <p><strong>Student:</strong> {{ getSelectedStudentName() }}</p>
                <p><strong>Subject:</strong> {{ getSelectedSubjectName() }}</p>
                <p><strong>Exam Type:</strong> {{ getSelectedExamTypeName() }}</p>
                <p><strong>Marks:</strong> {{ form.marks }}/100</p>
                <p><strong>Grade:</strong> {{ form.grade }}</p>
                <p><strong>Points:</strong> {{ form.points }}</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('results.index')">
                  Cancel
                </Link>
              </Button>
              <Button type="submit" :disabled="form.processing">
                <span v-if="form.processing">Updating...</span>
                <span v-else>Update Result</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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'

interface Result {
  id: number
  student_id: number
  subject_id: number
  classroom_id: number
  academic_year_id: number
  exam_type_id: number
  marks: number
  grade: string
  points: number
}

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

const form = useForm({
  academic_year_id: props.result.academic_year_id.toString(),
  classroom_id: props.result.classroom_id.toString(),
  student_id: props.result.student_id.toString(),
  subject_id: props.result.subject_id.toString(),
  exam_type_id: props.result.exam_type_id.toString(),
  marks: props.result.marks.toString(),
  grade: props.result.grade,
  points: props.result.points.toString(),
})

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: any) => e.classroom_id.toString() === form.classroom_id)
  )
})

const filteredSubjects = computed(() => {
  if (!form.classroom_id) return []
  const classroom = props.classrooms.find(c => c.id.toString() === form.classroom_id)
  return classroom?.subjects || []
})

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

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

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

const calculateGradeAndPoints = () => {
  const marks = parseFloat(form.marks)
  if (isNaN(marks)) return

  if (marks >= 90) { form.grade = 'A+'; form.points = '12' }
  else if (marks >= 80) { form.grade = 'A'; form.points = '11' }
  else if (marks >= 75) { form.grade = 'A-'; form.points = '10' }
  else if (marks >= 70) { form.grade = 'B+'; form.points = '9' }
  else if (marks >= 65) { form.grade = 'B'; form.points = '8' }
  else if (marks >= 60) { form.grade = 'B-'; form.points = '7' }
  else if (marks >= 55) { form.grade = 'C+'; form.points = '6' }
  else if (marks >= 50) { form.grade = 'C'; form.points = '5' }
  else if (marks >= 45) { form.grade = 'C-'; form.points = '4' }
  else if (marks >= 40) { form.grade = 'D+'; form.points = '3' }
  else if (marks >= 35) { form.grade = 'D'; form.points = '2' }
  else if (marks >= 30) { form.grade = 'D-'; form.points = '1' }
  else { form.grade = 'F'; form.points = '0' }
}

const getSelectedStudentName = () => {
  const student = props.students.find(s => s.id.toString() === form.student_id)
  return student ? `${student.user?.first_name} ${student.user?.last_name}` : ''
}

const getSelectedSubjectName = () => {
  const subject = props.subjects.find(s => s.id.toString() === form.subject_id)
  return subject?.name || ''
}

const getSelectedExamTypeName = () => {
  const examType = props.examTypes.find(et => et.id.toString() === form.exam_type_id)
  return examType?.name || ''
}

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