<script setup lang="ts">
import RadioInput from "../components/RadioInput.vue";
import { toast } from "vue-sonner";
import { useUtmPayload } from "~/composables/useUtmPayload";
import { useApi } from "~/composables/useApi";

const props = defineProps<{
  next: () => void;
  prev: () => void;
  isNextDisabled: boolean;
  isPrevDisabled: boolean;
}>();

const selected = ref("");
const loading = ref(false);
const {t} = useI18n();

const isNextButtonDisabled = computed(() => {
  return loading.value || !selected.value;
});

async function handleSubmit() {
  if (!selected.value) {
    toast.error("Please select a start time.");
    return;
  }

  const { post } = useApi();
  const { getUTMPayload } = useUtmPayload();
  const utm = getUTMPayload();
  const formState = useState("campaign-form");

  try {
    loading.value = true;
    const payload = {
      order_id: (formState.value as any)?.order_id,
      project_start_time: selected.value,
      utm: utm,
    };

    await post("contact_us_stepper?step=6", payload);
    props.next();
  } catch (err) {
    console.error(err);
    toast.error("Error submitting step");
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <div>
    <h2 class="mb-2">{{ $t("stepper.step6.desc") }}</h2>

    <div class="flex flex-col gap-8">
      <RadioInput id="Immediately" :value="t('step6.startImmediately')" :text="t('step6.startImmediately')" v-model="selected" name="startTime" />

      <RadioInput id="Within 1 month: 3 months from now" :value="t('step6.startIn1To3Months')"
       :text="t('step6.startIn1To3Months')" v-model="selected" name="startTime" />

      <RadioInput id="Within 3 to 6 months from now" :value="t('step6.startIn3To6Months')"
       :text="t('step6.startIn3To6Months')" v-model="selected" name="startTime" />
      <RadioInput id="+ 6 months from now" :value="t('step6.startAfter6Months')" :text="t('step6.startAfter6Months')" v-model="selected"
        name="startTime" />
    </div>

    <div class="mt-6 flex w-[98%] gap-4">
      <Button size="stepBtn" variant="wsPrev" :disabled="props.isPrevDisabled || loading" @click="props.prev"
        class="w-1/2">
        {{ $t("buttons.prev") }}
      </Button>

      <Button size="stepBtn" :disabled="isNextButtonDisabled" @click="handleSubmit" class="w-1/2"> <span
          v-if="loading">{{ $t("buttons.loading_send_button") }}</span>
        <span v-else>{{ $t("buttons.next") }}</span>
      </Button>
    </div>
  </div>
</template>