<script setup lang="ts">
import { computed, inject, readonly, ref, toRaw, useTemplateRef, watch, watchEffect } from 'vue'
import MarkdownRender from '@/components/markdown-render/markdown-render.vue'
import type { FormInst, FormRules, FormItemRule } from 'naive-ui'
import { useI18n } from 'vue-i18n'
import { useSystemLanguageStore } from '@/store/modules/system-language'
import CustomLoading from '../../custom-loading.vue'
import isEmail from 'validator/es/lib/isEmail'
import type { BusinessTripForm, ResponseBusinessTripForm } from '../types/types'
import { businessTripFormParser, businessTripFormReturner } from '../utils/smart-forms'
import { fetchBusinessTripFormSubmit } from '@/apis/smart-forms'

interface Props {
  messageItem: ConversationMessageItem
  isAgentMessage: boolean
  currentBubbleTextColor: string
  messageAuthor: string
}

const props = defineProps<Props>()

const { t } = useI18n()
const systemLanguageStore = useSystemLanguageStore()

const businessTripFormRef = useTemplateRef<FormInst>('businessTripFormRef')

const messageItemId = inject('messageItemId', '')
const { updateSpecifyMessageItem } = inject<{
  updateSpecifyMessageItem: (messageId: string, newMessageItem: Partial<ConversationMessageItem>) => void
}>('updateSpecifyMessageItem', {
  updateSpecifyMessageItem: () => {},
})

const formRules = readonly<FormRules>({
  objective: {
    required: true,
    trigger: ['blur', 'input'],
    message: '',
  },
  travelLocation: {
    required: true,
    trigger: ['blur', 'input'],
    message: '',
  },
  departureTime: {
    type: 'number',
    required: true,
    trigger: ['blur', 'input'],
    message: '',
  },
  returnTime: {
    type: 'number',
    required: true,
    trigger: ['blur', 'input'],
    message: '',
  },
  email: {
    required: true,
    trigger: ['blur', 'input'],
    validator: (_rule: FormItemRule, value: string) => {
      if (!value) {
        return new Error(t('login_module.please_enter_your_email_address'))
      } else if (!isEmail(value)) {
        return new Error(t('login_module.please_enter_the_correct_email_address'))
      }

      return
    },
  },
})

const formModel = ref<BusinessTripForm>({
  objective: 'CustomerVisits',
  travelLocation: '',
  departureTime: null,
  returnTime: null,
  vehicle: '',
  vehicleEstimatedCost: null,
  residence: '',
  residenceEstimatedCost: null,
  advancePaymentAmount: null,
  generalBudget: '',
  email: '',
})

const submitFormBtnLoading = ref(false)

const objectiveOptions = readonly([
  {
    label: t('smart_forms_module.business_trip_form.customer_visit'),
    value: 'CustomerVisits',
  },
  {
    label: t('smart_forms_module.business_trip_form.meeting'),
    value: 'Meetings',
  },
  {
    label: t('smart_forms_module.business_trip_form.training'),
    value: 'Training',
  },
])

const isDisabledForm = computed(() => {
  return !!props.messageItem.smartFormInfo && props.messageItem.smartFormInfo.isDisabled
})

watch(
  () => props.messageItem.smartFormInfo,
  (smartFormInfo) => {
    if (smartFormInfo && smartFormInfo.params) {
      let config: Partial<ResponseBusinessTripForm> = {}

      try {
        config = JSON.parse(smartFormInfo.params)
      } catch (err) {
        throw new Error('Invalid JSON')
      }

      formModel.value = {
        ...formModel.value,
        ...businessTripFormParser(config),
      }
    }
  },
  {
    once: true,
    immediate: true,
  },
)

watchEffect(() => {
  let aggregateAmount = 0

  if (formModel.value.vehicleEstimatedCost) {
    aggregateAmount += formModel.value.vehicleEstimatedCost
  }
  if (formModel.value.residenceEstimatedCost) {
    aggregateAmount += formModel.value.residenceEstimatedCost
  }
  if (formModel.value.advancePaymentAmount) {
    aggregateAmount += formModel.value.advancePaymentAmount
  }

  formModel.value.generalBudget = aggregateAmount.toString()
})

function handleSubmitForm() {
  businessTripFormRef.value?.validate((errors) => {
    if (!errors) {
      submitFormBtnLoading.value = true

      fetchBusinessTripFormSubmit(businessTripFormReturner(toRaw(formModel.value)))
        .then((res) => {
          if (res.code !== 0) return ''

          updateSpecifyMessageItem(messageItemId, {
            smartFormInfo: {
              ...(props.messageItem.smartFormInfo || { type: 'BusinessTripForm', params: '' }),
              isDisabled: true,
            },
          })
        })
        .finally(() => {
          submitFormBtnLoading.value = false
        })
    }
  })
}
</script>

<template>
  <div class="overflow-hidden">
    <div
      :class="{
        'min-w-[80px]': messageItem.isAnswerResponseLoading,
      }"
    >
      <div
        class="box-content min-w-[10px] max-w-full rounded-[10px] border border-[#9EA3FF] bg-[#777EF9] px-[15px] py-[11px] text-justify"
        :class="{
          '!bg-[#fff]': isAgentMessage,
        }"
      >
        <div v-if="messageItem.isAnswerResponseLoading" class="flex px-4 py-1.5">
          <CustomLoading :active-color="currentBubbleTextColor" />
        </div>
        <template v-else>
          <div class="mb-[10px]">
            <i class="iconfont icon-tongyi font-600 text-[14px] text-[#6ccb59]"></i>
            <span class="ml-[5px] text-[14px] text-[#999]">{{
              t('smart_forms_module.business_trip_form.execution_successful_doc')
            }}</span>
          </div>

          <MarkdownRender
            ref="markdownRenderRef"
            :raw-text-content="t('smart_forms_module.business_trip_form.result_doc')"
            :color="currentBubbleTextColor"
          />

          <!-- <div v-if="messageItem.isAnswerLoading" class="ml-[15px] pt-[12px]">
              <MessageBubbleLoading active-color="#fff" width="5px" />
            </div> -->
        </template>
      </div>

      <div
        v-if="!messageItem.isAnswerResponseLoading"
        class="mt-[10px] box-content min-h-[21px] min-w-[10px] max-w-full rounded-[10px] border border-[#9EA3FF] bg-[#777EF9] px-[15px] py-[14px] text-justify"
        :class="{
          '!bg-[#fff]': isAgentMessage,
        }"
      >
        <h2 class="font-600 text-[15px] text-[#0B7DFF]">{{ t('smart_forms_module.business_trip_form.title') }}</h2>

        <div class="mt-[12px]">
          <n-form
            ref="businessTripFormRef"
            :model="formModel"
            :rules="formRules"
            label-placement="left"
            :label-width="systemLanguageStore.isEnglishLanguage ? '150' : '90'"
            require-mark-placement="right-hanging"
            :show-feedback="false"
            :disabled="isDisabledForm"
          >
            <n-form-item
              class="mb-[10px]"
              :label="t('smart_forms_module.business_trip_form.objective')"
              path="objective"
            >
              <n-select
                v-model:value="formModel.objective"
                :placeholder="`${t('smart_forms_module.business_trip_form.please_enter_the')}${t('smart_forms_module.business_trip_form.objective')}`"
                :options="objectiveOptions"
              />
            </n-form-item>

            <n-form-item
              class="mb-[10px]"
              :label="t('smart_forms_module.business_trip_form.travel_location')"
              path="travelLocation"
            >
              <n-input
                v-model:value="formModel.travelLocation"
                :placeholder="`${t('smart_forms_module.business_trip_form.please_enter_the')} ${t('smart_forms_module.business_trip_form.objective').toLocaleLowerCase()}`"
              />
            </n-form-item>

            <n-form-item
              class="mb-[10px]"
              :label="t('smart_forms_module.business_trip_form.departure_time')"
              path="departureTime"
            >
              <n-date-picker v-model:value="formModel.departureTime" type="datetime" />
            </n-form-item>

            <n-form-item :label="t('smart_forms_module.business_trip_form.return_time')" path="returnTime">
              <n-date-picker v-model:value="formModel.returnTime" type="datetime" />
            </n-form-item>

            <n-form-item label="">
              <div class="h-[1px] w-full bg-[#B1B1B1] opacity-45"></div>
            </n-form-item>

            <n-form-item class="mb-[10px]" :label="t('smart_forms_module.business_trip_form.vehicle')" path="vehicle">
              <n-input
                v-model:value="formModel.vehicle"
                :placeholder="`${t('smart_forms_module.business_trip_form.please_enter_the')} ${t('smart_forms_module.business_trip_form.vehicle').toLocaleLowerCase()}`"
              />
            </n-form-item>

            <n-form-item :label="t('smart_forms_module.business_trip_form.estimated_cost')" path="vehicleEstimatedCost">
              <n-input-number
                v-model:value="formModel.vehicleEstimatedCost"
                :placeholder="`${t('smart_forms_module.business_trip_form.please_enter_the')} ${t('smart_forms_module.business_trip_form.estimated_cost').toLocaleLowerCase()}`"
                clearable
              />
            </n-form-item>

            <n-form-item label="">
              <div class="h-[1px] w-full bg-[#B1B1B1] opacity-45"></div>
            </n-form-item>

            <n-form-item
              class="mb-[10px]"
              :label="t('smart_forms_module.business_trip_form.residence')"
              path="residence"
            >
              <n-input
                v-model:value="formModel.residence"
                :placeholder="`${t('smart_forms_module.business_trip_form.please_enter_the')} ${t('smart_forms_module.business_trip_form.residence').toLocaleLowerCase()}`"
              />
            </n-form-item>

            <n-form-item
              :label="t('smart_forms_module.business_trip_form.estimated_cost')"
              path="residenceEstimatedCost"
            >
              <n-input-number
                v-model:value="formModel.residenceEstimatedCost"
                :placeholder="`${t('smart_forms_module.business_trip_form.please_enter_the')} ${t('smart_forms_module.business_trip_form.estimated_cost').toLocaleLowerCase()}`"
                clearable
              />
            </n-form-item>

            <n-form-item label="">
              <div class="h-[1px] w-full bg-[#B1B1B1] opacity-45"></div>
            </n-form-item>

            <n-form-item
              class="mb-[10px]"
              :label="t('smart_forms_module.business_trip_form.advance_payment_amount')"
              path="advancePaymentAmount"
            >
              <n-input-number
                v-model:value="formModel.advancePaymentAmount"
                :placeholder="`${t('smart_forms_module.business_trip_form.please_enter_the')} ${t('smart_forms_module.business_trip_form.advance_payment_amount').toLocaleLowerCase()}`"
                clearable
              />
            </n-form-item>

            <n-form-item :label="t('smart_forms_module.business_trip_form.general_budget')" path="generalBudget">
              <n-input
                v-model:value="formModel.generalBudget"
                :placeholder="`${t('smart_forms_module.business_trip_form.please_enter_the')} ${t('smart_forms_module.business_trip_form.general_budget').toLocaleLowerCase()}`"
                disabled
              />
            </n-form-item>

            <n-form-item label="">
              <div class="h-[1px] w-full bg-[#B1B1B1] opacity-45"></div>
            </n-form-item>

            <n-form-item class="mb-[10px]" :label="t('smart_forms_module.business_trip_form.email')" path="email">
              <n-input
                v-model:value="formModel.email"
                :placeholder="`${t('smart_forms_module.business_trip_form.please_enter_the')} ${t('smart_forms_module.business_trip_form.email').toLocaleLowerCase()}`"
              />
            </n-form-item>

            <div class="mt-[46px] text-end">
              <n-button
                type="primary"
                :disabled="isDisabledForm"
                :loading="submitFormBtnLoading"
                @click="handleSubmitForm"
              >
                {{ t('smart_forms_module.business_trip_form.confirm_submission') }}
              </n-button>
            </div>
          </n-form>
        </div>
      </div>
    </div>
  </div>
</template>
