<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { RouterLink, useRouter } from 'vue-router'
import phoneIllustration from '@/assets/images/phone-illustration.svg'
import womanIllustration from '@/assets/images/woman-illustration.svg'
import { AlertRoot, AlertTitle, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Box } from '@/components/ui/box'
import { Button } from '@/components/ui/button'
import {
  CarouselRoot,
  CarouselPrevTrigger,
  CarouselNextTrigger,
  CarouselItemGroup,
  CarouselItem,
} from '@/components/ui/carousel'
import { DialogRoot, DialogContent, DialogCloseTrigger } from '@/components/ui/dialog'
import { Lucide, type Icon } from '@/components/ui/lucide'
import { usePermissions } from '@/composables/usePermissions'
import { completeOnboarding } from '@/modules/profile/services/profile.service'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const router = useRouter()
const { hasPermission } = usePermissions()

const onboardingDialog = ref(false)

const appName = import.meta.env.VITE_APP_NAME
const appVersion = import.meta.env.VITE_APP_VERSION

const greeting = computed(() => {
  const hour = new Date().getHours()
  if (hour < 12) return 'Selamat pagi'
  if (hour < 18) return 'Selamat petang'
  return 'Selamat malam'
})

const availableModules = computed(() => [
  {
    title: 'Profil',
    description: 'Kemas kini maklumat peribadi, pekerjaan, bank dan waris.',
    route: 'profile-overview-2',
    icon: 'User' as Icon,
    visible: true,
  },
  {
    title: 'Permohonan Keahlian',
    description: 'Urus dan semak permohonan keahlian KOPKB.',
    route: 'list-membership-applications',
    icon: 'ClipboardList' as Icon,
    visible: hasPermission('lihat permohonan keahlian'),
  },
  {
    title: 'Aktiviti',
    description: 'Lihat dan urus aktiviti serta laporan berkaitan.',
    route: 'list-activities',
    icon: 'CalendarDays' as Icon,
    visible: hasPermission('lihat aktiviti'),
  },
  {
    title: 'Senarai Pengguna',
    description: 'Pantau dan urus akaun pengguna sistem.',
    route: 'list-users',
    icon: 'Users' as Icon,
    visible: hasPermission('lihat pengguna'),
  },
].filter((module) => module.visible))

const upcomingFeatures = [
  'Ringkasan statistik keahlian',
  'Carta dan laporan bulanan',
  'Notifikasi dan aktiviti terkini',
  'Papan pemuka pentadbir',
]

onMounted(() => {
  onboardingDialog.value = !authStore.user?.onboarding_completed_at
})

async function markOnboardingComplete() {
  if (authStore.user?.onboarding_completed_at) {
    return
  }

  try {
    const res = await completeOnboarding()
    if (res.success) {
      authStore.setUserProfile(res.data)
    }
  } catch {
    // Will retry on next visit if the request failed
  }
}

async function finishOnboarding() {
  onboardingDialog.value = false
  await markOnboardingComplete()
  await router.push({ name: 'profile-overview-2' })
}

function handleOnboardingOpenChange(details: { open: boolean }) {
  onboardingDialog.value = details.open

  if (!details.open) {
    void markOnboardingComplete()
  }
}
</script>

<template>
  <div>
    <AlertRoot class="mb-6" look="outline" variant="primary">
      <Lucide class="mr-2 size-4 shrink-0" icon="Construction" />
      <AlertTitle>Sistem Dalam Pembangunan</AlertTitle>
      <AlertDescription>
        {{ appName }} {{ appVersion }} masih dalam fasa pembangunan. Beberapa fungsi papan pemuka
        belum tersedia. Sila gunakan modul sedia ada melalui menu sisi atau pautan di bawah.
      </AlertDescription>
    </AlertRoot>

    <div class="grid grid-cols-12 gap-6">
      <div class="col-span-12">
        <Box class="relative overflow-hidden p-6 sm:p-8">
          <div class="pointer-events-none absolute -right-10 -top-10 size-40 rounded-full bg-primary/10 blur-2xl" />
          <div class="relative">
            <Badge variant="pending" class="mb-4">Beta</Badge>
            <h2 class="text-2xl font-semibold">
              {{ greeting }}{{ authStore.userName ? `, ${authStore.userName}` : '' }}
            </h2>
            <p class="mt-2 max-w-2xl text-base leading-relaxed opacity-70">
              Selamat datang ke {{ appName }}. Papan pemuka utama sedang dibangunkan — buat masa ini,
              anda boleh mula dengan mengemas kini profil atau mengurus permohonan keahlian.
            </p>
          </div>
        </Box>
      </div>

      <div class="col-span-12 lg:col-span-7">
        <div class="mb-4 flex h-10 items-center">
          <h3 class="text-lg font-medium">Modul Tersedia</h3>
        </div>

        <div class="grid gap-4 sm:grid-cols-2">
          <Box v-for="module in availableModules" :key="module.route"
            class="flex h-full flex-col p-5 transition-colors hover:bg-foreground/2">
            <div class="mb-4 flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary">
              <Lucide :icon="module.icon" class="size-5" />
            </div>
            <div class="text-base font-medium">{{ module.title }}</div>
            <p class="mt-2 flex-1 text-sm leading-relaxed opacity-70">
              {{ module.description }}
            </p>
            <Button as-child variant="ghost" class="mt-5 w-full border border-foreground/15">
              <RouterLink :to="{ name: module.route }">
                Pergi ke {{ module.title }}
                <Lucide icon="ArrowRight" class="size-4" />
              </RouterLink>
            </Button>
          </Box>
        </div>
      </div>

      <div class="col-span-12 lg:col-span-5">
        <div class="mb-4 flex h-10 items-center">
          <h3 class="text-lg font-medium">Akan Datang</h3>
        </div>

        <Box class="p-5">
          <p class="text-sm leading-relaxed opacity-70">
            Ciri-ciri berikut sedang dirancang untuk papan pemuka ini:
          </p>
          <ul class="mt-4 space-y-3">
            <li v-for="feature in upcomingFeatures" :key="feature" class="flex items-start gap-3 text-sm">
              <Lucide icon="CircleDashed" class="mt-0.5 size-4 shrink-0 text-primary/70" />
              <span>{{ feature }}</span>
            </li>
          </ul>
        </Box>

        <Box class="mt-4 p-5">
          <div class="flex items-start gap-3">
            <Lucide icon="Lightbulb" class="mt-0.5 size-4 shrink-0 text-warning" />
            <div>
              <div class="text-sm font-medium">Petua</div>
              <p class="mt-1 text-sm leading-relaxed opacity-70">
                Pastikan profil anda lengkap dan terkini. Maklumat yang
                tepat membantu proses kelulusan berjalan lebih lancar.
              </p>
            </div>
          </div>
        </Box>
      </div>
    </div>

    <!-- BEGIN: Onboarding Dialog -->
    <DialogRoot :open="onboardingDialog" @openChange="handleOnboardingOpenChange">
      <DialogContent class="sm:max-w-xl">
        <DialogCloseTrigger />
        <div class="overflow-hidden">
          <div class="-my-5 -mx-10">
            <CarouselRoot :default-page="0" :slide-count="2" class="border-0">
              <CarouselItemGroup>
                <CarouselItem class="border-transparent bg-none bg-transparent" :index="0">
                  <div class="relative mx-3 flex flex-col items-center gap-1 px-3.5 pb-20">
                    <div
                      class="w-full bg-primary/5 mb-7 border-primary/10 shadow-lg shadow-black/10 relative rounded-3xl border h-52 overflow-hidden before:bg-noise before:absolute before:inset-0 before:opacity-30 after:bg-accent after:absolute after:inset-0 after:opacity-30 after:blur-2xl">
                      <img class="absolute inset-0 mx-auto mt-10 w-2/5 scale-125" :src="phoneIllustration"
                        alt="MyKOPKB" />
                    </div>
                    <div class="px-8">
                      <div class="text-center text-xl font-medium">Selamat Datang ke Sistem MyKOPKB</div>
                      <div class="mt-3 text-center text-base leading-relaxed opacity-70">
                        Sistem MyKOPKB adalah sistem integrasi bagi ahli Koperasi Permodalan Kelantan Berhad (KOPKB).
                      </div>
                    </div>
                    <div class="absolute inset-x-0 bottom-0 flex justify-end px-5">
                      <CarouselNextTrigger class="text-primary flex items-center gap-3 font-medium me-0 px-5">
                        Seterusnya
                        <Lucide icon="MoveRight" />
                      </CarouselNextTrigger>
                    </div>
                  </div>
                </CarouselItem>
                <CarouselItem class="border-transparent bg-none bg-transparent" :index="1">
                  <div class="relative mx-3 flex flex-col items-center gap-1 px-3.5 pb-20">
                    <div
                      class="w-full bg-primary/5 mb-7 border-primary/10 shadow-lg shadow-black/10 relative rounded-3xl border h-52 overflow-hidden before:bg-noise before:absolute before:inset-0 before:opacity-30 after:bg-accent after:absolute after:inset-0 after:opacity-30 after:blur-2xl">
                      <img class="absolute inset-0 mx-auto mt-10 w-2/5 scale-125" :src="womanIllustration"
                        alt="MyKOPKB" />
                    </div>
                    <div class="px-8">
                      <div class="text-center text-xl font-medium">Mulakan dengan Profil Anda</div>
                      <div class="mt-3 text-center text-base leading-relaxed opacity-70">
                        Lengkapkan maklumat peribadi, pekerjaan dan butiran bank.
                      </div>
                    </div>
                    <div class="absolute inset-x-0 bottom-0 flex place-content-between px-5">
                      <CarouselPrevTrigger class="text-primary flex items-center gap-3 font-medium ms-0 px-5">
                        <Lucide icon="MoveLeft" /> Kembali
                      </CarouselPrevTrigger>
                      <a class="inline-flex items-center gap-2 rounded-lg bg-primary px-6 py-3 font-semibold text-white shadow-md transition-all duration-200 hover:bg-primary/90 hover:shadow-lg active:scale-95 cursor-pointer"
                        @click.prevent="finishOnboarding">
                        <span>Selesai</span>
                        <Lucide icon="Check" class="h-5 w-5" />
                      </a>
                    </div>
                  </div>
                </CarouselItem>
              </CarouselItemGroup>
            </CarouselRoot>
          </div>
        </div>
      </DialogContent>
    </DialogRoot>
    <!-- END: Onboarding Dialog -->
  </div>
</template>
