<script setup lang="ts">
import { useForm } from "vee-validate";
import * as z from "zod";
import { toTypedSchema } from "@vee-validate/zod";

const { t } = useI18n();
const { getUTMPayload } = useUtmPayload();

const formSchema = toTypedSchema(
  z.object({
    email: z
      .string({
        required_error: t("schemaErrors.email_required_error"),
      })
      .email(t("schemaErrors.email_invalid_error")),
  }),
);

const { handleSubmit, resetForm } = useForm({
  validationSchema: formSchema,
  validateOnMount: false,
});

const loading = ref(false);
const successMessage = ref("");
const errorMessage = ref("");

const onSubmit = handleSubmit(async (values) => {
  const { post } = useApi();
  try {
    loading.value = true;
    errorMessage.value = "";
    successMessage.value = "";
    const payload = {
      ...values,
      utm: getUTMPayload(),
    };
    await post("news-letter", payload);
    successMessage.value = t("success_message");
    resetForm();

    setTimeout(() => {
      successMessage.value = "";
    }, 3000);
  } catch (err: any) {
    // console.error('Subscribe form submission error:', err);

    const message = err?.response?.data?.message || t("error_message");

    errorMessage.value = message;

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

<template>
  <section
    id="subscribe"
    class="bg-surface-background container mx-auto flex flex-col items-center justify-center rounded-lg px-4 py-12 text-center"
  >
    <BlogsTitle
      :title="t('subscriptionSection.title')"
      :description="t('subscriptionSection.description')"
      custom-style="!gap-1 text-[32px] md:text-[40px] font-bold"
      title-heading="h2"
      description-custom-style="text-base md:text-lg font-normal"
    />

    <form class="mt-6 w-full max-w-[600px]" @submit.prevent="onSubmit">
      <FormField
        v-slot="{ componentField }"
        name="email"
        :validate-on-blur="true"
        :validate-on-input="false"
      >
        <FormItem>
          <div
            class="flex w-full flex-col items-stretch overflow-hidden rounded-md sm:flex-row"
          >
            <FormControl>
              <Input
                class="bg-input placeholder:text-primary relative h-[50px] w-full rounded-none border-none px-4 text-sm focus:ring-0 focus:outline-none focus-visible:ring-0"
                :placeholder="t('placeholders.email')"
                v-bind="componentField"
              />
            </FormControl>

            <button
              type="submit"
              :disabled="loading"
              class="ws-gradient-border border-input-border text-primary borderRedius absolute bottom-1 w-full cursor-pointer !rounded-t-none border-t px-4 py-2 text-lg font-medium sm:bottom-0 sm:w-[34%] sm:!rounded-t-md sm:!rounded-l-none sm:border-t-0 sm:border-r sm:border-l-0 rtl:!rounded-l-md rtl:sm:!rounded-r-none"
              :class="[
                $i18n.locale === 'ar'
                  ? 'left-0 sm:left-1'
                  : 'right-0 sm:right-1',
                { 'cursor-not-allowed opacity-50': loading },
              ]"
            >
              <span v-if="loading" class="animate-spin-loader" />
              <span v-else>{{ t("buttons.subscribe_button") }}</span>
            </button>
          </div>

          <div class="text-destructive mt-1 min-h-[20px] text-center text-base">
            <FormMessage />
          </div>
        </FormItem>
      </FormField>
    </form>

    <p v-if="successMessage" class="mt-2 text-center text-base text-green-600">
      {{ successMessage }}
    </p>
    <p v-if="errorMessage" class="mt-2 text-center text-base text-red-600">
      {{ errorMessage }}
    </p>
  </section>
</template>

<style scoped>
.bg-input {
  background: linear-gradient(
    90deg,
    rgba(0, 190, 215, 0.1) 0%,
    rgba(200, 83, 239, 0.1) 100%
  );
}

input:-webkit-autofill {
  -webkit-background-color: var(--surface-background-gradient) !important;
  -webkit-text-fill-color: var(--primary) !important;
  transition: background-color 5000s ease-in-out 10s;
}
</style>
