'use client'

import Layout from '@/hoc/Layout'
import { NextPage } from 'next'
import {
    Breadcrumb,
    BreadcrumbItem,
    BreadcrumbLink,
    BreadcrumbList,
    BreadcrumbPage,
    BreadcrumbSeparator,
} from '@/components/ui/breadcrumb'
import BrandIntro from '../components/BrandIntro'
import BrandFilters from '../components/BrandFilters'
import BrandSorts from '../components/BrandSorts'
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 { useInfiniteBrandProductsData } from '../hooks/useInfiniteBrandData'
import { IProduct } from '@/types/landing.types'
import { Product } from '../types/Types'
import { useSearchParams, useParams } from 'next/navigation'

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

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

    // خواندن پارامترها از URL
    useEffect(() => {
        const urlParams = {
            page: parseInt(searchParams.get('page') || '1'),
            limit: parseInt(searchParams.get('limit') || '20'),
            sort: parseInt(searchParams.get('sort') || '3'),
            category: searchParams.get('category') || undefined,
            minPrice: searchParams.get('minPrice') ? Number(searchParams.get('minPrice')) : undefined,
            maxPrice: searchParams.get('maxPrice') ? Number(searchParams.get('maxPrice')) : undefined,
        }
        setFilterParams(urlParams)
    }, [searchParams])

    // دریافت داده‌های محصولات از API بر اساس brandId با infinite scroll
    const {
        data,
        isLoading,
        error,
        fetchNextPage,
        hasNextPage
    } = useInfiniteBrandProductsData(brandId, 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-1.5">
            {/* معرفی برند */}
            {data?.pages?.[0]?.results.brand && (
                <BrandIntro brand={data.pages[0].results.brand} />
            )}

            <div className=' 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.brand && (
                            <>
                                <BreadcrumbSeparator className="text-muted-foreground select-none">/</BreadcrumbSeparator>
                                <BreadcrumbItem>
                                    <BreadcrumbPage className="text-foreground">
                                        {data.pages[0].results.brand.title_fa}
                                    </BreadcrumbPage>
                                </BreadcrumbItem>
                            </>
                        )}
                    </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 */}
                    <BrandFilters brandId={brandId} />

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

                    <div className='flex-1'>
                        <BrandSorts 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: 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>

            {/* Breadcrumb */}

        </div>
    )
}

export default function BrandPageWithLayout() {
    return (
        <Layout>
            <BrandPage />
        </Layout>
    )
}