<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { required, email, helpers } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core'
import { useCompanyStore } from '../../../../stores/company.store'

const companyStore = useCompanyStore()
const { t } = useI18n()

const isSaving = ref<boolean>(false)

const settingsForm = reactive<{
  notify_invoice_viewed: string
  notify_estimate_viewed: string
  notification_email: string
}>({
  notify_invoice_viewed:
    companyStore.selectedCompanySettings.notify_invoice_viewed ?? 'NO',
  notify_estimate_viewed:
    companyStore.selectedCompanySettings.notify_estimate_viewed ?? 'NO',
  notification_email:
    companyStore.selectedCompanySettings.notification_email ?? '',
})

const rules = computed(() => ({
  notification_email: {
    required: helpers.withMessage(t('validation.required'), required),
    email: helpers.withMessage(t('validation.email_incorrect'), email),
  },
}))

const v$ = useVuelidate(
  rules,
  computed(() => settingsForm)
)

const invoiceViewedField = computed<boolean>({
  get: () => settingsForm.notify_invoice_viewed === 'YES',
  set: async (newValue: boolean) => {
    const value = newValue ? 'YES' : 'NO'
    settingsForm.notify_invoice_viewed = value

    await companyStore.updateCompanySettings({
      data: { settings: { notify_invoice_viewed: value } },
      message: 'general.setting_updated',
    })
  },
})

const estimateViewedField = computed<boolean>({
  get: () => settingsForm.notify_estimate_viewed === 'YES',
  set: async (newValue: boolean) => {
    const value = newValue ? 'YES' : 'NO'
    settingsForm.notify_estimate_viewed = value

    await companyStore.updateCompanySettings({
      data: { settings: { notify_estimate_viewed: value } },
      message: 'general.setting_updated',
    })
  },
})

async function submitForm(): Promise<void> {
  v$.value.$touch()
  if (v$.value.$invalid) return

  isSaving.value = true

  await companyStore.updateCompanySettings({
    data: {
      settings: {
        notification_email: settingsForm.notification_email,
      },
    },
    message: 'settings.notification.email_save_message',
  })

  isSaving.value = false
}
</script>

<template>
  <BaseSettingCard
    :title="$t('settings.notification.title')"
    :description="$t('settings.notification.description')"
  >
    <form action="" @submit.prevent="submitForm">
      <div class="grid-cols-2 col-span-1 mt-14">
        <BaseInputGroup
          :error="
            v$.notification_email.$error &&
            v$.notification_email.$errors[0]?.$message
          "
          :label="$t('settings.notification.email')"
          class="my-2"
          required
        >
          <BaseInput
            v-model.trim="settingsForm.notification_email"
            :invalid="v$.notification_email.$error"
            type="email"
            @input="v$.notification_email.$touch()"
          />
        </BaseInputGroup>

        <BaseButton
          :disabled="isSaving"
          :loading="isSaving"
          variant="primary"
          type="submit"
          class="mt-6"
        >
          <template #left="slotProps">
            <BaseIcon
              v-if="!isSaving"
              :class="slotProps.class"
              name="ArrowDownOnSquareIcon"
            />
          </template>
          {{ $t('settings.notification.save') }}
        </BaseButton>
      </div>
    </form>

    <BaseDivider class="mt-6 mb-2" />

    <ul class="divide-y divide-line-default">
      <BaseSwitchSection
        v-model="invoiceViewedField"
        :title="$t('settings.notification.invoice_viewed')"
        :description="$t('settings.notification.invoice_viewed_desc')"
      />

      <BaseSwitchSection
        v-model="estimateViewedField"
        :title="$t('settings.notification.estimate_viewed')"
        :description="$t('settings.notification.estimate_viewed_desc')"
      />
    </ul>
  </BaseSettingCard>
</template>
