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

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

const { slug } = defineProps<{ slug: string }>();
const fileInput = ref<HTMLInputElement | null>(null);
const successMessage = ref("");
const errorMessage = ref("");
const loading = ref(false);
const formSchema = computed(() => createFormSchema(t));

function createFormSchema(t: (key: string) => string) {
  const phoneRegex = /^(?:\+?(20|966))?0?\d{9,10}$/;
  return toTypedSchema(
    z.object({
      full_name: z
        .string({
          required_error: t("schemaErrors.required_field_error"),
        })
        .min(3, t("schemaErrors.min")),
      phone: z
        .string({
          required_error: t("schemaErrors.phone_reqired_error"),
        })
        .refine((val) => phoneRegex.test(val), {
          message: t("schemaErrors.phone_invalid_error"),
        }),
      email: z
        .string({
          required_error: t("schemaErrors.email_required_error"),
        })
        .email(t("schemaErrors.email_invalid_error")),
      cv: z
        .any()
        .refine((file) => file instanceof File, {
          message: t("schemaErrors.required_field_error"),
        })
        .refine(
          (file) =>
            file &&
            [
              "application/pdf",
              "application/msword",
              "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            ].includes(file.type),
          {
            message: t("schemaErrors.file_type_error"),
          },
        ),
      portfolio: z
        .string()
        .url({ message: t("schemaErrors.portfolio_invalid_error") })
        .optional(),
      current_salary: z.coerce
        .number({
          invalid_type_error: t("schemaErrors.expected_salary_invalid_error"),
        })
        .optional(),
      expected_salary: z.coerce
        .number({
          required_error: t("schemaErrors.required_field_error"),
          invalid_type_error: t("schemaErrors.expected_salary_invalid_error"),
          message: t("schemaErrors.expected_salary_invalid_error"),
        })
        .min(1, { message: t("schemaErrors.required_field_error") }),
    }),
  );
}

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

const onSubmit = handleSubmit(async (values) => {
  const { post } = useApi();
  try {
    loading.value = true;
    errorMessage.value = "";
    successMessage.value = "";

    const formData = new FormData();
    formData.append("name", values.full_name);
    formData.append("phone", values.phone);
    formData.append("email", values.email);
    formData.append("cv", values.cv);
    if (values.portfolio) {
      formData.append("portfolio_url", values.portfolio);
    }
    if (values.current_salary !== undefined) {
      formData.append("current_salary", values.current_salary.toString());
    }
    formData.append("expected_salary", values.expected_salary.toString());

    const utmPayload = getUTMPayload();
    if (utmPayload) {
      formData.append("utm", JSON.stringify(utmPayload));
    }

    await post(`jobs/${slug}/apply`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }).then((res) => {
      console.log(res.data.message);
    });

    successMessage.value = t("success_message");
    resetForm();
  } catch (err: any) {
    console.error("Form submission error:", err);
    errorMessage.value = err?.response?.data?.message || t("error_message");

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

<template>
  <form class="mx-auto w-full space-y-3" @submit="onSubmit">
    <!-- First Row -->
    <div
      class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-1 xl:grid-cols-2"
    >
      <FormField
        v-slot="{ componentField }"
        name="full_name"
        :validate-on-blur="true"
        :validate-on-input="false"
      >
        <FormItem>
          <FormLabel class="text-primary capitalize">{{
            $t("labels.full_name_label")
          }}</FormLabel>
          <FormControl>
            <Input
              class="!bg-background border-input-border focus-visible:border-input-border h-[40px] rounded-sm border p-3 focus-visible:ring-0"
              v-bind="componentField"
            />
          </FormControl>
          <div class="text-destructive min-h-[20px] !text-sm">
            <FormMessage />
          </div>
        </FormItem>
      </FormField>

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

    <!-- Second Row -->
    <div
      class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-1 xl:grid-cols-2"
    >
      <FormField
        v-slot="{ componentField }"
        name="email"
        :validate-on-blur="true"
        :validate-on-input="false"
      >
        <FormItem>
          <FormLabel class="text-primary capitalize">{{
            $t("labels.email_label")
          }}</FormLabel>
          <FormControl>
            <Input
              class="!bg-background border-input-border focus-visible:border-input-border h-[40px] rounded-sm border p-3 focus-visible:ring-0"
              v-bind="componentField"
            />
          </FormControl>
          <div class="text-destructive min-h-[20px] !text-sm">
            <FormMessage />
          </div>
        </FormItem>
      </FormField>

      <FormField
        v-slot="{ componentField }"
        name="portfolio"
        :validate-on-blur="true"
        :validate-on-input="false"
      >
        <FormItem>
          <FormLabel class="text-primary capitalize">{{
            $t("labels.portfolio_label")
          }}</FormLabel>
          <FormControl>
            <Input
              class="!bg-background border-input-border focus-visible:border-input-border h-[40px] rounded-sm border p-3 focus-visible:ring-0"
              v-bind="componentField"
            />
          </FormControl>
          <div class="text-destructive min-h-[20px] !text-sm">
            <FormMessage />
          </div>
        </FormItem>
      </FormField>
    </div>
    <div
      class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-1 xl:grid-cols-2"
    >
      <FormField
        v-slot="{ componentField }"
        name="current_salary"
        :validate-on-blur="true"
        :validate-on-input="false"
      >
        <FormItem>
          <FormLabel class="text-primary capitalize">{{
            $t("labels.current_salary_label")
          }}</FormLabel>
          <FormControl>
            <Input
              class="!bg-background border-input-border focus-visible:border-input-border h-[40px] rounded-sm border p-3 focus-visible:ring-0"
              v-bind="componentField"
            />
          </FormControl>
          <div class="text-destructive min-h-[20px] !text-sm">
            <FormMessage />
          </div>
        </FormItem>
      </FormField>

      <FormField
        v-slot="{ componentField }"
        name="expected_salary"
        :validate-on-blur="true"
        :validate-on-input="false"
      >
        <FormItem>
          <FormLabel class="text-primary capitalize">{{
            $t("labels.expected_salary_label")
          }}</FormLabel>
          <FormControl>
            <Input
              class="!bg-background border-input-border focus-visible:border-input-border h-[40px] rounded-sm border p-3 focus-visible:ring-0"
              v-bind="componentField"
            />
          </FormControl>
          <div class="text-destructive min-h-[20px] !text-sm">
            <FormMessage />
          </div>
        </FormItem>
      </FormField>
    </div>
    <div>
      <FormField
        v-slot="{ componentField, handleChange, value }"
        name="cv"
        :validate-on-blur="true"
        :validate-on-input="false"
      >
        <FormItem>
          <FormLabel class="text-primary capitalize">{{
            $t("labels.cv_label")
          }}</FormLabel>
          <FormControl>
            <input
              ref="fileInput"
              type="file"
              accept=".pdf,.doc,.docx"
              class="hidden"
              v-bind="componentField"
              @change="
                (e) => handleChange((e.target as HTMLInputElement)?.files?.[0])
              "
            />
            <button
              type="button"
              class="!bg-background border-input-border focus-visible:border-input-border h-[40px] rounded-sm border p-3 focus-visible:ring-0"
              @click="fileInput?.click()"
            >
              <div v-if="value" class="flex h-full items-center text-sm">
                <span>{{ value.name }}</span>
              </div>
              <div v-else class="flex h-full items-center gap-2">
                <SvgUploadIcon />
                <span class="text-sm">{{ $t("buttons.upload_cv") }}</span>
              </div>
            </button>
          </FormControl>
          <div class="text-destructive min-h-[20px] !text-sm">
            <FormMessage />
          </div>
        </FormItem>
      </FormField>
    </div>

    <!-- Submit Button -->
    <Button
      type="submit"
      :class="loading ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'"
      class="ws-gradient-border text-foreground h-[48px] w-full"
    >
      <span v-if="loading" class="flex items-center gap-2">
        <span>{{ $t("buttons.loading_send_button") }}</span>
        <span class="animate-spin-loader" />
      </span>

      <span v-else>
        {{ $t("buttons.send_button") }}
      </span>
    </Button>
    <div v-if="successMessage" class="text-center text-green-500">
      {{ $t("success_message") }}
    </div>
    <div v-if="errorMessage" class="text-center text-red-500">
      {{ errorMessage }}
    </div>
  </form>
</template>
