<script setup lang="ts">
import AppSidebar from '@/components/AppSidebar.vue'
import SiteHeader from '@/components/SiteHeader.vue'
import {
  Alert,
  AlertDescription,
  AlertTitle,
} from '@/components/ui/alert'
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar'
import { CalendarDate } from '@internationalized/date'
import { AlertCircleIcon, ArrowLeft, CalendarIcon, Loader2 } from '@lucide/vue'
import { reactive, ref } from 'vue'
import { toast } from 'vue-sonner'

import { Button } from '@/components/ui/button'
import { Calendar } from '@/components/ui/calendar'
import {
  Card,
  CardContent,
} from '@/components/ui/card'
import {
  Field,
  FieldGroup,
  FieldLabel,
} from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { PhoneInput } from '@/components/ui/phone-input'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover'
import { cn } from '@/lib/utils'

const router = useRouter()
const config = useRuntimeConfig()

const form = ref({
  email: '',
  username: '',
  full_name: '',
  phone: '',
  address: '',
  pob: '',
})
const dob = ref<CalendarDate>()

const errors = reactive<Record<string, string>>({})
const loading = ref(false)

function validate() {
  Object.keys(errors).forEach(k => delete errors[k])
  if (!form.value.email.trim()) errors.email = 'Email wajib diisi'
  if (!form.value.username.trim()) errors.username = 'Username wajib diisi'
  if (!form.value.full_name.trim()) errors.full_name = 'Nama lengkap wajib diisi'
  return Object.keys(errors).length === 0
}

async function handleSubmit() {
  if (!validate()) {
    toast.error('Silakan cek kembali data yang Anda masukkan')
    return
  }

  loading.value = true
  try {
    await $fetch(`${config.public.apiBase}/users`, {
      method: 'POST',
      body: {
        email: form.value.email.trim(),
        username: form.value.username.trim(),
        password: 'Minimal8@',
        full_name: form.value.full_name.trim(),
        phone: form.value.phone.replace(/\s/g, '') || null,
        address: form.value.address.trim() || null,
        pob: form.value.pob.trim() || null,
        dob: dob.value?.toString() || null,
      },
    })
    toast.success('Pengguna berhasil ditambahkan')
    router.push('/admin/users')
  } catch (e: any) {
    const detail = e?.data?.detail
    if (Array.isArray(detail)) {
      for (const err of detail) {
        const field = err.loc?.at(-1)
        if (field && ['email', 'username', 'full_name', 'phone', 'address', 'pob', 'dob'].includes(field)) {
          errors[field] = err.msg
        }
      }
      if (Object.keys(errors).length) toast.error('Silakan cek kembali data yang Anda masukkan')
    } else {
      const msg = detail?.message ?? e?.data?.message ?? ''
      if (msg.toLowerCase().includes('email')) errors.email = msg
      if (msg.toLowerCase().includes('username')) errors.username = msg
      if (!errors.email && !errors.username) toast.error(msg || 'Gagal menyimpan pengguna')
    }
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <SidebarProvider :style="{
    '--sidebar-width': 'calc(var(--spacing) * 72)',
    '--header-height': 'calc(var(--spacing) * 12)',
  }">
    <AppSidebar variant="inset" />
    <SidebarInset>
      <SiteHeader />
      <div class="flex flex-1 flex-col">
        <div class="@container/main flex flex-1 flex-col gap-2">
          <div class="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
            <div class="px-4 lg:px-6">
              <div class="flex items-center justify-between">
                <h1 class="text-2xl font-bold">Tambah Pengguna</h1>
                <Button variant="outline" size="sm" @click="router.push('/admin/users')">
                  <ArrowLeft class="h-4 w-4 mr-1" />
                  Kembali
                </Button>
              </div>
            </div>
            <div class="px-4 lg:px-6">
              <div class="pb-3">
                <Alert>
                  <AlertCircleIcon />
                  <AlertTitle>Informasi</AlertTitle>
                  <AlertDescription>
                    <p>Kata sandi bawaan adalah <b>Minimal8@</b></p>
                  </AlertDescription>
                </Alert>
              </div>
              <form @submit.prevent="handleSubmit">
                <Card>
                  <CardContent>
                    <FieldGroup class="gap-4">
                      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <Field>
                          <FieldLabel for="form-email">Email <span class="text-red-500">*</span></FieldLabel>
                          <Input id="form-email" v-model="form.email" placeholder="Masukkan email" :disabled="loading"
                            :class="{ 'border-red-500': errors.email }" />
                          <p v-if="errors.email" class="text-sm text-red-500">{{ errors.email }}</p>
                        </Field>
                        <Field>
                          <FieldLabel for="form-username">Username <span class="text-red-500">*</span></FieldLabel>
                          <Input id="form-username" v-model="form.username" placeholder="Masukkan username"
                            :disabled="loading" :class="{ 'border-red-500': errors.username }" />
                          <p v-if="errors.username" class="text-sm text-red-500">{{ errors.username }}</p>
                        </Field>
                      </div>
                      <Field>
                        <FieldLabel for="form-full-name">Nama Lengkap <span class="text-red-500">*</span></FieldLabel>
                        <Input id="form-full-name" v-model="form.full_name" placeholder="Masukkan nama lengkap"
                          :disabled="loading" :class="{ 'border-red-500': errors.full_name }" />
                        <p v-if="errors.full_name" class="text-sm text-red-500">{{ errors.full_name }}</p>
                      </Field>
                      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <Field>
                          <FieldLabel for="form-phone">No. Telepon</FieldLabel>
                          <PhoneInput id="form-phone" v-model="form.phone" :disabled="loading"
                            :class="{ 'border-red-500': errors.phone }" />
                        </Field>
                        <Field>
                          <FieldLabel for="form-pob">Tempat Lahir</FieldLabel>
                          <Input id="form-pob" v-model="form.pob" placeholder="Masukkan tempat lahir"
                            :disabled="loading" />
                        </Field>
                        <Field>
                          <FieldLabel for="form-dob">Tanggal Lahir</FieldLabel>
                          <Popover>
                            <PopoverTrigger as-child>
                              <Button id="form-dob" variant="outline" :disabled="loading" :class="cn(
                                'w-full justify-start text-left font-normal',
                                !dob && 'text-muted-foreground',
                              )">
                                <CalendarIcon class="mr-2 h-4 w-4" />
                                {{ dob ? dob.toDate('UTC').toLocaleDateString('id-ID', {
                                  day: 'numeric', month: 'long',
                                  year: 'numeric'
                                }) : 'Pilih tanggal' }}
                              </Button>
                            </PopoverTrigger>
                            <PopoverContent class="w-auto p-0">
                              <Calendar v-model="dob" :initial-focus="true" layout="month-and-year" />
                            </PopoverContent>
                          </Popover>
                        </Field>
                      </div>
                      <Field>
                        <FieldLabel for="form-address">Alamat</FieldLabel>
                        <textarea id="form-address" v-model="form.address" placeholder="Masukkan alamat"
                          :disabled="loading" rows="2"
                          class="flex w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-3 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50" />
                      </Field>
                    </FieldGroup>
                  </CardContent>
                </Card>
                <div class="flex items-center justify-end gap-2 mt-4">
                  <Button type="button" variant="outline" :disabled="loading"
                    @click="router.push('/admin/users')">Batal</Button>
                  <Button type="submit" :disabled="loading">
                    <Loader2 v-if="loading" class="h-4 w-4 mr-1 animate-spin" />
                    Simpan
                  </Button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </SidebarInset>
  </SidebarProvider>
</template>
