<script setup lang="ts">
import * as z from "zod";
import { toTypedSchema } from "@vee-validate/zod";
import { toast } from "vue-sonner";
import { useForm } from "vee-validate";
import { useThrottleFn } from "@vueuse/core";
import { useUtmPayload } from "~/composables/useUtmPayload";
import { useApi } from "~/composables/useApi";

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

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

const formSubmitted = useState("form-submitted", () => false);
const formSchema = computed(() => createFormSchema(t));

function createFormSchema(t: (key: string) => string) {
  return toTypedSchema(
    z.object({
      company_name: z
        .string({ required_error: t("schemaErrors.required_field_error") })
        .min(3, t("schemaErrors.min")),
      work_field: z
        .string({ required_error: t("schemaErrors.required_field_error") })
        .min(3, t("schemaErrors.min")),
      company_size: z
        .string({ required_error: t("schemaErrors.required_field_error") })
        .min(1, t("schemaErrors.min_service")),
    }),
  );
}
const { handleSubmit, resetForm } = useForm({
  validationSchema: formSchema,
  validateOnMount: false,
});

const companySize = [
  { id: 1, size: "1 - 10" },
  { id: 2, size: "11 - 50" },
  { id: 3, size: "51 - 200" },
  { id: 4, size: "201 - 500" },
  { id: 5, size: "500+" },
];

const throttledSubmit = useThrottleFn(
  handleSubmit(async (values) => {
    const { post } = useApi();
    const { getUTMPayload } = useUtmPayload();
    const utm = getUTMPayload();
    const formState = useState("campaign-form");

    try {
      loading.value = true;
      errorMessage.value = "";
      successMessage.value = "";

      const payload = {
        order_id: (formState.value as any)?.order_id,
        company_name: values.company_name,
        type: "company",
        work_field: values.work_field,
        company_size: values.company_size,
        utm: utm,
      };
      await post("contact_us_stepper?step=2", payload);

      formSubmitted.value = true;
      props.next();
    } catch (err: unknown) {
      console.error("Contact form submission error:", err);

      const maybeAxiosErr = err as {
        response?: { data?: { message?: unknown } };
      };
      const message =
        typeof maybeAxiosErr?.response?.data?.message === "string"
          ? (maybeAxiosErr.response!.data!.message as string)
          : t("error_message");

      errorMessage.value = message;
      toast.error(message);

      setTimeout(() => {
        errorMessage.value = "";
      }, 3000);
    } finally {
      loading.value = false;
    }
  }),
  5000,
);
</script>

<template>
  <div>
    <form class="mx-auto w-full space-y-3">
      <!-- First Row -->
      <div class="flex w-full flex-col gap-4">
        <FormField
          v-slot="{ componentField }"
          name="company_name"
          :validate-on-blur="true"
          :validate-on-input="false"
        >
          <FormItem>
            <FormLabel class="text-primary capitalize">{{
              $t("labels.company_name_label")
            }}</FormLabel>
            <FormControl>
              <Input
                class="!bg-background border-input-border focus-visible:border-input-border h-[50px] rounded-sm border p-3 placeholder:text-[12px] focus-visible:ring-0"
                v-bind="componentField"
                :placeholder="$t('placeholders.company_name')"
              />
            </FormControl>
            <div class="text-destructive min-h-[20px] !text-sm">
              <FormMessage />
            </div>
          </FormItem>
        </FormField>

        <FormField
          v-slot="{ componentField }"
          name="work_field"
          :validate-on-blur="true"
          :validate-on-input="false"
        >
          <FormItem>
            <FormLabel class="text-primary capitalize">{{
              $t("labels.work_field_label")
            }}</FormLabel>
            <FormControl>
              <Input
                class="!bg-background border-input-border focus-visible:border-input-border h-[50px] rounded-sm border p-3 placeholder:text-[12px] focus-visible:ring-0"
                v-bind="componentField"
                :placeholder="$t('placeholders.work_field')"
              />
            </FormControl>
            <div class="text-destructive min-h-[20px] !text-sm">
              <FormMessage />
            </div>
          </FormItem>
        </FormField>

        <FormField
          v-slot="{ componentField }"
          name="company_size"
          :validate-on-blur="true"
          :validate-on-input="false"
        >
          <FormItem>
            <FormLabel class="text-primary capitalize">
              {{ $t("labels.company_size_label") }}
            </FormLabel>

            <FormControl>
              <Select
                v-bind="componentField"
                @update:model-value="(val) => componentField.onChange(val)"
              >
                <SelectTrigger
                  class="!bg-background border-input-border focus-visible:border-input-border !h-[50px] w-full rounded-sm border p-3 shadow-none focus-visible:ring-0 ltr:text-left rtl:flex-row-reverse rtl:text-right"
                >
                  <SelectValue
                    class="placeholder:text-[12px]"
                    :placeholder="$t('placeholders.company_size')"
                  />
                </SelectTrigger>

                <SelectContent
                  class="!bg-background border-input-border rounded-sm"
                  position="popper"
                  :side-offset="5"
                  :align="'start'"
                >
                  <SelectItem
                    v-for="item in companySize"
                    :key="item.id"
                    :value="item.size"
                  >
                    {{ item.size }} {{ $t("step2.employees") }}
                  </SelectItem>
                </SelectContent>
              </Select>
            </FormControl>

            <div class="text-destructive min-h-[20px] !text-sm">
              <FormMessage />
            </div>
          </FormItem>
        </FormField>
      </div>
    </form>

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

      <Button
        size="stepBtn"
        :disabled="loading"
        @click="throttledSubmit($event)"
        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>

<style scoped>
html[dir="rtl"] :deep(.SelectContent) {
  direction: rtl;
}

html[dir="rtl"] :deep(.SelectItem) {
  text-align: right;
}
</style>
