<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { AlertRoot, AlertTitle, AlertDescription } from '@/components/ui/alert'
import { Box } from '@/components/ui/box'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
  SelectRoot,
  SelectControl,
  SelectTrigger,
  SelectValueText,
  SelectContent,
  SelectItemGroup,
  SelectItemGroupLabel,
  SelectItem,
  SelectItemText,
} from '@/components/ui/select'
import { Field, FieldLabel } from '@/components/ui/field'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import RolePermissionsPicker from '../components/RolePermissionsPicker.vue'
import { useRoleSelectFields } from '../composables/useRoleSelectFields'
import { createRole, listPermissions } from '../services/role.service'
import type { RolePermission } from '../types/role.types'

const router = useRouter()

const loading = ref(false)
const saving = ref(false)
const error = ref<string | null>(null)
const successMessage = ref<string | null>(null)

const name = ref('')
const fullname = ref('')
const permissions = ref<RolePermission[]>([])
const selectedPermissionIds = ref<Set<string>>(new Set())

const {
  guardCollection,
  contextCollection,
  guardInitial,
  contextInitial,
  setGuardValue,
  setContextValue,
  getGuardName,
  getContext,
} = useRoleSelectFields()

const selectedCount = computed(() => selectedPermissionIds.value.size)

function setPermissionChecked(permissionId: string, checked: boolean) {
  const next = new Set(selectedPermissionIds.value)
  if (checked) next.add(permissionId)
  else next.delete(permissionId)
  selectedPermissionIds.value = next
}

async function fetchPermissions() {
  loading.value = true
  error.value = null

  try {
    const response = await listPermissions()
    permissions.value = response.data
  } catch (err) {
    error.value = getApiErrorMessage(err, 'Gagal memuatkan senarai permissions.')
  } finally {
    loading.value = false
  }
}

async function handleSubmit() {
  saving.value = true
  error.value = null
  successMessage.value = null

  try {
    await createRole({
      name: name.value.trim(),
      fullname: fullname.value.trim(),
      guard_name: getGuardName(),
      context: getContext(),
      permissions: Array.from(selectedPermissionIds.value),
    })

    successMessage.value = 'Peranan berjaya didaftarkan.'
    setTimeout(() => {
      router.push({ name: 'list-roles' })
    }, 300)
  } catch (err) {
    error.value = getApiErrorMessage(err, 'Gagal mendaftarkan peranan.')
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  fetchPermissions()
})
</script>

<template>
  <div class="w-full space-y-6">
    <div class="flex flex-wrap items-center gap-3">
      <h2 class="mr-auto text-lg font-medium">Daftar Peranan</h2>
      <Button look="outline" variant="secondary" type="button" :disabled="saving"
        @click="router.push({ name: 'list-roles' })">
        Kembali
      </Button>
    </div>

    <AlertRoot v-if="error" variant="danger">
      <AlertTitle>Ralat</AlertTitle>
      <AlertDescription>{{ error }}</AlertDescription>
    </AlertRoot>

    <AlertRoot v-if="successMessage" variant="success">
      <AlertTitle>Berjaya</AlertTitle>
      <AlertDescription>{{ successMessage }}</AlertDescription>
    </AlertRoot>

    <Box>
      <form class="space-y-4" @submit.prevent="handleSubmit">
        <Field>
          <FieldLabel for="role-name">Nama Peranan</FieldLabel>
          <Input id="role-name" v-model="name" class="w-full" type="text" placeholder="Contoh: ADMIN"
            :disabled="loading || saving" required />
        </Field>

        <Field>
          <FieldLabel for="role-fullname">Nama Penuh Peranan</FieldLabel>
          <Input id="role-fullname" v-model="fullname" class="w-full" type="text" placeholder="Contoh: Pentadbir Sistem"
            :disabled="loading || saving" required />
        </Field>

        <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
          <Field>
            <FieldLabel>Guard</FieldLabel>
            <SelectRoot class="w-full" :collection="guardCollection" :default-value="guardInitial" disabled
              @value-change="setGuardValue">
              <SelectControl>
                <SelectTrigger>
                  <SelectValueText placeholder="Pilih guard" />
                </SelectTrigger>
              </SelectControl>
              <SelectContent>
                <SelectItemGroup>
                  <SelectItemGroupLabel>Guard</SelectItemGroupLabel>
                  <SelectItem v-for="item in guardCollection.items" :key="item.label" :item="item">
                    <SelectItemText>{{ item.label }}</SelectItemText>
                  </SelectItem>
                </SelectItemGroup>
              </SelectContent>
            </SelectRoot>
          </Field>

          <Field>
            <FieldLabel>Konteks</FieldLabel>
            <SelectRoot class="w-full" :collection="contextCollection" :default-value="contextInitial"
              :disabled="loading || saving" @value-change="setContextValue">
              <SelectControl>
                <SelectTrigger>
                  <SelectValueText placeholder="Pilih konteks" />
                </SelectTrigger>
              </SelectControl>
              <SelectContent>
                <SelectItemGroup>
                  <SelectItemGroupLabel>Konteks</SelectItemGroupLabel>
                  <SelectItem v-for="item in contextCollection.items" :key="item.label" :item="item">
                    <SelectItemText>{{ item.label }}</SelectItemText>
                  </SelectItem>
                </SelectItemGroup>
              </SelectContent>
            </SelectRoot>
          </Field>
        </div>

        <div class="space-y-2">
          <div class="flex items-center justify-between gap-3">
            <div class="font-medium">Permissions</div>
            <div class="text-sm opacity-70">{{ selectedCount }} dipilih</div>
          </div>

          <RolePermissionsPicker :permissions="permissions" :selected-permission-ids="selectedPermissionIds"
            :loading="loading" :disabled="saving" @checked-change="setPermissionChecked" />
        </div>

        <div class="flex items-center justify-end gap-2 pt-2">
          <Button type="submit" variant="primary" look="outline" :disabled="loading || saving">
            {{ saving ? 'Mendaftar...' : 'Daftar' }}
          </Button>
        </div>
      </form>
    </Box>
  </div>
</template>
