<template>
  <AppLayout title="Edit Enrollment">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Edit Enrollment</h1>
          <p class="text-muted-foreground">
            Update enrollment information for {{ enrollment.student?.user?.name }}
          </p>
        </div>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Main Form -->
        <div class="lg:col-span-2">
          <Card>
            <CardHeader>
              <CardTitle>Enrollment Information</CardTitle>
              <CardDescription>
                Update the enrollment details below
              </CardDescription>
            </CardHeader>
            <CardContent>
              <form @submit.prevent="submit" class="space-y-6">
                <!-- Student Information (Read-only) -->
                <div class="space-y-2">
                  <Label>Student</Label>
                  <div class="p-3 bg-muted rounded-lg">
                    <p class="font-medium">
                      {{ enrollment.student?.user?.name }}
                    </p>
                    <p class="text-sm text-muted-foreground">ID: {{ enrollment.student?.student_id }}</p>
                  </div>
                </div>

                <!-- Academic Year -->
                <div class="space-y-2">
                  <Label for="academic_year_id">Academic Year *</Label>
                  <Select v-model="form.academic_year_id" required>
                    <SelectTrigger>
                      <SelectValue placeholder="Select academic year" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem v-for="year in academicYears" :key="year.id" :value="year.id.toString()">
                        {{ year.name }}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                  <div v-if="form.errors.academic_year_id" class="text-sm text-destructive">
                    {{ form.errors.academic_year_id }}
                  </div>
                </div>

                <!-- Classroom -->
                <div class="space-y-2">
                  <Label for="classroom_id">Classroom *</Label>
                  <Select v-model="form.classroom_id" required>
                    <SelectTrigger>
                      <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">
                          (Capacity: {{ classroom.capacity }})
                        </span>
                      </SelectItem>
                    </SelectContent>
                  </Select>
                  <div v-if="form.errors.classroom_id" class="text-sm text-destructive">
                    {{ form.errors.classroom_id }}
                  </div>
                </div>

                <!-- Enrolled Date -->
                <div class="space-y-2">
                  <Label for="enrolled_at">Enrolled Date *</Label>
                  <Input
                    id="enrolled_at"
                    v-model="form.enrolled_at"
                    type="date"
                    required
                  />
                  <div v-if="form.errors.enrolled_at" class="text-sm text-destructive">
                    {{ form.errors.enrolled_at }}
                  </div>
                </div>

                <!-- Status -->
                <div class="flex items-center space-x-2">
                  <Checkbox
                    id="is_active"
                    v-model:checked="form.is_active"
                  />
                  <Label for="is_active">Active Enrollment</Label>
                </div>
                <div v-if="form.errors.is_active" class="text-sm text-destructive">
                  {{ form.errors.is_active }}
                </div>

                <!-- Form Actions -->
                <div class="flex items-center justify-between pt-6">
                  <Button variant="outline" type="button" as-child>
                    <Link :href="route('enrollment.show', enrollment.id)">
                      Cancel
                    </Link>
                  </Button>
                  <Button type="submit" :disabled="form.processing">
                    <span v-if="form.processing">Updating...</span>
                    <span v-else>Update Enrollment</span>
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </div>

        <!-- Sidebar -->
        <div class="space-y-6">
          <!-- Current Enrollment Info -->
          <Card>
            <CardHeader>
              <CardTitle>Current Information</CardTitle>
            </CardHeader>
            <CardContent class="space-y-3">
              <div>
                <Label class="text-sm font-medium text-muted-foreground">Current Classroom</Label>
                <p class="font-medium">{{ enrollment.classroom?.name }}</p>
              </div>
              <div>
                <Label class="text-sm font-medium text-muted-foreground">Current Academic Year</Label>
                <p class="font-medium">{{ enrollment.academic_year?.name }}</p>
              </div>
              <div>
                <Label class="text-sm font-medium text-muted-foreground">Current Status</Label>
                <Badge :variant="enrollment.is_active ? 'default' : 'secondary'">
                  {{ enrollment.is_active ? 'Active' : 'Inactive' }}
                </Badge>
              </div>
              <div>
                <Label class="text-sm font-medium text-muted-foreground">Enrolled Since</Label>
                <p class="font-medium">{{ formatDate(enrollment.enrolled_at) }}</p>
              </div>
            </CardContent>
          </Card>

          <!-- Student Quick Info -->
          <Card>
            <CardHeader>
              <CardTitle>Student Information</CardTitle>
            </CardHeader>
            <CardContent class="space-y-3">
              <div>
                <Label class="text-sm font-medium text-muted-foreground">Name</Label>
                <p class="font-medium">
                  {{ enrollment.student?.user?.name }}
                </p>
              </div>
              <div>
                <Label class="text-sm font-medium text-muted-foreground">Student ID</Label>
                <p class="font-medium">{{ enrollment.student?.student_id }}</p>
              </div>
              <div v-if="enrollment.student?.user?.email">
                <Label class="text-sm font-medium text-muted-foreground">Email</Label>
                <p class="font-medium">{{ enrollment.student.user.email }}</p>
              </div>
            </CardContent>
          </Card>

          <!-- Actions -->
          <Card>
            <CardHeader>
              <CardTitle>Quick Actions</CardTitle>
            </CardHeader>
            <CardContent class="space-y-2">
              <Button variant="outline" size="sm" class="w-full" as-child>
                <Link :href="route('enrollment.show', enrollment.id)">
                  View Details
                </Link>
              </Button>
              <Button variant="outline" size="sm" class="w-full" as-child>
                <Link :href="route('enrollment.index')">
                  Back to Enrollments
                </Link>
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { useForm, Link, usePage } from '@inertiajs/vue3'
import { useToast } from '@/composables/useToast'
import { computed, onMounted } 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 { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'

interface Enrollment {
  id: number
  classroom_id: number
  academic_year_id: number
  enrolled_at: string
  is_active: boolean
  student?: {
    id: number
    student_id: string
    user?: {
      first_name: string
      last_name: string
      email?: string
    }
  }
  classroom?: {
    id: number
    name: string
    capacity?: number
  }
  academic_year?: {
    id: number
    name: 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<{
  enrollment: Enrollment
  academicYears: AcademicYear[]
  classrooms: Classroom[]
}>()

const page = usePage()
const toast = useToast()

const form = useForm({
  classroom_id: props.enrollment.classroom_id.toString(),
  academic_year_id: props.enrollment.academic_year_id.toString(),
  enrolled_at: props.enrollment.enrolled_at.split('T')[0], // Format for date input
  is_active: props.enrollment.is_active,
})

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

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const submit = () => {
  form.put(route('enrollment.update', props.enrollment.id), {
    onError: (errors) => {
      // Show toast for validation errors
      const firstError = Object.values(errors)[0]
      const errorMessage = Array.isArray(firstError) ? firstError[0] : firstError
      toast.error(errorMessage || 'Please check the form for errors.')
    }
  })
}

// Show success toast if redirected with success message
onMounted(() => {
  if (page.props.success) {
    toast.success(page.props.success)
  }
})
</script>
