<template>
  <AppLayout title="Edit Classroom">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Edit Classroom</h1>
          <p class="text-muted-foreground">
            Update classroom information and subject assignments
          </p>
        </div>
      </div>

      <!-- Form Card -->
      <Card>
        <CardHeader>
          <CardTitle>Classroom Information</CardTitle>
          <CardDescription>
            Update the classroom details and subject assignments
          </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">
                  <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="name">Classroom Name *</Label>
                <Input
                  id="name"
                  v-model="form.name"
                  type="text"
                  placeholder="e.g., Form 1A"
                  :class="{ 'border-destructive': form.errors.name }"
                />
                <p v-if="form.errors.name" class="text-sm text-destructive">
                  {{ form.errors.name }}
                </p>
              </div>

              <div class="space-y-2">
                <Label for="capacity">Capacity</Label>
                <Input
                  id="capacity"
                  v-model="form.capacity"
                  type="number"
                  min="1"
                  max="100"
                  placeholder="e.g., 30"
                  :class="{ 'border-destructive': form.errors.capacity }"
                />
                <p v-if="form.errors.capacity" class="text-sm text-destructive">
                  {{ form.errors.capacity }}
                </p>
                <p class="text-sm text-muted-foreground">
                  Maximum number of students in this classroom
                </p>
              </div>

              <div class="space-y-2 md:col-span-2">
                <Label for="description">Description</Label>
                <Textarea
                  id="description"
                  v-model="form.description"
                  placeholder="Enter classroom description (optional)"
                  rows="3"
                  :class="{ 'border-destructive': form.errors.description }"
                />
                <p v-if="form.errors.description" class="text-sm text-destructive">
                  {{ form.errors.description }}
                </p>
              </div>

              <!-- Subject Assignment -->
              <div class="space-y-2 md:col-span-2">
                <Label>Subject Assignments *</Label>
                <div class="grid grid-cols-2 md:grid-cols-3 gap-2 max-h-40 overflow-y-auto border rounded-md p-3">
                  <div v-for="subject in subjects" :key="subject.id" class="flex items-center space-x-2">
                    <Checkbox
                      :id="`subject-${subject.id}`"
                      :checked="form.subject_ids.includes(subject.id)"
                      @update:checked="toggleSubject(subject.id, $event)"
                    />
                    <Label :for="`subject-${subject.id}`" class="text-sm">
                      {{ subject.name }} ({{ subject.code }})
                    </Label>
                  </div>
                </div>
                <p v-if="form.errors.subject_ids" class="text-sm text-destructive">
                  {{ form.errors.subject_ids }}
                </p>
                <p class="text-sm text-muted-foreground">
                  Select subjects taught in this classroom
                </p>
              </div>
            </div>

            <!-- Classroom Preview -->
            <div v-if="form.name && form.academic_year_id" class="mt-6 p-4 bg-muted rounded-lg">
              <h3 class="font-medium mb-2">Classroom Preview</h3>
              <div class="space-y-1 text-sm">
                <p><strong>Name:</strong> {{ form.name }}</p>
                <p><strong>Academic Year:</strong> {{ getSelectedAcademicYearName() }}</p>
                <p v-if="form.capacity"><strong>Capacity:</strong> {{ form.capacity }} students</p>
                <p><strong>Subjects:</strong> {{ form.subject_ids.length }} selected</p>
                <p v-if="form.description"><strong>Description:</strong> {{ form.description }}</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('classrooms.index')">
                  Cancel
                </Link>
              </Button>
              <Button type="submit" :disabled="form.processing">
                <span v-if="form.processing">Updating...</span>
                <span v-else>Update Classroom</span>
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  </AppLayout>
</template>

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

interface Classroom {
  id: number
  academic_year_id: number
  name: string
  capacity?: number
  description?: string
  subjects?: Array<{ id: number }>
}

interface AcademicYear {
  id: number
  name: string
}

interface Subject {
  id: number
  name: string
  code: string
}

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

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

const form = useForm({
  academic_year_id: props.classroom.academic_year_id.toString(),
  name: props.classroom.name,
  capacity: props.classroom.capacity || '',
  description: props.classroom.description || '',
  subject_ids: props.classroom.subjects?.map(s => s.id) || [],
})

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

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

const submit = () => {
  form.put(route('classrooms.update', props.classroom.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>
