<script setup lang="ts">
import { toTypedSchema } from "@vee-validate/zod";
import PhoneInput from "base-vue-phone-input";
import type { Results } from "base-vue-phone-input";
import { useFocus, useThrottleFn } from "@vueuse/core";
import { ChevronsUpDown } from "lucide-vue-next";
import { useForm } from "vee-validate";
import * as z from "zod";
import type { Country, Service } from "~/types/Contact";
import { toast } from "vue-sonner";
import { useCountriesQuery, useServicesQuery } from "~/queries/contact";
import RadioInput from "../components/RadioInput.vue";
import Individual from "~/components/svg/CampaignForm/Individual.vue";
import Campony from "~/components/svg/CampaignForm/Campony.vue";
import { useUtmPayload } from "~/composables/useUtmPayload";
import { useApi } from "~/composables/useApi";



interface CampaignFormState {
  type?: string;
}

const props = defineProps<{
  next: () => void;
  prev: () => void;
  isNextDisabled: boolean;
  isPrevDisabled: boolean;
}>();
interface Props {
  services: Service[];
}
const { t } = useI18n();
const { data: countries } = useCountriesQuery();
const { data: services } = useServicesQuery();

const phoneInput = ref(null);
const { focused } = useFocus(phoneInput);
const open = ref(false);
const phoneResult = ref<Results | null>();
const successMessage = ref("");
const errorMessage = ref("");
const loading = ref(false);

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

function onPhoneUpdate(res: Results) {
  phoneResult.value = res;
}

function createFormSchema(t: (key: string) => string) {
  return toTypedSchema(
    z.object({
      full_name: z
        .string({ required_error: t("schemaErrors.required_field_error") })
        .min(3, t("schemaErrors.min")),
      email: z
        .string({ required_error: t("schemaErrors.email_required_error") })
        .email(t("schemaErrors.email_invalid_error")),
      phone: z
        .string({ required_error: t("schemaErrors.required_field_error") })
        .min(1, t("schemaErrors.required_field_error"))
        .refine(
          () => phoneResult.value?.isValid === true,
          t("schemaErrors.phone_invalid_error"),
        ),
      service_id: z
        .number({ required_error: t("schemaErrors.required_field_error") })
        .min(1, t("schemaErrors.min_service")),

      type: z.enum(["individual", "company"], {
        required_error: t("schemaErrors.required_field_error"),
      }),
    }),
  );
}
const { handleSubmit, resetForm } = useForm({
  validationSchema: formSchema,
  validateOnMount: false,
});

function handleSuccess() {
  const route = useRoute();
  if (route.path !== "/campaign-v2/stepper-form") {
    navigateTo("/campaign-v2/stepper-form");
  } else {
    props.next();
  }
}

const throttledSubmit = useThrottleFn(
  handleSubmit(async (values) => {
    try {
      loading.value = true;
      const { post } = useApi();
      const { getUTMPayload } = useUtmPayload();
      const utm = getUTMPayload();

      const payload = {
        full_name: values.full_name,
        email: values.email,
        phone: phoneResult.value?.formatInternational,
        country_code: phoneResult.value?.countryCode,
        service_id: values.service_id,
        type: values.type,
        utm: utm,
      };
      const response = await post("contact_us_stepper?step=1", payload);
      const orderId = response?.data?.data?.order_id;

     const formState = useState<CampaignFormState>("campaign-form");
      formState.value = { ...formState.value, ...payload, order_id: orderId };

      formSubmitted.value = true;

      handleSuccess();
    } catch (err) {
      console.error(err);
      toast.error("Error submitting form");
    } finally {
      loading.value = false;
    }
  }),
  3000,
);
</script>

<template>
  <div class="w-full">
    <form class="mx-auto w-full space-y-3" @submit.prevent="throttledSubmit">
      <!-- First Row -->
      <div class="grid grid-cols-1 gap-4 md: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-[50px] rounded-sm border p-3 placeholder:text-[12px] focus-visible:ring-0"
                v-bind="componentField"
                :placeholder="$t('placeholders.name')"
              />
            </FormControl>
            <div class="text-destructive min-h-[20px] !text-sm">
              <FormMessage />
            </div>
          </FormItem>
        </FormField>

        <FormField v-slot="{ componentField }" name="phone">
          <FormItem>
            <FormLabel class="text-primary capitalize">
              {{ $t("labels.phone_label") }}
            </FormLabel>
            <FormControl>
              <ClientOnly>
                <PhoneInput
                  noUseBrowserLocale
                  fetchCountry
                  :country-code="'SA'"
                  :country-locale="$i18n.locale"
                  class="flex items-center"
                  :only-countries="[
                    'SA',
                    'EG',
                    'AE',
                    'KW',
                    'QA',
                    'BH',
                    'JO',
                    'MA',
                    'PS',
                    'TN',
                    'DZ',
                    'KM',
                    'DJ',
                    'IQ',
                    'LB',
                    'LY',
                    'MR',
                    'OM',
                    'SD',
                    'SY',
                    'YE',
                  ]"
                  @update="onPhoneUpdate"
                >
                  <template
                    #selector="{ inputValue, updateInputValue, countries }"
                  >
                    <Popover>
                      <PopoverTrigger>
                        <Button
                          type="button"
                          class="!bg-background border-input-border focus-visible:border-input-border border-e-none h-[50px] rounded-sm rounded-e-none border p-3 placeholder:text-[12px] focus-visible:ring-0"
                        >
                          <ContactFlagComponent :country="inputValue" />
                          <ChevronsUpDown
                            class="text-foreground h-4 w-4 opacity-50"
                          />
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent
                        :align="'start'"
                        class="!bg-background border-input-border ws-scrollbar w-[287px] rounded-sm p-0 sm:w-[540px] md:w-[325px] lg:w-[455px] xl:w-[270px] 2xl:w-[335px]"
                      >
                        <Command :dir="$i18n.locale === 'ar' ? 'rtl' : 'ltr'">
                          <CommandInput
                            :placeholder="$t('placeholders.country')"
                          />
                          <CommandEmpty>{{
                            $t("placeholders.noResult")
                          }}</CommandEmpty>
                          <CommandList>
                            <CommandGroup>
                              <CommandItem
                                v-for="option in countries"
                                :key="option.iso2"
                                :value="option.iso2"
                                class="gap-2"
                                @select="
                                  () => {
                                    updateInputValue(option.iso2);
                                    open = false;
                                    focused = true;
                                  }
                                "
                              >
                                <ContactFlagComponent :country="option?.iso2" />
                                <span class="flex-1 text-sm">{{
                                  option.name
                                }}</span>
                                <span class="text-foreground/50 text-sm">{{
                                  option.dialCode
                                }}</span>
                              </CommandItem>
                            </CommandGroup>
                          </CommandList>
                        </Command>
                      </PopoverContent>
                    </Popover>
                  </template>

                  <!-- Phone number input slot -->
                  <template
                    #input="{ inputValue, updateInputValue, placeholder }"
                  >
                    <Input
                      ref="phoneInput"
                      class="!bg-background border-input-border focus-visible:border-input-border border-s-none h-[50px] rounded-sm rounded-s-none border p-3 placeholder:text-[12px] focus-visible:ring-0"
                      type="text"
                      v-bind="componentField"
                      :model-value="inputValue"
                      :placeholder="placeholder"
                      style="unicode-bidi: plaintext"
                      @input="updateInputValue"
                    />
                  </template>
                </PhoneInput>
              </ClientOnly>
            </FormControl>
            <div class="text-destructive min-h-[20px] !text-sm">
              <FormMessage />
            </div>
          </FormItem>
        </FormField>
      </div>

      <!-- Second Row -->
      <div class="flex w-full flex-col gap-4">
        <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-[50px] rounded-sm border p-3 placeholder:text-[12px] focus-visible:ring-0"
                v-bind="componentField"
                placeholder="email@example.com"
              />
            </FormControl>
            <div class="text-destructive min-h-[20px] !text-sm">
              <FormMessage />
            </div>
          </FormItem>
        </FormField>

        <FormField
          v-slot="{ componentField }"
          name="service_id"
          :validate-on-blur="true"
          :validate-on-input="false"
        >
          <FormItem>
            <FormLabel class="text-primary capitalize">{{
              $t("labels.service_label")
            }}</FormLabel>
            <FormControl>
              <Select v-bind="componentField">
                <SelectTrigger
                  :aria-label="$t('ariaLabels.services')"
                  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.service')"
                  />
                </SelectTrigger>
                <SelectContent
                  class="!bg-background border-input-border rounded-sm"
                >
                  <SelectItem
                    v-for="service in services"
                    :key="service.id"
                    :value="service.id"
                    >{{ service.title }}
                  </SelectItem>
                </SelectContent>
              </Select>
            </FormControl>
            <div class="text-destructive min-h-[20px] !text-sm">
              <FormMessage />
            </div>
          </FormItem>
        </FormField>
      </div>

      <!-- Third Row -->

      <FormField
        v-slot="{ componentField }"
        name="type"
        :validate-on-blur="true"
        :validate-on-input="false"
      >
        <FormItem>
          <FormControl>
            <div class="flex gap-3">
              <RadioInput
                id="individual"
                value="individual"
                :text="t('step1.individual')"
                v-bind="componentField"
                :icon="Individual"
              />

              <RadioInput
                id="company"
                value="company"
                :text="t('step1.corporation')"
                v-bind="componentField"
                :icon="Campony"
              />
            </div>
          </FormControl>
          <div class="text-destructive min-h-[20px] !text-sm">
            <FormMessage />
          </div>
        </FormItem>
      </FormField>
    </form>
    <br />
    <div class="flex w-[100%] justify-between">
      <Button
        :disabled="loading"
        @click="throttledSubmit($event)"
        variant="wsDefault"
        size="wsDefault"
        class="cursor-pointer"
      >
        <span v-if="loading">{{ $t("buttons.loading_send_button") }}</span>
        <span v-else>{{ $t("buttons.start_button") }}</span>
      </Button>
    </div>
  </div>
</template>
