<template>
  <AppLayout title="Edit Student Results">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Edit Student Results</h1>
          <p class="text-muted-foreground">
            Update examination results for {{ student.first_name }} {{ student.last_name }}
          </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>

      <!-- Student Info Card -->
      <Card>
        <CardHeader>
          <CardTitle>Student Information</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
              <Label class="text-sm font-medium text-gray-600">Student</Label>
              <p class="text-lg font-semibold">{{ student.first_name }} {{ student.last_name }}</p>
              <p class="text-sm text-gray-500">ID: {{ student.student_id }}</p>
            </div>
            <div>
              <Label class="text-sm font-medium text-gray-600">Academic Year</Label>
              <p class="text-lg">{{ academicYear.name }}</p>
            </div>
            <div>
              <Label class="text-sm font-medium text-gray-600">Exam Type</Label>
              <p class="text-lg">{{ examType.name }}</p>
            </div>
            <div>
              <Label class="text-sm font-medium text-gray-600">Classroom</Label>
              <p class="text-lg">{{ getStudentClassroom() }}</p>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Results Form -->
      <Card>
        <CardHeader>
          <CardTitle>Subject Results</CardTitle>
          <CardDescription>
            Update marks for each subject (0-100). Grades and points will be calculated automatically.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form @submit.prevent="submit" class="space-y-6">
            <div v-if="form.results.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 results found</p>
              <p class="text-sm text-gray-400">This student has no results for this exam type</p>
            </div>

            <div v-else class="space-y-4">
              <div
                v-for="(result, index) in form.results"
                :key="index"
                class="border rounded-lg p-4 bg-gray-50"
              >
                <div class="grid grid-cols-1 md:grid-cols-5 gap-4 items-end">
                  <!-- Subject Name (Read-only) -->
                  <div class="space-y-2">
                    <Label>Subject</Label>
                    <div class="flex items-center h-10 px-3 py-2 border border-gray-200 bg-gray-100 rounded-md">
                      <span class="text-sm font-medium">{{ result.subject_name }}</span>
                    </div>
                  </div>

                  <!-- Marks Input -->
                  <div class="space-y-2">
                    <Label>Marks *</Label>
                    <Input
                      v-model="result.marks"
                      type="number"
                      min="0"
                      max="100"
                      placeholder="0-100"
                      :class="{ 'border-destructive': form.errors[`results.${index}.marks`] }"
                      @input="updateCalculations(index)"
                    />
                    <p v-if="form.errors[`results.${index}.marks`]" class="text-sm text-destructive">
                      {{ form.errors[`results.${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="result.marks !== ''"
                        :variant="getGradeVariant(result.grade)"
                        class="text-sm"
                      >
                        {{ result.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="result.marks !== ''" class="text-sm font-medium">
                        {{ result.points }} points
                      </span>
                      <span v-else class="text-sm text-gray-400">Auto-calculated</span>
                    </div>
                  </div>

                  <!-- Original vs Current -->
                  <div class="space-y-2">
                    <Label>Status</Label>
                    <div class="flex items-center h-10">
                      <Badge
                        :variant="hasChanged(index) ? 'default' : 'secondary'"
                        class="text-xs"
                      >
                        {{ hasChanged(index) ? 'Modified' : 'Unchanged' }}
                      </Badge>
                    </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.results.length > 0">
                  {{ form.results.length }} subject(s) • {{ getModifiedCount() }} modified
                </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.results.length === 0 || getModifiedCount() === 0"
                  class="min-w-[120px]"
                >
                  <span v-if="form.processing">Updating...</span>
                  <span v-else>Update Results</span>
                </Button>
              </div>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { computed, onMounted } 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 { ArrowLeft, BookOpen } from 'lucide-vue-next'

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

const form = useForm({
  student_id: props.student.id,
  academic_year_id: props.academicYear.id,
  exam_type_id: props.examType.id,
  classroom_id: '',
  results: [] as Array<{
    id?: number
    subject_id: number
    subject_name: string
    marks: string
    grade: string
    points: number
    original_marks: string
  }>
})

// Initialize form data
onMounted(() => {
  // Set classroom ID
  const enrollment = props.student.enrollments?.find(e =>
    e.academic_year_id === props.academicYear.id
  )
  if (enrollment) {
    form.classroom_id = enrollment.classroom_id
  }

  // Initialize results from existing data
  form.results = props.existingResults.map(result => ({
    id: result.id,
    subject_id: result.subject_id,
    subject_name: result.subject.name,
    marks: result.marks.toString(),
    grade: result.grade,
    points: result.points,
    original_marks: result.marks.toString()
  }))
})

// Methods
const getStudentClassroom = () => {
  const enrollment = props.student.enrollments?.find(e =>
    e.academic_year_id === props.academicYear.id
  )
  return enrollment?.classroom?.name || 'N/A'
}

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 result = form.results[index]
  if (result.marks !== '') {
    result.grade = calculateGrade(result.marks)
    result.points = calculatePoints(result.marks)
  }
}

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

const hasChanged = (index: number): boolean => {
  const result = form.results[index]
  return result.marks !== result.original_marks
}

const getModifiedCount = (): number => {
  return form.results.filter((_, index) => hasChanged(index)).length
}

const submit = () => {
  const data = {
    student_id: form.student_id,
    academic_year_id: form.academic_year_id,
    exam_type_id: form.exam_type_id,
    classroom_id: form.classroom_id,
    results: form.results.map(result => ({
      id: result.id,
      subject_id: result.subject_id,
      marks: result.marks,
      grade: result.grade,
      points: result.points
    }))
  }

  router.put('/results/update-multiple', data, {
    onSuccess: () => {
      router.visit(route('results.index'))
    },
    onError: (errors) => {
      console.error('Update failed:', errors)
    }
  })
}
</script>
