<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 route = useRoute()
const config = useRuntimeConfig()

const { data: user, status } = useFetch<any>(`${config.public.apiBase}/users/${route.params.id}`)

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
}

watch(user, (val) => {
  if (val) {
    form.value = {
      email: val.email ?? '',
      username: val.username ?? '',
      full_name: val.profile?.full_name ?? '',
      phone: val.profile?.phone ?? '',
      address: val.profile?.address ?? '',
      pob: val.profile?.pob ?? '',
    }
    if (val.profile?.dob) {
      const [y, m, d] = val.profile.dob.split('-').map(Number)
      dob.value = new CalendarDate(y, m, d)
    }
  }
})

async function handleSubmit() {
  if (!validate()) {
    toast.error('Harap lengkapi form yang wajib diisi')
    return
  }

  loading.value = true
  try {
    const body: Record<string, any> = {
      email: form.value.email.trim(),
      username: form.value.username.trim(),
      full_name: form.value.full_name.trim(),
    }
    if (form.value.phone.trim()) body.phone = form.value.phone.replace(/\s/g, '')
    if (form.value.address.trim()) body.address = form.value.address.trim()
    if (form.value.pob.trim()) body.pob = form.value.pob.trim()
    if (dob.value) body.dob = dob.value.toString()

    await $fetch(`${config.public.apiBase}/users/${route.params.id}`, {
      method: 'PUT',
      body,
    })
    toast.success('Pengguna berhasil diperbarui')
    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 v-if="status === 'pending'" class="flex items-center justify-center py-12">
                <Loader2 class="h-6 w-6 animate-spin text-muted-foreground" />
              </div>
              <template v-else-if="user">
                <div class="flex items-center justify-between">
                  <h1 class="text-2xl font-bold">Edit Pengguna</h1>
                  <Button variant="outline" size="sm" @click="router.push('/admin/users')">
                    <ArrowLeft class="h-4 w-4 mr-1" />
                    Kembali
                  </Button>
                </div>
              </template>
            </div>
            <div v-if="user" class="px-4 lg:px-6">
              <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>
