<template>
  <BasicModal
    :title="isEditMode ? 'ویرایش سابقه کاری' : 'افزودن سابقه کاری'"
    title-en="Work Experience"
    width="95%"
    max-width="58rem"
    min-width="auto"
    :show-close-button="true"
  >
    <template #default="{ close }">
      <form class="add-work" @submit.prevent="onSubmit(close)">
        <TextField
          v-model="form.jobTitle"
          name="jobTitle"
          label="عنوان شغل شما"
          :error="errors.jobTitle"
          @blur="validateAt('jobTitle', form.jobTitle)"
        />

        <div class="add-work__row">
          <TextField
            v-model="form.activityField"
            name="activityField"
            label="زمینه فعالیت شما در این شرکت"
          />
          <TextField
            v-model="form.organizationLevel"
            name="organizationLevel"
            label="رده سازمانی"
          />
        </div>

        <TextField
          v-model="form.organizationName"
          name="organizationName"
          label="نام سازمان"
          :error="errors.organizationName"
          @blur="validateAt('organizationName', form.organizationName)"
        />

        <div class="add-work__row">
          <SelectField
            v-model="form.provinceId"
            name="provinceId"
            label="استان"
            :options="provinces"
            option-label="name"
            option-value="id"
            @change="onProvinceChange"
          />
          <SelectField
            v-model="form.cityId"
            name="cityId"
            label="شهر"
            :options="cities"
            option-label="name"
            option-value="id"
            :disabled="!form.provinceId"
          />
        </div>

        <div class="add-work__row add-work__row--always">
          <SelectField
            v-model="form.startMonth"
            name="startMonth"
            label="ماه شروع"
            :options="MONTHS"
            option-label="label"
            option-value="value"
          />
          <TextField
            v-model="form.startYear"
            name="startYear"
            label="سال شروع"
            inputmode="numeric"
            :convert-digits="true"
          />
        </div>

        <div class="add-work__row add-work__row--always">
          <SelectField
            v-model="form.endMonth"
            name="endMonth"
            label="ماه پایان"
            :options="MONTHS"
            option-label="label"
            option-value="value"
          />
          <TextField
            v-model="form.endYear"
            name="endYear"
            label="سال پایان"
            inputmode="numeric"
            :convert-digits="true"
          />
        </div>

        <TextareaField
          v-model="form.achievements"
          name="achievements"
          label="دستاورد‌ها و وظایف کلیدی"
          :row="4"
        />

        <div class="add-work__divider" />

        <footer class="add-work__footer">
          <BaseButton type="submit" text="ذخیره اطلاعات" custom-class="add-work__submit">
            <template #appendIcon>
              <SvgIcon name="arrow-left" :size="18" color="#fff" />
            </template>
          </BaseButton>
        </footer>
      </form>
    </template>
  </BasicModal>
</template>

<script setup>
import { ref } from 'vue'
import * as yup from 'yup'
import useYup from '@/composables/useYup'
import useModal from '@/composables/useModal'
import BasicModal from '@/components/BasicModal.vue'
import BaseButton from '@/components/BaseButton.vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import TextField from '@/components/form/TextField.vue'
import SelectField from '@/components/form/SelectField.vue'
import TextareaField from '@/components/form/TextareaField.vue'
import { MONTHS } from '@/features/missionary/constants/complete-info'
import { useCompleteInfoStore } from '@/features/missionary/store/complete-info'
import { useGetCitiesOfProvinceQuery, useGetProvincesQuery } from '@/services/query/common'

defineOptions({ name: 'MissionaryAddWorkExperienceModal' })

const store = useCompleteInfoStore()
const { getModal } = useModal()

const modalData = getModal('MissionaryAddWorkExperienceModal')?.data ?? {}
const editingIndex = modalData.index ?? null
const isEditMode = editingIndex != null

const emptyForm = () => ({
  jobTitle: '',
  activityField: '',
  organizationLevel: '',
  organizationName: '',
  provinceId: null,
  cityId: null,
  startMonth: null,
  startYear: '',
  endMonth: null,
  endYear: '',
  achievements: '',
})

const form = ref({ ...emptyForm(), ...modalData.entry })

const schema = yup.object({
  jobTitle: yup.string().trim().required('عنوان شغل را وارد کنید'),
  organizationName: yup.string().trim().required('نام سازمان را وارد کنید'),
})

const { validate, validateAt, errors } = useYup(schema)

const { data: provinces = ref([]) } = useGetProvincesQuery()

const provinceIdRef = ref(form.value.provinceId)
const { data: cities = ref([]) } = useGetCitiesOfProvinceQuery(provinceIdRef, {
  enabled: () => !!provinceIdRef.value,
})

const onProvinceChange = () => {
  provinceIdRef.value = form.value.provinceId
  form.value.cityId = null
}

const onSubmit = async (close) => {
  const { isValid } = await validate(form.value)
  if (!isValid) return
  store.upsertWorkExperience({ ...form.value }, editingIndex)
  close?.()
}
</script>

<style lang="scss" scoped>
.add-work {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  text-align: start;
  padding-block: 0.25rem 0.5rem;

  &__row {
    display: grid;
    grid-template-columns: 1fr;
    gap: 0 0.875rem;

    @media (min-width: 768px) {
      grid-template-columns: 1fr 1fr;
    }

    &--always {
      grid-template-columns: 1fr 1fr;
    }
  }

  &__divider {
    border-block-end: 1px solid #ddd;
    margin-block: 0.5rem 0.75rem;
  }

  &__footer {
    display: flex;
    justify-content: flex-start;
  }

  &__submit {
    min-width: 14rem;
    padding: 0 1.5rem;
  }
}
</style>
