<template>
  <AppLayout title="Grading Rules">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Grading Rules</h1>
          <p class="text-muted-foreground">
            Manage grading rules for different academic years
          </p>
        </div>
        <div class="flex gap-2">
          <Button variant="outline" @click="createDefaultRules">
            <Settings class="w-4 h-4 mr-2" />
            Create Default Rules
          </Button>
          <Button @click="showCreateDialog = true">
            <Plus class="w-4 h-4 mr-2" />
            Add Grading Rule
          </Button>
        </div>
      </div>

      <!-- Filters -->
      <Card>
        <CardContent class="pt-6">
          <div class="flex flex-col sm:flex-row gap-4">
            <div class="flex-1">
              <Input
                v-model="filters.search"
                placeholder="Search grading rules..."
                @input="debouncedSearch"
                class="max-w-sm"
              />
            </div>
            <div class="flex gap-2">
              <Select v-model="filters.academic_year_id" @update:model-value="search">
                <SelectTrigger class="w-48">
                  <SelectValue placeholder="All Academic Years" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Academic Years</SelectItem>
                  <SelectItem 
                    v-for="academicYear in academicYears" 
                    :key="academicYear.id" 
                    :value="academicYear.id.toString()"
                  >
                    {{ academicYear.name }}
                  </SelectItem>
                </SelectContent>
              </Select>
              <Button variant="outline" @click="clearFilters">
                Clear Filters
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Grading Rules Table -->
      <Card>
        <CardHeader>
          <CardTitle>Grading Rules ({{ gradingRules.total }})</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Grade</TableHead>
                  <TableHead>Mark Range</TableHead>
                  <TableHead>Points</TableHead>
                  <TableHead>Academic Year</TableHead>
                  <TableHead class="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                <TableRow v-for="rule in gradingRules.data" :key="rule.id">
                  <TableCell>
                    <Badge :variant="getGradeVariant(rule.grade)" class="font-mono">
                      {{ rule.grade }}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <span class="font-mono">{{ rule.min_marks }}% - {{ rule.max_marks }}%</span>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">{{ rule.points }} pts</Badge>
                  </TableCell>
                  <TableCell>
                    <Badge variant="secondary">
                      {{ rule.academic_year?.name || 'N/A' }}
                    </Badge>
                  </TableCell>
                  <TableCell class="text-right">
                    <DropdownMenu>
                      <DropdownMenuTrigger as-child>
                        <Button variant="ghost" class="h-8 w-8 p-0">
                          <MoreHorizontal class="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem @click="editRule(rule)">
                          <Edit class="mr-2 h-4 w-4" />
                          Edit
                        </DropdownMenuItem>
                        <DropdownMenuItem @click="deleteRule(rule.id)" class="text-destructive">
                          <Trash2 class="mr-2 h-4 w-4" />
                          Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              </TableBody>
            </Table>
            
            <div v-if="gradingRules.data.length === 0" class="text-center py-8 text-muted-foreground">
              No grading rules found. Create your first grading rule to get started.
            </div>
          </div>

          <!-- Pagination -->
          <div v-if="gradingRules.last_page > 1" class="flex items-center justify-between mt-4">
            <div class="text-sm text-muted-foreground">
              Showing {{ gradingRules.from }} to {{ gradingRules.to }} of {{ gradingRules.total }} results
            </div>
            <div class="flex gap-2">
              <Button 
                variant="outline" 
                size="sm" 
                :disabled="!gradingRules.prev_page_url"
                @click="router.get(gradingRules.prev_page_url)"
              >
                Previous
              </Button>
              <Button 
                variant="outline" 
                size="sm" 
                :disabled="!gradingRules.next_page_url"
                @click="router.get(gradingRules.next_page_url)"
              >
                Next
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Create/Edit Dialog -->
      <Dialog v-model:open="showCreateDialog">
        <DialogContent class="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>{{ editingRule ? 'Edit' : 'Create' }} Grading Rule</DialogTitle>
            <DialogDescription>
              {{ editingRule ? 'Update the' : 'Add a new' }} grading rule for an academic year.
            </DialogDescription>
          </DialogHeader>
          
          <form @submit.prevent="submitForm" class="space-y-4">
            <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="grid grid-cols-2 gap-4">
              <div class="space-y-2">
                <Label for="grade">Grade *</Label>
                <Input
                  id="grade"
                  v-model="form.grade"
                  placeholder="e.g., A+, B, C-"
                  :class="{ 'border-destructive': form.errors.grade }"
                />
                <p v-if="form.errors.grade" class="text-sm text-destructive">
                  {{ form.errors.grade }}
                </p>
              </div>

              <div class="space-y-2">
                <Label for="points">Points *</Label>
                <Input
                  id="points"
                  v-model="form.points"
                  type="number"
                  min="0"
                  max="10"
                  placeholder="e.g., 8"
                  :class="{ 'border-destructive': form.errors.points }"
                />
                <p v-if="form.errors.points" class="text-sm text-destructive">
                  {{ form.errors.points }}
                </p>
              </div>
            </div>

            <div class="grid grid-cols-2 gap-4">
              <div class="space-y-2">
                <Label for="min_marks">Min Marks *</Label>
                <Input
                  id="min_marks"
                  v-model="form.min_marks"
                  type="number"
                  min="0"
                  max="100"
                  placeholder="e.g., 80"
                  :class="{ 'border-destructive': form.errors.min_marks }"
                />
                <p v-if="form.errors.min_marks" class="text-sm text-destructive">
                  {{ form.errors.min_marks }}
                </p>
              </div>

              <div class="space-y-2">
                <Label for="max_marks">Max Marks *</Label>
                <Input
                  id="max_marks"
                  v-model="form.max_marks"
                  type="number"
                  min="0"
                  max="100"
                  placeholder="e.g., 100"
                  :class="{ 'border-destructive': form.errors.max_marks }"
                />
                <p v-if="form.errors.max_marks" class="text-sm text-destructive">
                  {{ form.errors.max_marks }}
                </p>
              </div>
            </div>

            <DialogFooter>
              <Button type="button" variant="outline" @click="cancelEdit">
                Cancel
              </Button>
              <Button type="submit" :disabled="form.processing">
                <span v-if="form.processing">{{ editingRule ? 'Updating...' : 'Creating...' }}</span>
                <span v-else>{{ editingRule ? 'Update' : 'Create' }} Rule</span>
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  </AppLayout>
</template>

<script setup lang="ts">
import { useForm, router } from '@inertiajs/vue3'
import { reactive, ref } from 'vue'
import { debounce } from 'lodash'
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Plus, Settings, MoreHorizontal, Edit, Trash2 } from 'lucide-vue-next'

interface Props {
  gradingRules: {
    data: Array<{
      id: number
      grade: string
      min_marks: number
      max_marks: number
      points: number
      academic_year?: {
        id: number
        name: string
      }
    }>
    total: number
    from: number
    to: number
    last_page: number
    prev_page_url?: string
    next_page_url?: string
  }
  academicYears: Array<{
    id: number
    name: string
  }>
  filters: {
    search?: string
    academic_year_id?: string
  }
  defaultRules?: Array<any>
}

const props = defineProps<Props>()

const showCreateDialog = ref(false)
const editingRule = ref(null)

const filters = reactive({
  search: props.filters.search || '',
  academic_year_id: props.filters.academic_year_id || 'all'
})

const form = useForm({
  academic_year_id: '',
  grade: '',
  min_marks: '',
  max_marks: '',
  points: ''
})

const search = () => {
  router.get(route('configuration.grading-rules'), {
    search: filters.search || undefined,
    academic_year_id: filters.academic_year_id !== 'all' ? filters.academic_year_id : undefined,
  }, {
    preserveState: true,
    replace: true
  })
}

const debouncedSearch = debounce(search, 300)

const clearFilters = () => {
  filters.search = ''
  filters.academic_year_id = 'all'
  search()
}

const editRule = (rule: any) => {
  editingRule.value = rule
  form.academic_year_id = rule.academic_year?.id?.toString() || ''
  form.grade = rule.grade
  form.min_marks = rule.min_marks.toString()
  form.max_marks = rule.max_marks.toString()
  form.points = rule.points.toString()
  showCreateDialog.value = true
}

const cancelEdit = () => {
  editingRule.value = null
  form.reset()
  showCreateDialog.value = false
}

const submitForm = () => {
  if (editingRule.value) {
    form.put(route('configuration.grading-rules.update', editingRule.value.id), {
      onSuccess: () => {
        cancelEdit()
      }
    })
  } else {
    form.post(route('configuration.grading-rules.store'), {
      onSuccess: () => {
        cancelEdit()
      }
    })
  }
}

const deleteRule = (ruleId: number) => {
  if (confirm('Are you sure you want to delete this grading rule?')) {
    router.delete(route('configuration.grading-rules.destroy', ruleId))
  }
}

const createDefaultRules = () => {
  if (confirm('This will create default grading rules for all active academic years. Continue?')) {
    router.post(route('configuration.create-default-rules'))
  }
}

const getGradeVariant = (grade: string) => {
  if (grade.startsWith('A')) return 'default'
  if (grade.startsWith('B')) return 'secondary'
  if (grade.startsWith('C')) return 'outline'
  if (grade.startsWith('D')) return 'outline'
  return 'destructive'
}
</script>
