import axios from "axios";
import type { FiltersProductsInterface } from "./interfaces/filters_products.interface";
import type { ProductInterface, Products } from "./interfaces/products.interface";

export const useProductsStore = defineStore("products_store", () => {
    const runtimeConfig = useRuntimeConfig();
    const route = useRoute();
    const products = ref<Products>({ products: [], total: 0, page: 1, last_page: 1 });
    const product = ref<ProductInterface>(null);
    const active_img = ref<string>('');

    const filters = ref<FiltersProductsInterface>({
        search: '',
        min_price: '0',
        max_price: null,
        limit: '10',
        page: '1',
        category: null,
        type_id: null,
        order: null,
    });

    const getProducts = async (filters_tmp: FiltersProductsInterface): Promise<Products> => {
        try {

            const list_products = await axios.get<Products>(`${runtimeConfig.public.api_url}/api/product`, {
                params: { ...filters_tmp, page: filters.value.page, limit: filters.value.limit },
            })

            if (list_products.data) {
                products.value = list_products.data;
                return list_products.data;
            } else {
                return {
                    products: [],
                    total: 0,
                    page: 1,
                    last_page: 1,
                }
            }

        } catch (error) {
            return {
                products: [],
                total: 0,
                page: 1,
                last_page: 1,
            }
        }
    }

    const getProduct = async (product_id: number): Promise<ProductInterface> => {
        try {
            const access_token = useCookie('access_token').value || '';

            const product_tmp = await axios.get<ProductInterface>(`${runtimeConfig.public.api_url}/api/product/${product_id}`, {
                headers: {
                    Authorization: `Bearer ${access_token}`
                }
            });

            if(product_tmp.data) {
                product.value = product_tmp.data
                active_img.value = product_tmp.data.photos[0].small_size_url;
                return product_tmp.data;
            } else {
                return null;
            }

        } catch (error) {
            return null;
        }
    }

    // filteredProducts
    const filteredProducts = computed(() => {
        if (route.query.min_price && route.query.max_price) {
            return products.value.products.filter(
                (p) =>
                    Number(p.price) >= Number(route.query.min_price) &&
                    Number(p.price) <= Number(route.query.max_price)
            );
        } else {
            return products.value.products;
        }
    });

    const getQueryParams = () => {
        const new_filters = { ...filters.value };

        delete new_filters.limit

        if (new_filters.page == '1') {
            delete new_filters.page;
        }

        if (Number(new_filters.min_price) == 0) {
            delete new_filters.min_price;
        }

        Object.keys(new_filters).forEach(key => {
            if (new_filters[key] === null || new_filters[key] === undefined || new_filters[key] === '') {
                delete new_filters[key];
            }
        });
        return new_filters;
    }

    const handleImageActive = (img: string) => {
        active_img.value = img;
      };


    /** -------  FILTROS ------  **/

    const resetFilters = () => {
        filters.value = {
            search: filters.value.search,
            limit: '10',
            page: '1',
            category: null,
            max_price: null,
            min_price: '0',
            type_id: null,
            order: null,
        }
    }

    const max_product_price = computed(() => {
        return products.value.products.reduce((max, product) => {
            return Number(product.price) > max ? Number(product.price) : max;
        }, 0);
    })

    const price_values = ref([0, max_product_price.value]);


    const handlePriceChange = (value: number[]) => {
        price_values.value = value;
        filters.value.min_price = value[0].toString();
        filters.value.max_price = value[1].toString();
    };

    const handleSelectFilter = async (e: { value: string; text: string }) => {
        if(e.value != '') {
            filters.value.order = e.value;
        } else {
            filters.value.order = null;
        }

        await getProducts(filters.value);

      }

    watch(max_product_price, (new_val) => {
        price_values.value = [Number(filters.value.min_price), new_val];
    })

    return {
        getProducts,
        getQueryParams,
        handlePriceChange,
        resetFilters,
        handleSelectFilter,
        getProduct,
        handleImageActive,
        filteredProducts,
        products,
        filters,
        price_values,
        max_product_price,
        product,
        active_img,
    }
})