'use client'
import { FC, useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator'
import { Star1 } from 'iconsax-react'
import { Product } from '@/types/product.types'
import AddComment from './AddComment'
import { useGetProductComments } from '../hooks/useProductData'
import PageLoading from '@/components/PageLoading'
import moment from 'moment-jalaali'

interface ReviewsProps {
    product: Product
}

const Reviews: FC<ReviewsProps> = ({ product }) => {
    const { data: commentsData, isLoading } = useGetProductComments(product._id)
    const [sort, setSort] = useState<'new' | 'helpful'>('new')
    const [open, setOpen] = useState(false)

    const comments = useMemo(() => commentsData?.results?.comments || [], [commentsData?.results?.comments])

    const sortedComments = useMemo(() => {
        if (sort === 'new') {
            return [...comments].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
        }
        return [...comments].sort((a, b) => (b.status === 'approved' ? 1 : 0) - (a.status === 'approved' ? 1 : 0))
    }, [sort, comments])

    const approvedComments = useMemo(() => {
        return comments.filter(comment => comment.status === 'approved')
    }, [comments])

    const average = useMemo(() => {
        if (approvedComments.length === 0) return '0.0'
        const sum = approvedComments.reduce((acc, comment) => acc + comment.rate, 0)
        return (sum / approvedComments.length).toFixed(1)
    }, [approvedComments])

    if (isLoading) {
        return <PageLoading />
    }

    return (
        <div id="reviews-section" className="mt-12 sm:mt-16 w-full scroll-mt-20">
            <div className="flex items-center justify-end gap-3 flex-row-reverse">
                <h2 className="text-primary text-base sm:text-lg">نظرات خریداران</h2>
                <div className="w-1 h-6 bg-primary rounded"></div>
            </div>

            <div className="mt-4 sm:mt-6 grid grid-cols-12 gap-4 sm:gap-6">
                <div className="col-span-12 md:col-span-9 md:order-last">
                    <div className="flex flex-col sm:flex-row sm:items-center justify-start gap-2 sm:gap-4 text-xs sm:text-sm text-[#7F7F7F]">
                        <span>مرتب سازی بر اساس:</span>
                        <div className="flex items-center gap-4 sm:gap-6">
                            <button
                                type="button"
                                onClick={() => setSort('new')}
                                className={
                                    sort === 'new' ? 'text-primary font-medium' : 'text-[#B2B2B2] hover:text-primary'
                                }
                            >
                                جدیدترین
                            </button>
                            <button
                                type="button"
                                onClick={() => setSort('helpful')}
                                className={
                                    sort === 'helpful' ? 'text-primary font-medium' : 'text-[#B2B2B2] hover:text-primary'
                                }
                            >
                                مفیدترین
                            </button>
                        </div>
                    </div>

                    <div className="mt-4 sm:mt-6 rounded-xl bg-white">
                        {sortedComments.length > 0 ? (
                            sortedComments.map((comment, idx) => (
                                <div key={comment._id} className="px-4 sm:px-6 py-4 sm:py-5">
                                    <div className="flex flex-col sm:flex-row sm:items-center justify-start gap-2 sm:gap-3">
                                        <div className="px-2 py-0.5 rounded-full bg-[#02A55A] text-white text-xs w-fit">
                                            {comment.rate.toFixed(1)}
                                        </div>
                                        <div className="flex flex-wrap items-center gap-1 sm:gap-2 text-xs text-[#999999]">
                                            {comment.status === 'approved' && (
                                                <span className="px-2 py-0.5 rounded bg-[#F1F1F1] text-[#7F7F7F]">خریدار</span>
                                            )}
                                            <span className="size-1.5 rounded-full bg-[#E5E5E5]"></span>
                                            <span>{moment(comment.createdAt, 'jYYYY/jMM/jDD HH:mm:ss').format('jYYYY/jMM/jD')}</span>
                                            <span className="size-1.5 rounded-full bg-[#E5E5E5]"></span>
                                            <span>{comment.user.fullName}</span>
                                        </div>
                                    </div>

                                    {comment.title && (
                                        <div className="mt-2 text-[#333333] text-sm font-medium text-right">
                                            {comment.title}
                                        </div>
                                    )}

                                    {(comment.advantage && comment.advantage.length > 0) || (comment.disAdvantage && comment.disAdvantage.length > 0) ? (
                                        <div className="mt-4 grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
                                            {comment.advantage && comment.advantage.length > 0 && (
                                                <div className="bg-[#F0F9F4] rounded-lg p-3">
                                                    <div className="text-[#02A55A] text-xs sm:text-sm font-medium mb-2">نکات مثبت:</div>
                                                    <ul className="text-xs sm:text-sm text-[#02A55A] space-y-1.5">
                                                        {comment.advantage.map((item, index) => (
                                                            <li key={index} className="flex items-start gap-2 text-right">
                                                                <span className="text-[#02A55A] mt-0.5">•</span>
                                                                <span>{item}</span>
                                                            </li>
                                                        ))}
                                                    </ul>
                                                </div>
                                            )}

                                            {comment.disAdvantage && comment.disAdvantage.length > 0 && (
                                                <div className="bg-[#FEF2F2] rounded-lg p-3">
                                                    <div className="text-[#EF4444] text-xs sm:text-sm font-medium mb-2">نکات منفی:</div>
                                                    <ul className="text-xs sm:text-sm text-[#EF4444] space-y-1.5">
                                                        {comment.disAdvantage.map((item, index) => (
                                                            <li key={index} className="flex items-start gap-2 text-right">
                                                                <span className="text-[#EF4444] mt-0.5">•</span>
                                                                <span>{item}</span>
                                                            </li>
                                                        ))}
                                                    </ul>
                                                </div>
                                            )}
                                        </div>
                                    ) : null}

                                    <div className="mt-3 text-[#333333] text-xs sm:text-sm leading-6 sm:leading-7 text-right">
                                        {comment.content}
                                    </div>

                                    {idx !== sortedComments.length - 1 && <div className="mt-4 sm:mt-5"> <Separator /> </div>}
                                </div>
                            ))
                        ) : (
                            <div className="px-4 sm:px-6 py-8 text-center text-[#999999] text-sm">
                                هنوز نظری ثبت نشده است
                            </div>
                        )}
                    </div>
                </div>

                <div className="col-span-12 md:col-span-3 order-first md:order-first">
                    <div className="rounded-[10px] p-4 sm:p-6 h-fit md:sticky md:top-[170px]">
                        <div className="text-primary text-xs sm:text-sm">نظرات خریداران</div>
                        <div className="mt-3 sm:mt-4 flex items-center justify-end gap-2">
                            <Star1 size={16} color="#FFC107" variant="Bold" className="sm:w-[18px] sm:h-[18px]" />
                            <div className="text-xs sm:text-sm">
                                <span className="font-medium">{average}</span>
                                <span className="text-[#7F7F7F]"> / 5</span>
                            </div>
                        </div>
                        <div className="mt-3 sm:mt-4 text-xs text-[#7F7F7F] leading-5 sm:leading-6 text-justify">
                            شما هم درباره این کالا نظر خود را ثبت کنید. نظر شما پس از بررسی و تایید نمایش داده می‌شود.
                        </div>
                        <Button className="w-full mt-4 sm:mt-5 text-xs sm:text-sm" onClick={() => setOpen(true)}>ثبت دیدگاه</Button>
                    </div>
                </div>
            </div>

            <AddComment open={open} close={() => setOpen(false)} />
        </div>
    )
}

export default Reviews



