'use client'

import Layout from '@/hoc/Layout'
import { NextPage } from 'next'
import {
    Breadcrumb,
    BreadcrumbItem,
    BreadcrumbLink,
    BreadcrumbList,
    BreadcrumbPage,
    BreadcrumbSeparator,
} from '@/components/ui/breadcrumb'
import Filters from '../components/Filters'
import Sorts from '../components/Sorts'
import GridWrapper from '@/components/GridWrapper'
import ProductCard from '@/components/ProductCard'
import { Setting5 } from 'iconsax-react'
import { useState, useEffect, useMemo } from 'react'
import InfiniteScroll from 'react-infinite-scroll-component'
import { useInfiniteCategoryProductsData } from '../hooks/useInfiniteProductsData'
import { IProduct } from '@/types/landing.types'
import { Product } from '@/types/products.types'
import { useSearchParams, useParams } from 'next/navigation'

const Products: NextPage = () => {
    const [showMobileFilters, setShowMobileFilters] = useState(false)
    const searchParams = useSearchParams()
    const params = useParams()
    const [filterParams, setFilterParams] = useState({
        page: 1,
        limit: 20,
        sort: '3'
    })

    // استخراج categoryUrl از URL
    const categoryUrl = params.id as string

    // خواندن پارامترها از URL
    useEffect(() => {
        const params = {
            page: parseInt(searchParams.get('page') || '1'),
            limit: parseInt(searchParams.get('limit') || '20'),
            sort: searchParams.get('sort') || '3',
            category: searchParams.get('category') || undefined,
            brand: searchParams.get('brand') || undefined,
            minPrice: searchParams.get('minPrice') ? Number(searchParams.get('minPrice')) : undefined,
            maxPrice: searchParams.get('maxPrice') ? Number(searchParams.get('maxPrice')) : undefined,
            stock: searchParams.get('stock') || undefined,
            wholeSale: searchParams.get('wholeSale') || undefined,
            rating: searchParams.get('rating') ? Number(searchParams.get('rating')) : undefined,
            attributes: searchParams.get('attributes')?.split(',').filter(Boolean) || undefined,
            sizes: searchParams.get('sizes')?.split(',').filter(Boolean).map(Number) || undefined,
            meterages: searchParams.get('meterages')?.split(',').filter(Boolean).map(Number) || undefined,
        }
        setFilterParams(params)
    }, [searchParams])

    // دریافت داده‌های محصولات از API بر اساس categoryUrl با infinite scroll
    const {
        data,
        isLoading,
        error,
        fetchNextPage,
        hasNextPage
    } = useInfiniteCategoryProductsData(categoryUrl, filterParams)

    // جمع‌آوری تمام محصولات از صفحات مختلف
    const allProducts = useMemo(() => {
        if (!data?.pages) return [];
        return data.pages.flatMap(page => page.results.products);
    }, [data?.pages]);

    // تبدیل Product به IProduct
    const convertToIProduct = (product: Product): IProduct => {
        // اطمینان از وجود default_variant
        const defaultVariant = product.default_variant || product.variants?.[0];
        const price = defaultVariant?.price || {
            order_limit: 1,
            retailPrice: 0,
            is_specialSale: false,
            discount_percent: 0,
            specialSale_order_limit: null,
            specialSale_quantity: null,
            specialSale_endDate: null,
            selling_price: 0
        };

        return {
            _id: product._id,
            title_fa: product.title_fa,
            title_en: product.title_en,
            seoTitle: product.seoTitle || null,
            seoDescription: product.seoDescription || null,
            model: '',
            description: product.description,
            tags: product.tags || [],
            shop: defaultVariant?.shop || {
                _id: '',
                shopName: '',
                shopDescription: '',
                logo: ''
            },
            status: defaultVariant?.market_status || 'active',
            imagesUrl: product.imagesUrl,
            url: product.url,
            isWishlist: false,
            default_variant: {
                _id: defaultVariant?._id || product._id.toString(),
                market_status: defaultVariant?.market_status || 'active',
                price: price,
                stock: defaultVariant?.stock || 0,
                isFreeShip: defaultVariant?.isFreeShip || false,
                isWholeSale: defaultVariant?.isWholeSale || false
            },
            variants: (product.variants || []).map(variant => ({
                ...variant,
                market_status: variant.market_status as "Marketable" | "Unmarketable" | "OutOfStock",
                shipmentMethod: variant.shipmentMethod.map(method => ({
                    ...method,
                    deliveryType: method.deliveryType as "Standard" | "SameDay" | "Express"
                }))
            }))
        };
    }

    return (
        <div className="mt-14 px-4 sm:px-6 md:px-8 lg:px-20">
            <Breadcrumb aria-label="breadcrumb">
                <BreadcrumbList className="text-sm text-muted-foreground">
                    <BreadcrumbItem>
                        <BreadcrumbLink href="/">فروشگاه آناهیتا</BreadcrumbLink>
                    </BreadcrumbItem>
                    {data?.pages?.[0]?.results.breadcrumb?.map((item, index) => (
                        <div key={item._id} className="flex items-center">
                            <BreadcrumbSeparator className="text-muted-foreground select-none">/</BreadcrumbSeparator>
                            <BreadcrumbItem>
                                {index === (data?.pages?.[0]?.results.breadcrumb?.length || 0) - 1 ? (
                                    <BreadcrumbPage className="text-foreground">
                                        {item.title_fa}
                                    </BreadcrumbPage>
                                ) : (
                                    <BreadcrumbLink href={`/category/${item.title_en}`}>
                                        {item.title_fa}
                                    </BreadcrumbLink>
                                )}
                            </BreadcrumbItem>
                        </div>
                    ))}
                </BreadcrumbList>
            </Breadcrumb>

            {/* Mobile Filter Button */}
            <div className='lg:hidden mt-4 flex justify-between items-center'>
                <button
                    onClick={() => setShowMobileFilters(true)}
                    className='flex items-center gap-2 px-3 py-2 border border-border rounded-lg bg-white shadow-sm'
                >
                    <Setting5 size={18} color='#666666' />
                    <span className='text-sm text-[#666666]'>فیلترها</span>
                </button>
            </div>

            <div className='mt-6 sm:mt-8 md:mt-12 lg:mt-8 flex flex-col lg:flex-row gap-4 sm:gap-6'>
                {/* Desktop Filters */}
                <Filters categoryUrl={categoryUrl} />

                {/* Mobile Filters Modal */}
                <Filters
                    isMobile={true}
                    isOpen={showMobileFilters}
                    onClose={() => setShowMobileFilters(false)}
                    categoryUrl={categoryUrl}
                />

                <div className='flex-1'>
                    <Sorts data={data?.pages?.[0]} />

                    <div className='mt-6 sm:mt-8 md:mt-10'>
                        {isLoading ? (
                            <div className="text-center py-8">
                                <div className="text-gray-500">در حال بارگذاری...</div>
                            </div>
                        ) : error ? (
                            <div className="text-center py-8">
                                <div className="text-red-500">خطا در بارگذاری محصولات</div>
                            </div>
                        ) : allProducts.length > 0 ? (
                            <InfiniteScroll
                                dataLength={allProducts.length}
                                next={fetchNextPage}
                                hasMore={!!hasNextPage}
                                loader={
                                    <div className="text-center py-4">
                                        <div className="text-gray-500">در حال بارگذاری محصولات بیشتر...</div>
                                    </div>
                                }
                                endMessage={
                                    <div className="text-center py-4">
                                        {/* <div className="text-gray-500">تمام محصولات بارگذاری شد</div> */}
                                    </div>
                                }
                            >
                                <GridWrapper desktop={4} mobile={2} gapMobile={3} gapDesktop={6}>
                                    {allProducts.map((product) => (
                                        <ProductCard
                                            key={product._id}
                                            item={convertToIProduct(product)}
                                        />
                                    ))}
                                </GridWrapper>
                            </InfiniteScroll>
                        ) : (
                            <div className="text-center py-8">
                                <div className="text-gray-500">محصولی یافت نشد</div>
                            </div>
                        )}
                    </div>

                </div>
            </div>
        </div>
    )
}

export default function ProductsWithLayout() {
    return (
        <Layout>
            <Products />
        </Layout>
    )
}