'use client'
import { Star1 } from 'iconsax-react'
import { FC, useEffect } from 'react'
import { Product } from '@/types/product.types'
import Image from 'next/image'
import { clx } from '@/helpers/utils'
import { useProductStore } from '../store/Store'

interface BaseInformationProps {
    product: Product
    stats: {
        commentsCount: number;
        averageRate: number;
    }
}

const BaseInformation: FC<BaseInformationProps> = ({ product, stats }) => {

    const { setVariantId, variantId } = useProductStore()

    const brand = product.brand

    const descriptionSource =
        product.metaDescription || product.seoDescription || product.description

    const shortDescription =
        descriptionSource && descriptionSource.length > 160
            ? `${descriptionSource.slice(0, 160)}...`
            : descriptionSource

    // محاسبه میانگین امتیاز و تعداد دیدگاه‌ها


    // تابع برای انتخاب variant
    const handleVariantSelect = (variantId: string) => {
        setVariantId(variantId)
    }

    // انتخاب اولین variant به صورت پیش‌فرض
    useEffect(() => {
        if (product.variants.length > 0 && !variantId) {
            setVariantId(product.variants[0]._id)
        }
    }, [product.variants, variantId, setVariantId])

    return (
        <div className='flex-1'>
            <h1 className='text-base sm:text-lg text-[#191919] leading-relaxed'>
                {product.title_fa}
            </h1>

            <p className='mt-4 sm:mt-6 text-[#B2B2B2] text-xs sm:text-sm'>
                {product.title_en}
            </p>

            <div className='mt-4 flex flex-wrap gap-2 sm:gap-4 items-center'>
                <h3 className='text-primary text-sm sm:text-base'>
                    {brand.title_fa}
                </h3>
                <div className='size-1.5 rounded-full bg-[#E5E5E5]'></div>
                <button
                    onClick={() => {
                        const reviewsSection = document.getElementById('reviews-section')
                        reviewsSection?.scrollIntoView({ behavior: 'smooth', block: 'start' })
                    }}
                    className='flex items-center gap-1 hover:opacity-80 transition-opacity cursor-pointer'
                >
                    <Star1 size={16} color='#FFC107' variant='Bold' className='sm:w-5 sm:h-5' />
                    <span className='text-xs sm:text-sm'>
                        {stats.commentsCount > 0 ? `${stats.averageRate} امتیاز` : '۰ امتیاز'}
                    </span>
                </button>
                <div className='size-1.5 rounded-full bg-[#E5E5E5]'></div>
                <button
                    onClick={() => {
                        const reviewsSection = document.getElementById('reviews-section')
                        reviewsSection?.scrollIntoView({ behavior: 'smooth', block: 'start' })
                    }}
                    className='text-primary text-xs sm:text-sm hover:underline'
                >
                    {stats.commentsCount} دیدگاه
                </button>
            </div>

            {/* نمایش variant ها */}
            {(() => {
                if (product.variants.length === 0) return null

                const hasMeterage = product.variants.some(v => v.meterage)
                const hasColor = product.variants.some(v => v.color)
                const hasSize = product.variants.some(v => v.size)
                const hasThemeValue = product.variants.some(v => v.themeValue)
                const hasAnySpecificField = hasMeterage || hasColor || hasSize || hasThemeValue

                // اگر فقط یک variant وجود دارد و هیچ فیلد خاصی ندارد، نمایش نده
                if (product.variants.length === 1 && !hasAnySpecificField) {
                    return null
                }

                return (
                    <div className='mt-4 sm:mt-6 flex gap-4 flex-wrap'>
                        {/* بررسی وجود فیلدهای خاص در variant ها */}
                        {(() => {
                            // اگر هیچ فیلد خاصی وجود نداشت، نمایش عمومی
                            if (!hasAnySpecificField) {
                                return (
                                    <div className='flex flex-wrap items-center gap-1.5'>
                                        {product.variants.map((variant, index) => {
                                            const isSelected = variantId === variant._id
                                            return (
                                                <button
                                                    key={variant._id}
                                                    onClick={() => handleVariantSelect(variant._id)}
                                                    className={`text-[13px] px-4 py-2 border border-border rounded-lg whitespace-nowrap transition-colors ${isSelected
                                                        ? 'bg-primary text-white border-primary'
                                                        : 'hover:border-primary/50'
                                                        }`}
                                                >
                                                    گزینه {index + 1}
                                                </button>
                                            )
                                        })}
                                    </div>
                                )
                            }

                            // نمایش فیلدهای خاص
                            return (
                                <>
                                    {/* متراژ */}
                                    {hasMeterage && (
                                        <div className='flex flex-wrap items-center gap-1.5 mb-4'>
                                            {product.variants.map((variant) => {
                                                if (variant.meterage) {
                                                    const isSelected = variantId === variant._id
                                                    return (
                                                        <button
                                                            key={variant._id}
                                                            onClick={() => handleVariantSelect(variant._id)}
                                                            className={`text-[13px] px-4 py-2 border border-border rounded-lg whitespace-nowrap transition-colors ${isSelected
                                                                ? 'bg-primary text-white border-primary'
                                                                : 'hover:border-primary/50'
                                                                }`}
                                                        >
                                                            {variant.meterage.value}
                                                        </button>
                                                    )
                                                }
                                                return null
                                            })}
                                        </div>
                                    )}

                                    {/* رنگ ها */}
                                    {hasColor && (
                                        <div className='flex flex-wrap items-center gap-1.5 mb-4'>
                                            {product.variants.map((variant) => {
                                                if (variant.color) {
                                                    const isSelected = variantId === variant._id
                                                    return (
                                                        <button
                                                            key={variant._id}
                                                            onClick={() => handleVariantSelect(variant._id)}
                                                            className={clx(
                                                                'size-10 rounded-full flex justify-center items-center',
                                                                variant.color.hexColor === '#FFFFFF' ? 'border border-border' : ''
                                                            )}
                                                            style={{ backgroundColor: variant.color.hexColor }}
                                                        >
                                                            {isSelected && <Image src='/images/tick.svg' alt='check' width={20} height={20} className={clx(
                                                                'size-5',
                                                                variant.color.hexColor === '#FFFFFF' ? 'filterBlack' : ''
                                                            )} />}
                                                        </button>
                                                    )
                                                }
                                                return null
                                            })}
                                        </div>
                                    )}

                                    {/* سایزها */}
                                    {hasSize && (
                                        <div className='flex flex-wrap items-center gap-1.5 mb-4'>
                                            {product.variants.map((variant) => {
                                                if (variant.size) {
                                                    const isSelected = variantId === variant._id
                                                    return (
                                                        <button
                                                            key={variant._id}
                                                            onClick={() => handleVariantSelect(variant._id)}
                                                            className={`text-[13px] px-4 py-2 border border-border rounded-lg whitespace-nowrap transition-colors ${isSelected
                                                                ? 'bg-primary text-white border-primary'
                                                                : 'hover:border-primary/50'
                                                                }`}
                                                        >
                                                            {variant.size.value}
                                                        </button>
                                                    )
                                                }
                                                return null
                                            })}
                                        </div>
                                    )}

                                    {/* themeValue ها - نمایش داینامیک */}
                                    {hasThemeValue && (() => {
                                        // تابع برای تبدیل theme به string
                                        const getThemeKey = (theme: Record<string, unknown> | string | null): string => {
                                            if (typeof theme === 'string') return theme
                                            if (theme === null) return 'default'
                                            return JSON.stringify(theme)
                                        }

                                        // گروه‌بندی variant‌ها بر اساس theme
                                        const themeGroups = new Map<string, typeof product.variants>()

                                        product.variants.forEach(variant => {
                                            if (variant.themeValue) {
                                                const themeKey = getThemeKey(variant.themeValue.theme)
                                                if (!themeGroups.has(themeKey)) {
                                                    themeGroups.set(themeKey, [])
                                                }
                                                themeGroups.get(themeKey)!.push(variant)
                                            }
                                        })

                                        // تابع برای بررسی hex بودن value
                                        const isHexColor = (value: string | number): boolean => {
                                            if (typeof value !== 'string') return false
                                            const hexPattern = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/
                                            return hexPattern.test(value)
                                        }

                                        return Array.from(themeGroups.entries()).map(([theme, variants]) => (
                                            <div key={theme} className='flex flex-wrap items-center gap-1.5 mb-4'>
                                                {variants.map((variant) => {
                                                    if (variant.themeValue) {
                                                        const isSelected = variantId === variant._id
                                                        const value = typeof variant.themeValue.value === 'string'
                                                            ? variant.themeValue.value
                                                            : String(variant.themeValue.value)
                                                        const isHex = isHexColor(value)

                                                        // اگر hex بود، دایره رنگی نمایش بده
                                                        if (isHex) {
                                                            return (
                                                                <button
                                                                    key={variant._id}
                                                                    onClick={() => handleVariantSelect(variant._id)}
                                                                    className={clx(
                                                                        'size-10 rounded-full flex justify-center items-center',
                                                                        value === '#FFFFFF' ? 'border border-border' : ''
                                                                    )}
                                                                    style={{ backgroundColor: value }}
                                                                >
                                                                    {isSelected && <Image src='/images/tick.svg' alt='check' width={20} height={20} className={clx(
                                                                        'size-5',
                                                                        value === '#FFFFFF' ? 'filterBlack' : ''
                                                                    )} />}
                                                                </button>
                                                            )
                                                        }

                                                        // اگر hex نبود، name را نمایش بده
                                                        return (
                                                            <button
                                                                key={variant._id}
                                                                onClick={() => handleVariantSelect(variant._id)}
                                                                className={`text-[13px] px-4 py-2 border border-border rounded-lg whitespace-nowrap transition-colors ${isSelected
                                                                    ? 'bg-primary text-white border-primary'
                                                                    : 'hover:border-primary/50'
                                                                    }`}
                                                            >
                                                                {variant.themeValue.name}
                                                            </button>
                                                        )
                                                    }
                                                    return null
                                                })}
                                            </div>
                                        ))
                                    })()}
                                </>
                            )
                        })()}
                    </div>
                )
            })()}

            {
                product.tags.length > 0 ?
                    <div className='mt-6 sm:mt-7 text-base sm:text-lg text-[#333333]'>
                        ویژگی های کلیدی
                    </div>
                    : null
            }

            {product.tags.length === 0 && shortDescription && (
                <p className='mt-4 sm:mt-6 line-clamp-3 text-xs sm:text-sm text-[#4B4B4B] leading-7'>
                    {shortDescription}
                </p>
            )}

            <div className='mt-6  flex flex-wrap gap-4 sm:gap-4'>
                {product.tags.slice(0, 10).map((spec) => (
                    <div key={spec} className='px-5 h-10 bg-gray-50 text-gray-500 w-fit flex text-xs whitespace-nowrap items-center justify-center rounded-full'>
                        {spec}
                    </div>
                ))}
            </div>
        </div>
    )
}

export default BaseInformation