<template>
  <AppLayout title="Division Rules">
    <div class="space-y-6">
      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight">Division Rules</h1>
          <p class="text-muted-foreground">
            Manage division rules based on total points 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 Division 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 division 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>

      <!-- Division Rules Table -->
      <Card>
        <CardHeader>
          <CardTitle>Division Rules ({{ divisionRules.total }})</CardTitle>
        </CardHeader>
        <CardContent>
          <div class="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Division</TableHead>
                  <TableHead>Points Range</TableHead>
                  <TableHead>Academic Year</TableHead>
                  <TableHead class="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                <TableRow v-for="rule in divisionRules.data" :key="rule.id">
                  <TableCell>
                    <Badge :variant="getDivisionVariant(rule.division)" class="font-medium">
                      {{ rule.division }}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <span class="font-mono">{{ rule.min_points }} - {{ rule.max_points }} pts</span>
                  </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="divisionRules.data.length === 0" class="text-center py-8 text-muted-foreground">
              No division rules found. Create your first division rule to get started.
            </div>
          </div>

          <!-- Pagination -->
          <div v-if="divisionRules.last_page > 1" class="flex items-center justify-between mt-4">
            <div class="text-sm text-muted-foreground">
              Showing {{ divisionRules.from }} to {{ divisionRules.to }} of {{ divisionRules.total }} results
            </div>
            <div class="flex gap-2">
              <Button 
                variant="outline" 
                size="sm" 
                :disabled="!divisionRules.prev_page_url"
                @click="router.get(divisionRules.prev_page_url)"
              >
                Previous
              </Button>
              <Button 
                variant="outline" 
                size="sm" 
                :disabled="!divisionRules.next_page_url"
                @click="router.get(divisionRules.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' }} Division Rule</DialogTitle>
            <DialogDescription>
              {{ editingRule ? 'Update the' : 'Add a new' }} division 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="space-y-2">
              <Label for="division">Division Name *</Label>
              <Input
                id="division"
                v-model="form.division"
                placeholder="e.g., First Class, Second Class, Third Class"
                :class="{ 'border-destructive': form.errors.division }"
              />
              <p v-if="form.errors.division" class="text-sm text-destructive">
                {{ form.errors.division }}
              </p>
              <p class="text-sm text-muted-foreground">
                Only letters and spaces allowed
              </p>
            </div>

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

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

            <div class="space-y-2">
              <Label for="description">Description (Optional)</Label>
              <Textarea
                id="description"
                v-model="form.description"
                placeholder="Additional description for this division..."
                rows="3"
                :class="{ 'border-destructive': form.errors.description }"
              />
              <p v-if="form.errors.description" class="text-sm text-destructive">
                {{ form.errors.description }}
              </p>
            </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 { Textarea } from '@/components/ui/textarea'
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 {
  divisionRules: {
    data: Array<{
      id: number
      division: string
      min_points: number
      max_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: '',
  division: '',
  min_points: '',
  max_points: '',
  description: ''
})

const search = () => {
  router.get(route('configuration.division-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.division = rule.division
  form.min_points = rule.min_points.toString()
  form.max_points = rule.max_points.toString()
  form.description = rule.description || ''
  showCreateDialog.value = true
}

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

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

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

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

const getDivisionVariant = (division: string) => {
  const lowerDiv = division.toLowerCase()
  if (lowerDiv.includes('first') || lowerDiv.includes('distinction')) return 'default'
  if (lowerDiv.includes('second')) return 'secondary'
  if (lowerDiv.includes('third')) return 'outline'
  if (lowerDiv.includes('fail')) return 'destructive'
  return 'outline'
}
</script>
