'use client'

import { useState, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
import { FiX } from 'react-icons/fi'
import Skeleton from '@/components/Skeleton'
import CommentsList from './CommentsList'
import CommentInput from './CommentInput'
import CommentsListSkeleton from './Skeletons/CommentsListSkeleton'
import type { Comment } from './types'

interface CommentsPanelProps {
    isOpen: boolean
    onClose: () => void
    comments: Comment[]
    commentCount: number
    commentsLoading?: boolean
    onReply?: (commentId: string, replyText: string, replyTo: string) => void
    onCreateComment?: (content: string) => Promise<void>
    onDelete?: (commentId: string) => void
    onEdit?: (commentId: string, newContent: string) => Promise<void>
    onPin?: (commentId: string, isPinned: boolean) => Promise<void>
    onLike?: (commentId: string) => Promise<void>
    userAvatar?: string | null
    isLoggedIn?: boolean
    currentUserId?: string | null
    videoOwnerId?: string | null
    usePortal?: boolean
}

export default function CommentsPanel({
    isOpen,
    onClose,
    comments,
    commentCount,
    commentsLoading = false,
    onReply,
    onCreateComment,
    onDelete,
    onEdit,
    onPin,
    onLike,
    userAvatar,
    isLoggedIn = false,
    currentUserId,
    videoOwnerId,
    usePortal = true,
}: CommentsPanelProps) {
    const { t } = useTranslation()
    const [isClosing, setIsClosing] = useState(false)

    useEffect(() => {
        const body = document.body
        const prevOverflowY = body.style.overflowY

        if (isOpen) {
            // 不要蓋掉 overflowX（小螢幕需要水平捲動避免擠壓）
            body.style.overflowY = 'hidden'
            setIsClosing(false)
        } else {
            body.style.overflowY = prevOverflowY
        }
        return () => {
            body.style.overflowY = prevOverflowY
        }
    }, [isOpen])

    const handleClose = () => {
        setIsClosing(true)
        setTimeout(() => {
            onClose()
            setIsClosing(false)
        }, 200) // 與動畫時長一致
    }

    if (!isOpen && !isClosing) return null

    const panelContent = (
        <>
            {/* 背景遮罩 */}
            <div
                className={`${usePortal ? 'fixed' : 'absolute'} inset-0 bg-black/50 z-[9999] ${isClosing ? 'animate-share-backdrop-exit' : isOpen ? 'animate-share-backdrop-enter' : 'opacity-0'}`}
                onClick={handleClose}
            />

            {/* 留言面板 */}
            <div
                className={`${usePortal ? 'fixed' : 'absolute'} left-1/2 top-1/2 w-[95%] max-w-[95%] md:max-w-[30%] h-[85vh] max-h-[85vh] bg-white dark:bg-[#0c0d0e] shadow-2xl z-[10000] flex flex-col rounded-xl overflow-hidden ${isClosing ? 'animate-share-panel-exit' : isOpen ? 'animate-share-panel-enter' : 'opacity-0'
                    }`}
            >
                {/* 標題欄 */}
                <div className="flex items-center justify-between px-4 md:px-5 pt-4 md:pt-5 pb-3 border-b border-gray-200 dark:border-gray-800 flex-shrink-0">
                    <div className="flex items-center gap-2">
                        <h2 className="text-base md:text-lg font-semibold text-black dark:text-white">
                            {t('catch.comments')}
                        </h2>
                        <span className="text-xs md:text-sm text-gray-500 dark:text-gray-400 font-medium">
                            {commentCount.toLocaleString()}
                        </span>
                    </div>
                    <button
                        onClick={handleClose}
                        className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors"
                    >
                        <FiX className="w-5 h-5 text-gray-600 dark:text-gray-400" />
                    </button>
                </div>

                {/* 留言內容 */}
                <div className="flex-1 overflow-hidden flex flex-col min-h-0">
                    {commentsLoading ? (
                        <>
                            <div className="flex-1 min-h-0 overflow-y-auto hide-scrollbar px-4 md:px-5 py-3 md:py-4">
                                <CommentsListSkeleton />
                            </div>
                            {/* 輸入框骨架 */}
                            <div className="flex-shrink-0 px-4 py-2 border-t border-gray-200 dark:border-gray-800 bg-white dark:bg-[#0c0d0e]">
                                <div className="flex items-center gap-2 md:gap-3">
                                    <Skeleton variant="circular" width={32} height={32} className="md:w-9 md:h-9 flex-shrink-0" animation="shimmer" />
                                    <Skeleton variant="rectangular" width="100%" height={40} className="rounded-full" animation="shimmer" />
                                    <Skeleton variant="rectangular" width={60} height={40} className="rounded-full" animation="shimmer" />
                                </div>
                            </div>
                        </>
                    ) : (
                        <CommentsList
                            comments={comments}
                            commentInput={<CommentInput onSubmit={onCreateComment} userAvatar={userAvatar} isLoggedIn={isLoggedIn} />}
                            onReply={onReply}
                            onDelete={onDelete}
                            onEdit={onEdit}
                            onPin={onPin}
                            onLike={onLike}
                            userAvatar={userAvatar}
                            isLoggedIn={isLoggedIn}
                            currentUserId={currentUserId}
                            videoOwnerId={videoOwnerId}
                        />
                    )}
                </div>
            </div>
        </>
    )

    // 使用 Portal 將內容渲染到 document.body，確保不受父容器 z-index 限制
    if (usePortal && typeof window !== 'undefined') {
        return createPortal(panelContent, document.body)
    }

    return panelContent
}

