import type {IProduct} from "@/types/product-d-t";
import type {IMenuItem} from "@/types/menu-d-t";
import type {IDropdownMenu} from "@/types/dropdown-menu-d-t";
import type {TCategory, TCategoryResponse} from "@/types/category-t";
import type {TBrand, TBrandResponse} from "@/types/brand-t";
import type {IUserOrder} from "@/types/user-order-d-t";
import type {IUserAddresses} from "@/types/user-addresses-d-t";
import type {IUserOrderResponse} from "@/types/user-order-response-d-t";
import type {IUserAddressesResponse} from "@/types/user-addresses-response-d-t";
import type {ICartItem} from "@/types/cart-item-d-t";
import {useLocaleStore} from "@/pinia/useLocaleStore";

const idKey = ["slug", "sku"];

export function getColumnValueByLocale(
    obj: IProduct | any = {},
    {column, locale, $default}: {
        column: string,
        locale?: string,
        $default?: any
    } = {
        column: "name",
    }
) {
    locale = locale || useLocaleStore().locale();
    let column_name = `${locale}_${column}`;

    $default = $default === undefined ? obj?.[column] : $default;
    return obj?.[column_name] || $default;
}

export function getImageUrlValue(
    obj: IProduct | any = {},
    {prop, arrProp, defaultValue, parse}: {
        prop?: string,
        arrProp?: string,
        defaultValue?: string,
        parse?: boolean
    } = {
        prop: "imageUrl",
        arrProp: 'images',
        defaultValue: "",
        parse: true
    }
) {
    // @ts-ignore
    let r = obj?.[prop] || obj?.[arrProp]?.[0];

    return parse ? parseImageUrl(r) : r;
}

export function parseImageUrl(url = "", baseUrl = "") {
    baseUrl = baseUrl || "";
    baseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
    url = url.startsWith('/') ? url.slice(1) : url;

    // console.log(34, url, baseUrl, baseUrl + url);
    if (url) {
        return url.startsWith('http') || url.startsWith('https') ? url : (baseUrl + url);
    }

    // @ts-ignore
    return useNuxtApp()?.$settings?.noImageUrl;
}

export function id(obj: any): string {
    let idx = idKey.find(key => obj.hasOwnProperty(key));
    return idx && idx in obj ?
        obj[idx] :
        (typeof obj === "string" ? obj : '');
}

export function parseId(obj: any, suffix: string = ''): string {
    return idKey.includes('id') ? `${id(obj)}-${encodeURIComponent(suffix)}` : id(obj);
}

export function parseIdDev(obj: any, suffix: string = ''): string {
    return `${obj?.id}-${encodeURIComponent(suffix)}`;
}

export function getIdFromSlugPrefix(slug: string = ''): string {
    return String(String(slug).split('-').shift());
}

export function getSlug(slug: string | number, {prefix = '', suffix = ''} = {}): string {
    // let value = String(String(slug).split('-').shift());
    let value = String(slug);
    return value ? `${prefix || ''}${value}${suffix || ''}` : '';
}

export function slugToTitleCase(slug: string): string {
    return String(slug)
        .replace(/-/g, ' ')           // Replace hyphens with spaces
        .replace(/_/g, ' ')           // Replace underscores with spaces (if any)
        .replace(/\b\w/g, (char) => char.toUpperCase()); // Capitalize the first letter of each word
}

export function parseMenuName(menu: IMenuItem | IDropdownMenu): string {
    return menu?.title || "";
}

export function parseCategoryName(category?: TCategory | TCategoryResponse, $default: string = ''): string {
    return category && (
        ("name" in category && category?.name) ||
        ("parentName" in category && category?.parentName) ||
        // @ts-ignore
        ("slug" in category && slugToTitleCase(category?.slug))
    ) || $default;
}

export function parseProductName(p: IProduct|ICartItem, addSuffix: boolean = false): string {
    let product: IProduct;
    // @ts-ignore
    if ("differents" in p && !Array.isArray(p?.differents?.data || p?.differents)) {
        product = p.differents as IProduct;
    } else {
        product = p as IProduct;
    }

    let suffix = '';
    if (addSuffix) {
        let suffixName = getColumnValueByLocale(product?.additionalInfo?.[0] || product?.different, {column: 'different', $default: product?.different || product?.additionalInfo?.[0]?.value})
        suffix = (suffixName || product?.additionalInfo?.[0]?.value || product?.different) || '';
        suffix = suffix ? ` - ${suffix}` : '';
    }

    return String(getColumnValueByLocale(product) || (product?.sku ? slugToTitleCase(product?.sku) : undefined) || product?.id || '') +
        suffix;
}

export function parseProductDifferent(product: IProduct): string {
    return String(product?.additionalInfo?.[0]?.value || '');
}

export function parseProductDescription(
    product: IProduct, cutter: {
        when?: (() => boolean);
        max_length: number;
        suffix: string;
    } | (() => boolean) = {
        when: undefined,
        max_length: 100,
        suffix: '...'
    }
): string {
    let description = product?.description || '';
    if (typeof cutter === 'function') {
        if (cutter()) {
            description = (description.substring(0, 100) + '...');
        }
    } else if (cutter?.when) {
        if (cutter?.when()) {
            description = (description.substring(0, cutter.max_length) + cutter.suffix);
        }
    }

    return normalizeLineEndingsToHtml(description);

    // return (
    // 		!textMore || textMore()
    // 				? product?.description
    // 				: `${product?.description.substring(0, 100)}...`
    // ).replace(/\n/g, '<br>')
}

export function parseBrandName(brand: TBrand | TBrandResponse): string {
    return String(brand?.name || brand?.id || '');
}

export function normalizeLineEndings(text: string): string {
    return text.replace(/\r\n/g, '\n');
}

export function normalizeLineEndingsToHtml(text?: string): string {
    return normalizeLineEndings(text || "").replace(/\n/g, '<br>');
}

export function gotoCategory(category: TCategory | TCategoryResponse): void {
    useRouter().push(getCategoryUrl(category));
}

export function gotoBrand(brand: TBrand | TBrandResponse): void {
    useRouter().push(getBrandUrl(brand));
}

export function gotoProduct(product: IProduct): void {
    useRouter().push(getProductUrl(product));
}

export function gotoOrder(order: IUserOrder): void {
    useRouter().push(getOrderUrl(order));
}

export function gotoUserAddress(obj: IUserAddresses): void {
    useRouter().push(getUserAddressUrl(obj));
}

export function getProductReviewUrl(product: IProduct): string {
    return `/products/${product.id}/reviews`;
}

export function getRelatedProductUrl(product: IProduct): string {
    return `/products/${parseId(product, product?.sku)}/related`;
}

export function getProductUrl(product: IProduct, addSuffix: boolean = false): string {
    let suffix = '';
    if (addSuffix) {
        suffix = product?.additionalInfo?.[0]?.value || product?.different || '';
        suffix = suffix ? `?different=${product?.id}&different_name=${suffix}` : '';
    }

    return `/product-details/${parseId(product, product?.sku)}${suffix}`;
}

export function getCategoryUrl(category: TCategory | TCategoryResponse): string {
    return `/category/${parseId(category, category?.slug)}`;
}

export function getBrandUrl(brand: TBrand | TBrandResponse): string {
    return `/brand/${parseId(brand, brand?.slug)}`;
}

export function getOrderUrl(order: IUserOrder | IUserOrderResponse): string {
    return `/order/${order?.id}`;
}

export function getInvoiceUrl(order: IUserOrder | IUserOrderResponse): string {
    return `/invoice/${order?.id}`;
}

export function getOrderUrlByStatus(order: IUserOrder | IUserOrderResponse): string {
    return order?.status !== 'done' ? getOrderUrl(order) : getInvoiceUrl(order);
}

export function getUserAddressUrl(obj: IUserAddresses | IUserAddressesResponse): string {
    return `/address/${obj?.id}`;
}

export function getDefaultNoImageUrl(): string {
    return useRuntimeConfig()?.public?.noImageUrl || "";
}

export function getApiUrl(): string {
    return useRuntimeConfig()?.public?.apiUrl || "";
}

export function getBaseUrl(): string {
    return useRuntimeConfig()?.public?.baseUrl || "";
}

export function getSiteTitle(): string {
    return useRuntimeConfig()?.public?.siteTitle || "";
}

export default {
    getImageUrlValue,
    parseImageUrl,
    id,
    parseId,
    parseIdDev,
    getIdFromSlugPrefix,
    getSlug,
    slugToTitleCase,
    parseMenuName,
    parseCategoryName,
    parseProductName,
    parseProductDifferent,
    parseProductDescription,
    parseBrandName,
    normalizeLineEndings,
    normalizeLineEndingsToHtml,
    gotoCategory,
    gotoBrand,
    gotoProduct,
    gotoOrder,
    gotoUserAddress,
    getProductReviewUrl,
    getRelatedProductUrl,
    getProductUrl,
    getCategoryUrl,
    getBrandUrl,
    getOrderUrl,
    getInvoiceUrl,
    getOrderUrlByStatus,
    getUserAddressUrl,
    getDefaultNoImageUrl,
    getApiUrl,
    getBaseUrl,
    getSiteTitle,
}