<template>
  <AppLayout title="Create Classroom">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Create Classroom</h1>
          <p class="text-muted-foreground">
            Add a new classroom to the system
          </p>
        </div>
      </div>

      <!-- Form Card -->
      <Card>
        <CardHeader>
          <CardTitle>Classroom Information</CardTitle>
          <CardDescription>
            Enter the details for the new classroom
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form @submit.prevent="submit" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <!-- Classroom Name -->
              <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, Grade 10"
                  :class="{ 'border-destructive': form.errors.name }"
                />
                <p v-if="form.errors.name" class="text-sm text-destructive">
                  {{ form.errors.name }}
                </p>
              </div>

              <!-- Academic Year -->
              <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 }} ({{ academicYear.start_date }} - {{ academicYear.end_date }})
                    </SelectItem>
                  </SelectContent>
                </Select>
                <p v-if="form.errors.academic_year_id" class="text-sm text-destructive">
                  {{ form.errors.academic_year_id }}
                </p>
              </div>

              <!-- Capacity -->
              <div class="space-y-2">
                <Label for="capacity">Capacity *</Label>
                <Input
                  id="capacity"
                  v-model="form.capacity"
                  type="number"
                  min="1"
                  max="200"
                  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 (1-200)
                </p>
              </div>

              <!-- Subjects -->
              <div class="space-y-2">
                <Label for="subject_ids">Subjects (Optional)</Label>
                <div class="space-y-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}`"
                      :value="subject.id"
                      v-model:checked="selectedSubjects"
                      @update:checked="updateSubjectSelection(subject.id, $event)"
                    />
                    <Label :for="`subject-${subject.id}`" class="text-sm font-normal">
                      {{ subject.name }} ({{ subject.code }})
                    </Label>
                  </div>
                  <p v-if="subjects.length === 0" class="text-sm text-muted-foreground">
                    No active subjects available
                  </p>
                </div>
                <p v-if="form.errors.subject_ids" class="text-sm text-destructive">
                  {{ form.errors.subject_ids }}
                </p>
              </div>

              <!-- Description -->
              <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>
            </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">Creating...</span>
                <span v-else>Create Classroom</span>
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { useForm, Link, usePage } from '@inertiajs/vue3'
import { ref, watch, onMounted } from 'vue'
import { useToast } from '@/composables/useToast'
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'

const props = defineProps({
  academicYears: {
    type: Array,
    default: () => []
  },
  subjects: {
    type: Array,
    default: () => []
  }
})

const selectedSubjects = ref([])
const page = usePage()
const toast = useToast()

const form = useForm({
  name: '',
  academic_year_id: '',
  capacity: '',
  description: '',
  subject_ids: []
})

const updateSubjectSelection = (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 submit = () => {
  form.post(route('classrooms.store'), {
    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>
