<script setup lang="ts">
// imports

import useCreateOrUpdateAddress, {
    type CreateOrUpdateAddressRequest,
} from "~/composables/api/account/useCreateOrUpdateAddress";
import useGetAccount from "~/composables/api/account/useGetAccount";
import { QUERY_KEYS } from "~/constants";
import { useToast } from "~/composables/global/useToast";

// types

type Props = {
    address?: Address;
    isShow: boolean;
};

type Emits = {
    "update:address": [value: File];
    "update:isShow": [value: boolean];
};

// props

const props = defineProps<Props>();

const { address, isShow } = toRefs(props);

// emits

const emit = defineEmits<Emits>();

// computed

const isEditing = computed(() => !!address.value);

// state

const { $queryClient: queryClient } = useNuxtApp();

const { addToast } = useToast();

const addressData = ref<CreateOrUpdateAddressRequest>({
    id: address.value?.id ?? undefined,
    province: address.value?.province ?? "",
    city: address.value?.city ?? "",
    postal_code: address.value?.postal_code ?? "",
    address: address.value?.address ?? "",
    name: address.value?.name ?? "",
    phone: address.value?.phone ?? "",
    for_me: !isEditing.value
        ? address.value?.for_me ?? "بله"
        : address.value?.for_me == true
        ? "بله"
        : "خیر",
});

// queries

const { data: account } = useGetAccount();

const {
    mutateAsync: createOrUpdateAddress,
    isPending: createAddressIsPending,
} = useCreateOrUpdateAddress(isEditing);

// computed

const visible = computed({
    get: () => isShow.value ?? false,
    set: (value: boolean) => emit("update:isShow", value),
});

// methods

const closeModal = () => {
    if (!isEditing.value) {
        addressData.value = {
            id: undefined,
            province: "",
            city: "",
            address: "",
            postal_code: "",
            name: "",
            phone: "",
            for_me: "بله",
        };
    }
};

const addNew = () => {
    createOrUpdateAddress(
        { ...addressData.value },
        {
            onSuccess: () => {
                queryClient.invalidateQueries({
                    queryKey: [QUERY_KEYS.addresses],
                });
                closeModal();
                addToast({
                    message: isEditing.value
                        ? "آدرس با موفقیت ویرایش شد"
                        : "آدرس با موفقیت اضافه شد",
                    options: {
                        status: "success",
                    },
                });
            },
            onError: () => {
                addToast({
                    message: isEditing.value
                        ? "آدرس با موفقیت ویرایش شد"
                        : "مشکلی در افزودن آدرس رخ داد",
                    options: {
                        status: "error",
                    },
                });
            },
        }
    );
};

watch(
    () => addressData.value.for_me,
    (newValue) => {
        if (!isEditing.value) {
            addressData.value.phone =
                newValue == "بله" ? account.value?.phone : "";
        }
    },
    {
        immediate: true,
        deep: true,
    }
);
</script>

<template>
    <Modal
        v-model="visible"
        :title="!!address ? 'ویرایش آدرس' : 'افزودن آدرس'"
        :icon="!!address ? 'bi:pen' : 'ci:plus'"
        :iconSize="!!address ? '20' : '32'"
        contectClass="!w-[70vw]"
        @close="closeModal"
    >
        <template #trigger>
            <Button
                :end-icon="!!address ? 'bi:pen' : 'ci:plus'"
                size="md"
                class="rounded-full"
            >
                <span class="font-bold whitespace-pre">
                    {{ !!address ? "ویرایش آدرس" : "افزودن آدرس" }}
                </span>
            </Button>
        </template>

        <template #content>
            <div class="flex-col-center gap-6 py-10" dir="rtl">
                <div
                    class="grid w-full grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3"
                >
                    <div class="flex flex-col gap-2">
                        <label
                            for="name"
                            class="text-xs font-semibold lg:text-sm text-gray-900"
                            >نام پیش فرض
                            <span class="text-sm text-red-500">*</span></label
                        >

                        <Input
                            id="name"
                            type="text"
                            placeholder="اینجا وارد کنید ..."
                            v-model="addressData.name!"
                        />
                    </div>

                    <div class="flex flex-col gap-2">
                        <label
                            for="province"
                            class="text-xs font-semibold lg:text-sm text-gray-900"
                            >آدرس شما؟
                            <span class="text-sm text-red-500">*</span></label
                        >

                        <Select
                            :options="['بله', 'خیر']"
                            placeholder="انتخاب کنید"
                            v-model="addressData.for_me as string"
                        />
                    </div>

                    <div class="flex flex-col gap-2">
                        <label
                            for="phone"
                            class="text-xs font-semibold lg:text-sm text-gray-900"
                            >شماره تلفن
                            <span class="text-sm text-red-500">*</span></label
                        >

                        <Input
                            id="phone"
                            type="text"
                            placeholder="اینجا وارد کنید ..."
                            v-model="addressData.phone!"
                        />
                    </div>

                    <div class="flex flex-col gap-2">
                        <label
                            for="province"
                            class="text-xs font-semibold lg:text-sm text-gray-900"
                            >استان
                            <span class="text-sm text-red-500">*</span>
                        </label>

                        <Input
                            id="province"
                            type="text"
                            placeholder="اینجا وارد کنید ..."
                            v-model="addressData.province!"
                        />
                    </div>

                    <div class="flex flex-col gap-2">
                        <label
                            for="city"
                            class="text-xs font-semibold lg:text-sm text-gray-900"
                            >شهر
                            <span class="text-sm text-red-500">*</span></label
                        >
                        <Input
                            id="city"
                            type="text"
                            placeholder="اینجا وارد کنید ..."
                            v-model="addressData.city!"
                        />
                    </div>

                    <div class="flex flex-col gap-2">
                        <label
                            for="post"
                            class="text-xs font-semibold lg:text-sm text-gray-900"
                            >کد پستی
                            <span class="text-sm text-red-500">*</span></label
                        >
                        <Input
                            id="post"
                            type="text"
                            placeholder="اینجا وارد کنید ..."
                            v-model="addressData.postal_code!"
                        />
                    </div>
                </div>

                <div class="flex flex-col w-full gap-2">
                    <label
                        for="address"
                        class="text-xs font-semibold lg:text-sm text-gray-900"
                        >آدرس کامل
                        <span class="text-sm text-red-500">*</span></label
                    >
                    <textarea
                        id="address"
                        placeholder="آدرس خود را بنویسید"
                        v-model="addressData.address"
                        class="flex items-center field-sizing-content resize-none bg-slate-50 border-slate-200 hover:border-black focus:border-black max-h-[10rem] text-black justify-between cursor-text transition-all border-[1.5px] gap-3 typo-label-md px-4 py-3.5 selection:bg-slate-100 rounded-100 outline-none flex-1 !text-sm placeholder-slate-400"
                    ></textarea>
                </div>
            </div>

            <div class="py-6 border-t border-slate-200 flex gap-3">
                <Button
                    :disabled="createAddressIsPending"
                    @click="addNew"
                    class="rounded-full px-10"
                >
                    <Icon
                        v-if="createAddressIsPending"
                        name="svg-spinners:3-dots-bounce"
                    />
                    <span v-else>ثبت</span>
                </Button>
                <DialogClose aria-label="Close">
                    <Button variant="outlined" class="rounded-full px-10">
                        انصراف
                    </Button>
                </DialogClose>
            </div>
        </template>
    </Modal>
</template>

<style scoped></style>
