<script setup lang="ts">
const { t } = useI18n()
const localePath = useLocalePath()
const toast = useToast()
const { setConfig, getAllConfigs } = useSiteConfig()

definePageMeta({
  middleware: 'super-admin'
})

// Form state
const loading = ref(true)
const saving = ref(false)
const sidebarCollapsibleState = useState<boolean>('dashboard:sidebar:collapse', () => false)
const toasterPositionState = useState<string>('ui:toaster:position', () => 'bottom-center')

// Computed properties for v-model bindings
const sidebarCollapsible = computed({
  get: () => sidebarCollapsibleState.value,
  set: (value: boolean) => { sidebarCollapsibleState.value = value }
})

const toasterPosition = computed({
  get: () => toasterPositionState.value,
  set: (value: string) => { toasterPositionState.value = value }
})

// Load current configuration
const loadConfig = async () => {
  loading.value = true
  try {
    const configs = await getAllConfigs()
    const config = configs.find((c: { key: string, value: string }) => c.key === 'dashboard.sidebar.collapsible')
    if (config) {
      sidebarCollapsibleState.value = config.value === 'true' || config.value === '1'
    }
    const toaster = configs.find((c: { key: string, value: string }) => c.key === 'ui.toaster.position')
    if (toaster && toaster.value) {
      toasterPositionState.value = toaster.value as string
    }
  } catch {
    toast.add({
      title: t('admin.siteConfigurationPage.messages.loadError'),
      color: 'error'
    })
  } finally {
    loading.value = false
  }
}

// Save configuration
const saveConfig = async () => {
  saving.value = true
  try {
    await setConfig(
      'dashboard.sidebar.collapsible',
      sidebarCollapsibleState.value ? 'true' : 'false',
      t('admin.siteConfigurationPage.settings.dashboardSidebarCollapsible.description')
    )

    await setConfig(
      'ui.toaster.position',
      toasterPositionState.value,
      t('admin.siteConfigurationPage.settings.toasterPosition.description')
    )

    toast.add({
      title: t('admin.siteConfigurationPage.messages.saveSuccess'),
      color: 'success'
    })
    window.location.reload()
  } catch {
    toast.add({
      title: t('admin.siteConfigurationPage.messages.saveError'),
      color: 'error'
    })
  } finally {
    saving.value = false
  }
}

const sendTestToast = () => {
  toast.add({
    title: 'Test toast position: ' + toasterPositionState.value,
    description: 'Don\'t forget to save the configuration to apply the new position.',
    color: 'success'
  })
}

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

<template>
  <NuxtLayout
    :page-title="t('admin.siteConfiguration')"
    :parent="{
      label: t('admin.title'),
      to: localePath('/dashboard/admin')
    }"
    name="dashboard"
    type="admin"
  >
    <UPageBody>
      <PageMainCard
        :title="t('admin.siteConfigurationPage.title')"
        :description="t('admin.siteConfigurationPage.description')"
        :icon="useSolarIcon('settings')"
        :loading="loading"
        :on-refresh="loadConfig"
      >
        <div
          v-if="loading"
          class="flex justify-center py-8"
        >
          <UIcon
            name="lucide:loader-circle"
            class="animate-spin size-8"
          />
        </div>

        <div
          v-else
          class="space-y-6"
        >
          <!-- Dashboard Sidebar Collapsible Setting -->
          <div class="flex items-start justify-between gap-4">
            <div class="flex-1">
              <label class="text-sm font-medium text-highlighted">
                {{ t('admin.siteConfigurationPage.settings.dashboardSidebarCollapsible.label') }}
              </label>
              <p class="text-sm text-muted mt-1">
                {{ t('admin.siteConfigurationPage.settings.dashboardSidebarCollapsible.description') }}
              </p>
            </div>
            <USwitch v-model="sidebarCollapsible" />
          </div>

          <!-- Toaster Position Setting -->
          <div class="flex items-start justify-between gap-4">
            <div class="flex-1">
              <label class="text-sm font-medium text-highlighted">
                {{ t('admin.siteConfigurationPage.settings.toasterPosition.label') }}
              </label>
              <p class="text-sm text-muted mt-1">
                {{ t('admin.siteConfigurationPage.settings.toasterPosition.description') }}
              </p>
            </div>
            <USelect
              v-model="toasterPosition"
              :items="['top-left', 'top-center', 'top-right', 'bottom-left', 'bottom-center', 'bottom-right']"
              @change="sendTestToast"
            />
          </div>
        </div>
        <template #footer-actions>
          <UButton
            :label="t('common.save')"
            :loading="saving"
            @click="saveConfig"
          />
        </template>
      </PageMainCard>
    </UPageBody>
    <NotificationsSlideover />
  </NuxtLayout>
</template>
