'use client'
import React, { useMemo } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowLeft } from 'iconsax-react'
import Image from 'next/image'
import { useGetFavorites } from './hooks/useFavoriteData'
import { useGetProducts } from '@/app/[name]/(Main)/hooks/useMenuData'
import { getPrimaryVariantId } from '@/app/[name]/(Main)/types/Types'
import MenuItem from '@/components/listview/MenuItem'
import MenuItemRenderer from '@/components/listview/MenuItemRenderer'
import VerticalScrollView from '@/components/listview/VerticalScrollView'
import type { Favorite } from './types/Types'
import type { Product, ProductCategory, ProductVariant } from '@/app/[name]/(Main)/types/Types'

function FavoritePage() {
    const router = useRouter()
    const { data: favoritesData, isLoading } = useGetFavorites()
    const { data: productsData } = useGetProducts()
    const menuProducts = useMemo(() => productsData?.data ?? [], [productsData?.data])
    const productById = useMemo(() => {
        const map: Record<string, Product> = {}
        for (const p of menuProducts) {
            map[p.id] = p
        }
        return map
    }, [menuProducts])

    const favorites = useMemo(() => {
        return favoritesData?.data || []
    }, [favoritesData?.data])

    const productItems = useMemo(() => {
        return favorites.map((favorite: Favorite) => {
            const favProduct = favorite.product
            const menuProduct = productById[favProduct.id]
            if (menuProduct) {
                return { product: menuProduct, variantId: getPrimaryVariantId(menuProduct) }
            }
            const category: ProductCategory = {
                id: favProduct.category,
                createdAt: '',
                updatedAt: '',
                deletedAt: null,
                parent: null,
                title: '',
                isActive: true,
                shop: favProduct.shop,
                avatarUrl: '',
                order: 0,
            }
            const singleVariant: ProductVariant = {
                id: favProduct.id,
                createdAt: favProduct.createdAt,
                updatedAt: favProduct.updatedAt,
                deletedAt: favProduct.deletedAt,
                product: favProduct.id,
                value: '',
                price: favProduct.price ?? 0,
            }
            const product: Product = {
                id: favProduct.id,
                createdAt: favProduct.createdAt,
                updatedAt: favProduct.updatedAt,
                deletedAt: favProduct.deletedAt,
                shop: favProduct.shop,
                category,
                attribute: favProduct.attribute ?? '',
                title: favProduct.title,
                desc: favProduct.desc,
                price: favProduct.price,
                order: favProduct.order ?? 0,
                isActive: favProduct.isActive,
                images: favProduct.images,
                score: favProduct.score,
                discount: favProduct.discount,
                isSpecialOffer: favProduct.isSpecialOffer,
                name: favProduct.title,
                description: favProduct.desc,
                variants: [singleVariant],
            }
            return { product, variantId: favProduct.id }
        })
    }, [favorites, productById])

    return (
        <div className='overflow-y-auto h-full noscrollbar flex flex-col'>
            <div className='grid grid-cols-3 items-center'>
                <span></span>
                <h1 className='text-sm2 place-self-center font-medium'>علاقه‌مندی‌ها</h1>
                <ArrowLeft
                    className='cursor-pointer place-self-end'
                    size='24'
                    color='currentColor'
                    onClick={() => { router.back() }}
                />
            </div>

            <div className="mt-8 flex-1 h-full">
                {isLoading ? (
                    <div className='flex flex-col items-center justify-center gap-2 py-12 text-sm2 text-muted-foreground'>
                        <span className='h-4 w-4 animate-spin rounded-full border border-dashed border-foreground border-t-transparent'></span>
                        <p>در حال دریافت علاقه‌مندی‌ها...</p>
                    </div>
                ) : productItems.length === 0 ? (
                    <div className='flex flex-col items-center justify-center gap-4 h-full'>
                        <Image
                            src='/assets/images/favorite.png'
                            alt='favorite'
                            width={120}
                            height={120}
                            className='object-contain'
                        />
                        <div className='flex flex-col items-center gap-2 text-sm2 text-muted-foreground'>
                            <p>شما هیچ مورد علاقه‌مندی ثبت نکرده‌اید</p>
                            <p className='text-xs'>
                                برای افزودن کالا به علاقه‌مندی‌ها، به صفحه جزئیات کالا بروید
                            </p>
                        </div>
                    </div>
                ) : (
                    <VerticalScrollView className="overflow-y-auto h-full">
                        {productItems.map(({ product, variantId }) => (
                            <MenuItemRenderer key={product.id}>
                                <MenuItem product={product} variantId={variantId} />
                            </MenuItemRenderer>
                        ))}
                    </VerticalScrollView>
                )}
            </div>
        </div>
    )
}

export default FavoritePage