<template>
  <form class="professional-info" @submit.prevent="onSubmit">
    <LineTitleBlock title="مشخصات تبلیغی" title-en="Propagation Details" />
    <div class="professional-info__row">
      <div class="professional-info__cell professional-info__cell--5">
        <TextField
          v-model="form.propagationExperienceYears"
          name="propagationExperienceYears"
          label="سابقه فعالیت تبلیغی شما چند سال می باشد؟"
          inputmode="numeric"
          :convert-digits="true"
          :error="errors.propagationExperienceYears"
          @blur="validateAt('propagationExperienceYears', form.propagationExperienceYears)"
        >
          <template #appendIcon>
            <SvgIcon name="check-square" :size="20" color="var(--color-thd-gray)" />
          </template>
        </TextField>
      </div>
      <div class="professional-info__cell professional-info__cell--7">
        <TextareaField
          v-model="form.propagationMethodDescription"
          name="propagationMethodDescription"
          label="لطفا توضیحاتی ناظر بر مدل فعالیت تبلیغی خود بفرمایید."
          :row="isMobile ? 5 : 1"
          :error="errors.propagationMethodDescription"
          @blur="validateAt('propagationMethodDescription', form.propagationMethodDescription)"
        >
          <template #appendIcon>
            <SvgIcon name="file" :size="20" color="var(--color-thd-gray)" />
          </template>
        </TextareaField>
      </div>
      <div class="professional-info__cell professional-info__cell--full">
        <TextareaField
          v-model="form.specializedTopics"
          name="specializedTopics"
          label="موضوعات تخصصی تبلیغی خود را بفرمایید."
          :row="isMobile ? 5 : 1"
          :error="errors.specializedTopics"
          @blur="validateAt('specializedTopics', form.specializedTopics)"
        >
          <template #appendIcon>
            <SvgIcon name="file" :size="20" color="var(--color-thd-gray)" />
          </template>
        </TextareaField>
      </div>
      <div class="professional-info__cell professional-info__cell--5">
        <SelectField
          v-model="form.propagationPlatforms"
          name="propagationPlatforms"
          label="در چه بستر هایی فعالیت تبلیغی داشته اید؟ (امکان انتخاب چند گزینه وجود دارد)"
          :options="platformOptions"
          option-label="label"
          option-value="value"
          :multiple="true"
          :error="errors.propagationPlatforms"
          @change="onPlatformsChange"
        />
      </div>
      <div
        :class="[
          'professional-info__cell',
          'professional-info__cell--7',
          { 'professional-info__cell--blurred': !hasOther },
        ]"
      >
        <TextareaField
          v-model="form.otherPlatformDetails"
          name="otherPlatformDetails"
          label="نوع فعالیت خود را توضیح دهید."
          :row="isMobile ? 5 : 1"
          :disabled="!hasOther"
          :error="errors.otherPlatformDetails"
        >
          <template #appendIcon>
            <SvgIcon name="file" :size="20" color="var(--color-thd-gray)" />
          </template>
        </TextareaField>
      </div>
      <div
        :class="[
          'professional-info__cell',
          'professional-info__cell--full',
          { 'professional-info__cell--blurred': !hasOnline },
        ]"
      >
        <TextareaField
          v-model="form.onlinePlatformDetails"
          name="onlinePlatformDetails"
          label="نام شبکه و مدل فعالیت تبلیغی خود را ذکر کنید."
          :row="isMobile ? 5 : 1"
          :disabled="!hasOnline"
          :error="errors.onlinePlatformDetails"
        >
          <template #appendIcon>
            <SvgIcon name="file" :size="20" color="var(--color-thd-gray)" />
          </template>
        </TextareaField>
      </div>
    </div>

    <div class="professional-info__divider" />
    <StepActions :loading="saveRegisterMutation.isPending.value" @back="store.goToPrevStep()" />
  </form>
</template>

<script setup>
import useYup from '@/composables/useYup'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import TextField from '@/components/form/TextField.vue'
import SelectField from '@/components/form/SelectField.vue'
import LineTitleBlock from '@/components/LineTitleBlock.vue'
import TextareaField from '@/components/form/TextareaField.vue'
import { useSaveRegisterDataMutation } from '@/services/query/auth'
import { PROPAGATION_PLATFORM, STUDENT_REGISTRATION } from '@/enums'
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import StepActions from '@/features/auth/components/studentRegister/StepActions.vue'
import { professionalInformationSchema } from '@/features/auth/schema/student-register'
import { useStudentRegistrationStore } from '@/features/auth/store/student-registration'

const store = useStudentRegistrationStore()

const isMobile = ref(window.innerWidth < 768)
const onResize = () => {
  isMobile.value = window.innerWidth < 768
}
onMounted(() => window.addEventListener('resize', onResize))
onBeforeUnmount(() => window.removeEventListener('resize', onResize))

const platformOptions = Object.entries(PROPAGATION_PLATFORM).map(([value, label]) => ({
  value,
  label,
}))

const seedPlatforms = (store.professional.propagationPlatforms || []).map((p) => p.platform || p)
const seedOther =
  store.professional.propagationPlatforms?.find((p) => p.platform === 'other')?.platformDetails ||
  ''
const seedOnline =
  store.professional.propagationPlatforms?.find((p) => p.platform === 'online')?.platformDetails ||
  ''

const form = ref({
  propagationExperienceYears: store.professional.propagationExperienceYears || '',
  propagationMethodDescription: store.professional.propagationMethodDescription || '',
  specializedTopics: store.professional.specializedTopics || '',
  propagationPlatforms: seedPlatforms,
  otherPlatformDetails: seedOther,
  onlinePlatformDetails: seedOnline,
})

watch(form, (value) => store.updateSection('professional', value), { deep: true })

const hasOther = computed(() => form.value.propagationPlatforms.includes('other'))
const hasOnline = computed(() => form.value.propagationPlatforms.includes('online'))

const onPlatformsChange = (selected) => {
  let next = Array.isArray(selected) ? [...selected] : []
  const hasNone = next.includes('none')
  const hasOthers = next.some((v) => v !== 'none')
  if (hasNone && hasOthers) {
    const lastSelected = next.at(-1)
    next = lastSelected === 'none' ? ['none'] : next.filter((v) => v !== 'none')
  }
  form.value.propagationPlatforms = next
  if (!next.includes('online')) form.value.onlinePlatformDetails = ''
  if (!next.includes('other')) form.value.otherPlatformDetails = ''
}

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

const saveRegisterMutation = useSaveRegisterDataMutation()

const onSubmit = async () => {
  const { isValid, payload } = await validate(form.value)
  if (!isValid) return

  const propagationPlatforms = payload.propagationPlatforms.map((platform) => {
    if (platform === 'online') {
      return { platform: 'online', platformDetails: payload.onlinePlatformDetails || '' }
    }
    if (platform === 'other') {
      return { platform: 'other', platformDetails: payload.otherPlatformDetails || '' }
    }
    return { platform, platformDetails: '' }
  })

  const next = {
    propagationExperienceYears: Number(payload.propagationExperienceYears),
    propagationMethodDescription: payload.propagationMethodDescription,
    specializedTopics: payload.specializedTopics,
    propagationPlatforms,
  }
  await saveRegisterMutation.mutateAsync(next)
  store.professional = next
  store.markStepAsCompleted(STUDENT_REGISTRATION.PROFESSIONAL_INFORMATION)
  store.goToNextStep()
}
</script>

<style lang="scss" scoped>
.professional-info {
  &__row {
    display: grid;
    grid-template-columns: 1fr;
    gap: 0.5rem 0.625rem;
    margin-bottom: 1rem;

    @media (min-width: 1024px) {
      grid-template-columns: repeat(12, 1fr);
    }
  }

  &__cell--5 {
    @media (min-width: 1024px) {
      grid-column: span 5;
    }
  }

  &__cell--7 {
    @media (min-width: 1024px) {
      grid-column: span 7;
    }
  }

  &__cell--full {
    grid-column: 1 / -1;
  }

  &__cell--blurred {
    filter: blur(2px);
    transition: filter 0.2s ease;
  }

  &__divider {
    border-block-end: 1px solid var(--color-thd-gray);
    margin: 1rem 0 1.5rem;
  }
}
</style>
