<template>
  <UDashboardPanel id="settings">
    <template #header>
      <UDashboardNavbar :title="$t('settings.title')">
        <template #leading>
          <UDashboardSidebarCollapse />
        </template>
      </UDashboardNavbar>
    </template>

    <template #body>
      <div class="flex flex-col gap-6 w-full lg:max-w-4xl mx-auto p-6">
        <!-- Language Section -->
        <UCard>
          <template #header>
            <div>
              <h3 class="text-lg font-semibold text-highlighted">{{ $t('settings.language.title') }}</h3>
              <p class="text-sm text-muted mt-1">{{ $t('settings.language.description') }}</p>
            </div>
          </template>
          <ULocaleSelect
            :model-value="locale"
            :locales="[de, en]"
            class="w-full max-w-xs"
            size="md"
            @update:model-value="handleLocaleChange"
          />
        </UCard>

        <!-- Appearance Section -->
        <UCard>
          <template #header>
            <div>
              <h3 class="text-lg font-semibold text-highlighted">{{ $t('settings.appearance.title') }}</h3>
              <p class="text-sm text-muted mt-1">{{ $t('settings.appearance.description') }}</p>
            </div>
          </template>
          <URadioGroup v-model="selectedColorMode" :items="colorModeOptions" class="gap-4" />
        </UCard>

        <!-- Theme Colors Section -->
        <UCard>
          <template #header>
            <div>
              <h3 class="text-lg font-semibold text-highlighted">{{ $t('settings.theme.title') }}</h3>
              <p class="text-sm text-muted mt-1">{{ $t('settings.theme.description') }}</p>
            </div>
          </template>

          <div class="space-y-6">
            <!-- Primary Color -->
            <div>
              <h4 class="text-sm font-medium text-highlighted mb-3">{{ $t('settings.theme.primary') }}</h4>
              <div class="grid grid-cols-10 gap-2">
                <button
                  v-for="color in colors"
                  :key="color"
                  type="button"
                  :class="[
                    'w-10 h-10 rounded-md transition-all',
                    appConfig.ui.colors.primary === color
                      ? 'ring-2 ring-offset-2 ring-offset-background'
                      : 'hover:scale-110'
                  ]"
                  :style="{
                    backgroundColor: `var(--color-${color}-500)`,
                    '--tw-ring-color': `var(--color-${color}-500)`
                  }"
                  @click="appConfig.ui.colors.primary = color"
                />
              </div>
            </div>
          </div>
        </UCard>

        <!-- Email Notifications Section -->
        <UCard>
          <template #header>
            <div>
              <h3 class="text-lg font-semibold text-highlighted">{{ $t('settings.email.title') }}</h3>
              <p class="text-sm text-muted mt-1">{{ $t('settings.email.description') }}</p>
            </div>
          </template>

          <div class="space-y-4">
            <UInput
              v-model="emailAddress"
              :label="$t('settings.email.emailAddress')"
              type="email"
              placeholder="user@example.com"
              class="w-full max-w-md"
            />

            <div class="space-y-3">
              <UCheckbox v-model="emailOnFormCreated" :label="$t('settings.email.onFormCreated')" />
              <UCheckbox v-model="emailOnFormSubmitted" :label="$t('settings.email.onFormSubmitted')" />
              <UCheckbox v-model="emailOnFormUpdated" :label="$t('settings.email.onFormUpdated')" />
              <UCheckbox v-model="emailOnCommentAdded" :label="$t('settings.email.onCommentAdded')" />
            </div>

            <UButton :label="$t('common.save')" color="primary" :loading="isSaving" @click="saveEmailPreferences" />
          </div>
        </UCard>
      </div>
    </template>
  </UDashboardPanel>
</template>

<script setup lang="ts">
import { de, en } from '@nuxt/ui/locale'
import { useUserStore } from '~~/stores/useUserStore'
import { useUser } from '~/composables'

definePageMeta({
  layout: 'default'
})

const { t: $t, locale, setLocale } = useI18n()
const colorMode = useColorMode()
const appConfig = useAppConfig()
const toast = useToast()
const userStore = useUserStore()
const { getUserById, updateEmailPreferences } = useUser()
const logger = useLogger().withTag('settings')

const colors = [
  'red',
  'orange',
  'amber',
  'yellow',
  'lime',
  'green',
  'emerald',
  'teal',
  'cyan',
  'sky',
  'blue',
  'indigo',
  'violet',
  'purple',
  'fuchsia',
  'pink'
]

const emailAddress = ref('')
const emailOnFormCreated = ref(true)
const emailOnFormSubmitted = ref(true)
const emailOnFormUpdated = ref(true)
const emailOnCommentAdded = ref(true)
const isSaving = ref(false)

onMounted(async () => {
  if (userStore.user) {
    try {
      const userData = await getUserById(userStore.user.keycloakId)
      emailAddress.value = userData.email || ''
      emailOnFormCreated.value = userData.emailOnFormCreated ?? true
      emailOnFormSubmitted.value = userData.emailOnFormSubmitted ?? true
      emailOnFormUpdated.value = userData.emailOnFormUpdated ?? true
      emailOnCommentAdded.value = userData.emailOnCommentAdded ?? true
    } catch (error) {
      logger.error('Failed to load user email preferences:', error)
    }
  }
})

async function saveEmailPreferences() {
  if (!userStore.user) return

  isSaving.value = true
  try {
    await updateEmailPreferences(
      userStore.user.keycloakId,
      emailAddress.value || null,
      emailOnFormCreated.value,
      emailOnFormSubmitted.value,
      emailOnFormUpdated.value,
      emailOnCommentAdded.value
    )

    toast.add({
      title: $t('settings.email.saved'),
      color: 'success'
    })
  } catch {
    toast.add({
      title: $t('common.error'),
      color: 'error'
    })
  } finally {
    isSaving.value = false
  }
}

function handleLocaleChange(newLocale: string | undefined) {
  if (newLocale) {
    setLocale(newLocale as 'de' | 'en')
  }
}

const colorModeOptions = computed(() => [
  {
    value: 'light',
    label: $t('settings.appearance.light'),
    icon: 'i-lucide-sun'
  },
  {
    value: 'dark',
    label: $t('settings.appearance.dark'),
    icon: 'i-lucide-moon'
  }
])

const selectedColorMode = computed({
  get: () => colorMode.value,
  set: (value) => {
    colorMode.preference = value as 'light' | 'dark'
  }
})
</script>
