'use client'

import { FC, Fragment, useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import { ArrowDown2, MessageQuestion } from 'iconsax-react'
import { Product, Question } from '@/types/product.types'
import AddQuestion from './AddQuestion'
import { PRIMARY_COLOR } from '@/config/const'

interface QuestionsProps {
    product: Product
    questions?: Question[]
}

const Questions: FC<QuestionsProps> = ({ questions = [] }) => {
    const [sort, setSort] = useState<'new' | 'answers'>('new')
    const [expandedId, setExpandedId] = useState<string | null>(null)
    const [open, setOpen] = useState(false)
    const sorted = useMemo(() => {
        if (sort === 'new') {
            return [...questions].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
        }
        return [...questions].sort((a, b) => b.answers.length - a.answers.length)
    }, [sort, questions])

    const formatDate = (dateString: string) => {
        const date = new Date(dateString)
        return date.toLocaleDateString('fa-IR')
    }

    return (
        <div className="mt-12 sm:mt-16 w-full">
            <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 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-end 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('answers')}
                                className={
                                    sort === 'answers' ? 'text-primary font-medium' : 'text-[#B2B2B2] hover:text-primary'
                                }
                            >
                                بیشترین پاسخ
                            </button>
                        </div>
                    </div>

                    <div className="mt-4 sm:mt-6 rounded-xl bg-white divide-y divide-[#E6E6E6]">
                        {sorted.length > 0 ? (
                            sorted.map((question) => (
                                <Fragment key={question._id}>
                                    <div className="px-4 sm:px-6 py-4 sm:py-5">
                                        <div className="flex items-start gap-2 sm:gap-3">
                                            <div className="shrink-0 mt-0.5">
                                                <div className="size-6 sm:size-8 rounded-full border border-[#DDE9FF] bg-[#F6FAFF] flex items-center justify-center">
                                                    <MessageQuestion size={14} color="#2F80ED" className="sm:w-[18px] sm:h-[18px]" />
                                                </div>
                                            </div>
                                            <div className="text-[#333333] text-xs sm:text-sm leading-6 sm:leading-7 text-right flex-1">
                                                {question.question}
                                            </div>
                                        </div>

                                        <div className="mt-2 text-xs text-[#999999]">
                                            {question.user.name} • {formatDate(question.date)}
                                        </div>

                                        {question.answers.length === 0 && (
                                            <div className="mt-3 text-primary text-xs cursor-pointer w-fit">ثبت پاسخ</div>
                                        )}

                                        {question.answers.length > 0 && (
                                            <div className="mt-3 sm:mt-4 text-[#7F7F7F]">
                                                {(expandedId === question._id ? question.answers : question.answers.slice(0, 1)).map((answer) => (
                                                    <div key={answer._id} className='flex gap-2 items-start mt-2 first:mt-0'>
                                                        <div className="text-xs shrink-0">پاسخ</div>
                                                        <div className="text-xs leading-6 sm:leading-7 text-right text-[#333333]">
                                                            {answer.answer}
                                                        </div>
                                                    </div>
                                                ))}

                                                {question.answers.length > 1 && (
                                                    <button
                                                        type="button"
                                                        onClick={() => setExpandedId(expandedId === question._id ? null : question._id)}
                                                        className="mt-3 flex items-center gap-1 text-xs text-primary"
                                                    >
                                                        {expandedId === question._id ? 'بستن پاسخ‌ها' : 'مشاهده پاسخ های دیگر'}
                                                        <ArrowDown2 size={12} color={PRIMARY_COLOR} className={expandedId === question._id ? 'rotate-180 transition' : 'transition sm:w-[14px] sm:h-[14px]'} />
                                                    </button>
                                                )}
                                            </div>
                                        )}
                                    </div>
                                </Fragment>
                            ))
                        ) : (
                            <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 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>

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

        </div>
    )
}

export default Questions


