<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";
import { computed } from "vue";

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

const selected = ref("");
const loading = ref(false);

// Computed property to check if the Next button should be disabled
const isNextButtonDisabled = computed(() => {
  return loading.value || !selected.value;
});

async function handleSubmit() {
  if (!selected.value) {
    toast.error("Please select a budget range.");
    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,
      budget_range: selected.value,
      utm: utm,
    };

    await post("contact_us_stepper?step=5", 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.step5.desc") }}</h2>

    <div class="flex flex-col gap-3">
      <RadioInput id=" 5000  :  15,000" value=" 5000  :  15,000" text=" 5000  :  15,000" v-model="selected"
        name="range" />

      <RadioInput id=" 16,000  :  25,000" value=" 16,000  :  25,000" text=" 16,000  :  25,000" v-model="selected"
        name="range" />

      <RadioInput id=" 26,000  :  35,000" value=" 26,000  :  35,000" text=" 26,000  :  35,000" v-model="selected"
        name="range" />
      <RadioInput id=" 36,000  :  50,000" value=" 36,000  :  50,000" text=" 36,000  :  50,000" v-model="selected"
        name="range" />
      <RadioInput id="+50,000" value="+50,000" text="+50,000" v-model="selected" name="range" />
    </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>