import type { GenericResponse } from "~/types";
import type { AddressesList } from "~/types/checkout";
import { validation } from "../utils/validation";
import { REGEX_PHONE } from "../utils/regex";

export const useCheckoutStore = defineStore("checkoutStore", () => {
  const { $toast } = useNuxtApp();

  const addressesList = ref<AddressesList[]>();
  const activeAddress = ref<AddressesList | null>();
  async function restrictedAddress() {
    try {
      // const { data } = await useMyFetch<GenericResponse<object>>(
      //   `/api/restricted/user/addresses`,
      //   {
      //     headers: {
      //       "Content-Type": "application/json",
      //     },
      //     onErrorOccured: async (_, status) => {
      //       throw createError({
      //         statusCode: status,
      //         statusMessage: `HTTP error: ${status}`,
      //       });
      //     },
      //   }
      // );

      const data = [
        {
          address: {
            city: "Bochnia",
            country_iso: "pl",
            name: "John",
            postcode: "32-700",
            street: "Karosek",
            surname: "Kornelsky",
          },
          address_id: 2,
          alias: "home",
          customer_id: 4,
          is_default: true,
          is_official: false,
        },
      ];

      addressesList.value = data;
      activeAddress.value = addressesList.value[0];
    } catch (error) {
      console.error("restrictedAddress error:", error);
    }
  }

  const userName = ref("");
  const lastName = ref("");
  const address = ref("");
  const postCode = ref("");
  const city = ref("");
  const country = ref("");
  const phoneNumber = ref("");
  const accountPhoneNumber = ref("");
  async function restrictedAddressOfficial() {
    try {
      // const { data } = await useMyFetch<GenericResponse<object>>(
      //   `/api/restricted/user/address/official`,
      //   {
      //     headers: {
      //       "Content-Type": "application/json",
      //     },
      //     onErrorOccured: async (_, status) => {
      //       throw createError({
      //         statusCode: status,
      //         statusMessage: `HTTP error: ${status}`,
      //       });
      //     },
      //   }
      // );

      const data = {
        address: {
          city: "Bochnia",
          country_iso: "pl",
          name: "John",
          postcode: "32-700",
          street: "Karosek",
          surname: "Kornelsky",
        },
        address_id: 2,
        alias: "home",
        customer_id: 4,
        is_default: true,
        is_official: false,
      };

      userName.value = data.address.name;
      lastName.value = data.address.surname;
      address.value = data.address.street;
      postCode.value = data.address.postcode;
      city.value = data.address.city;
      country.value = data.address.country_iso;
      // resolve this
      // accountPhoneNumber.value = useUserStore().fullUserData.phone_number;
      phoneNumber.value = "+36 789 3773 737";
    } catch (error) {
      console.error("restrictedAddressOfficial error:", error);
    }
  }

  const vNewAddressName = ref("");
  const vNewAddressSurname = ref("");
  const vNewAddressAddress = ref("");
  const vNewAddressCode = ref("");
  const vNewAddressCity = ref("");
  const vNewAddressCountry = ref("");
  const vUseAccountPhoneNumber = ref(false);
  const isOpen = ref<boolean>(false);
  async function uploadAddress() {
    try {
      const res = await useMyFetch<GenericResponse<object>>(
        `/api/restricted/user/address/official`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            address: {
              city: vNewAddressCity.value,
              // country_iso: vNewAddressCountry.value?.iso_code,
              name: vNewAddressName.value,
              postcode: vNewAddressCode.value,
              street: vNewAddressAddress.value,
              surname: vNewAddressSurname.value,
            },
          }),
          onErrorOccured: async (_, status) => {
            throw createError({
              statusCode: status,
              statusMessage: `HTTP error: ${status}`,
            });
          },
        }
      );

      if (res.status === 200) {
        $toast.success("Address successfully added", {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        });
        isOpen.value = false;
        restrictedAddress();
      } else {
        $toast.error("Failed to add address. Please try again.", {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        });
      }
    } catch (error) {
      console.error("uploadAddress error:", error);
    }
  }

  const currentPrefix = ref<string | number>("+43");
  const changePrefix = (item: any) => {
    currentPrefix.value = item;
  };
  const phoneValidation = ref<boolean | null>(null);
  async function sendForm() {
    let phoneNum = `${currentPrefix.value}${phoneNumber.value}`
      .replaceAll(" ", "")
      .trim();
    // if (vUseAccountPhoneNumber.value) {
    //   phoneNum = phoneNumber.value;
    // }

    phoneValidation.value = validation(phoneNum, 1, 49, REGEX_PHONE);
    try {
      const res = await useMyFetch<GenericResponse<object>>(
        `restricted/cart/checkout/delivery`,
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            address: {
              city: activeAddress.value?.address.city,
              country_iso: activeAddress.value?.address.country_iso,
              name: activeAddress.value?.address.name,
              postcode: activeAddress.value?.address.postcode,
              street: activeAddress.value?.address.street,
              surname: activeAddress.value?.address.surname,
            },
            phone_number: phoneNum,
            // email: useUserStore().fullUserData.email,
          }),
          onErrorOccured: async (_, status) => {
            throw createError({
              statusCode: status,
              statusMessage: `HTTP error: ${status}`,
            });
          },
        }
      );

      if (res.status === 200) {
        $toast.success("Form successfully sent", {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        });
        // redirectToSummary();
      } else {
        $toast.error("Failed to send form. Please try again.", {
          autoClose: 5000,
          dangerouslyHTMLString: true,
        });
      }
    } catch (error) {
      console.error("uploadAddress error:", error);
    }
  }

  const changeActive = (item: any) => {
    activeAddress.value = item;
  };

  return {
    addressesList,
    activeAddress,
    isOpen,

    userName,
    lastName,
    address,
    postCode,
    city,
    country,
    phoneNumber,
    accountPhoneNumber,
    vUseAccountPhoneNumber,

    currentPrefix,
    vNewAddressName,
    vNewAddressSurname,
    vNewAddressAddress,
    vNewAddressCode,
    vNewAddressCity,
    vNewAddressCountry,

    restrictedAddress,
    restrictedAddressOfficial,
    changeActive,
    uploadAddress,
    sendForm,
  };
});
