'use client'

import { useCallback, useEffect, useState } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { useTranslation } from 'react-i18next'
import { FaThumbtack, FaXmark } from 'react-icons/fa6'
import CommentInput from '@/app/catch/_components/CommentInput'
import CommentItem from '@/app/catch/_components/CommentItem'
import CommentsListSkeleton from '@/app/catch/_components/Skeletons/CommentsListSkeleton'
import type { Comment } from '@/app/catch/_components/types'

type Post = {
    id: string
    authorName: string
    authorAvatar: string
    date: string
    pinned: boolean
    content: string
    comments: number
    views: number
    thumb: string
    thumbCount?: number
}

function countCommentsFlat(comments: Comment[]): number {
    let n = comments.length
    comments.forEach((c) => {
        if (c.nestedReplies?.length) n += countCommentsFlat(c.nestedReplies)
    })
    return n
}

export default function PostPageClient({
    post,
    userId,
    currentUserId,
    initialCurrentUserAvatar,
}: {
    post: Post
    userId: string
    currentUserId: string | null
    initialCurrentUserAvatar: string | null
}) {
    const { t } = useTranslation()
    const [comments, setComments] = useState<Comment[]>([])
    const [commentsLoading, setCommentsLoading] = useState(true)
    const [commentCount, setCommentCount] = useState(post.comments)
    const [imageLightboxUrl, setImageLightboxUrl] = useState<string | null>(null)

    const fetchComments = useCallback(async () => {
        setCommentsLoading(true)
        try {
            const res = await fetch(`/api/board-posts/${encodeURIComponent(post.id)}/comments`)
            const data = await res.json()
            if (data.ok && data.data) {
                setComments(data.data)
                setCommentCount(countCommentsFlat(data.data))
            }
        } catch (e) {
            console.error('Failed to fetch comments:', e)
        } finally {
            setCommentsLoading(false)
        }
    }, [post.id])

    useEffect(() => {
        fetchComments()
    }, [fetchComments])

    useEffect(() => {
        if (!imageLightboxUrl) return
        const onKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape') setImageLightboxUrl(null)
        }
        window.addEventListener('keydown', onKeyDown)
        return () => window.removeEventListener('keydown', onKeyDown)
    }, [imageLightboxUrl])

    const handleCreateComment = useCallback(
        async (content: string) => {
            const res = await fetch(`/api/board-posts/${encodeURIComponent(post.id)}/comments`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ content }),
            })
            const data = await res.json()
            if (!data.ok) throw new Error(data.message || 'Failed to create comment')
            await fetchComments()
        },
        [post.id, fetchComments]
    )

    const handleReply = useCallback(
        async (commentId: string, replyText: string, replyTo: string) => {
            const res = await fetch(`/api/board-posts/${encodeURIComponent(post.id)}/comments`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ content: replyText, parentId: commentId, replyTo }),
            })
            const data = await res.json()
            if (!data.ok) throw new Error(data.message || 'Failed to reply')
            await fetchComments()
        },
        [post.id, fetchComments]
    )

    const handleDelete = useCallback(
        async (commentId: string) => {
            const res = await fetch(
                `/api/board-posts/${encodeURIComponent(post.id)}/comments?commentId=${encodeURIComponent(commentId)}`,
                { method: 'DELETE' }
            )
            const data = await res.json()
            if (!data.ok) throw new Error(data.message || 'Failed to delete')
            await fetchComments()
        },
        [post.id, fetchComments]
    )

    return (
        <main className="flex-1 min-w-0">
            <section className="px-4 sm:px-8 md:px-[120px] py-6 sm:py-8">
                <div className="mx-auto max-w-[800px]">
                    <div className="mb-4">
                        <Link
                            href={`/user/${encodeURIComponent(userId)}`}
                            className="text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200"
                        >
                            ← {t('user.board.backToProfile')}
                        </Link>
                    </div>

                    <article>
                        <div className="flex items-center gap-3">
                            <div className="relative w-10 h-10 rounded-full overflow-hidden flex-shrink-0 border border-gray-200 dark:border-white/10">
                                <Image
                                    src={post.authorAvatar}
                                    alt=""
                                    fill
                                    className="object-cover"
                                    unoptimized
                                />
                            </div>
                            <div className="min-w-0 flex-1">
                                <p className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
                                    {post.authorName}
                                </p>
                            </div>
                        </div>
                        <div className="mt-3">
                            <p className="text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap break-words">
                                {post.content}
                            </p>
                        </div>
                        {post.thumb && (
                            <div className="mt-3 inline-block max-w-full">
                                <button
                                    type="button"
                                    onClick={() => setImageLightboxUrl(post.thumb)}
                                    className="block text-left cursor-zoom-in focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-gray-500 rounded-xl"
                                >
                                    <Image
                                        src={post.thumb}
                                        alt=""
                                        width={640}
                                        height={360}
                                        className="max-h-[360px] max-w-xl w-auto h-auto rounded-xl bg-gray-100 dark:bg-neutral-900"
                                        unoptimized
                                    />
                                </button>
                            </div>
                        )}
                        <div className="flex items-center gap-4 mt-3 pt-2">
                            <span className="inline-flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400">
                                <svg viewBox="0 0 24 24" className="w-5 h-5" fill="currentColor">
                                    <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
                                </svg>
                                <span>{post.views}</span>
                            </span>
                            <span className="inline-flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400">
                                <svg viewBox="0 0 24 24" className="w-5 h-5" fill="currentColor">
                                    <path d="M5 4h14a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2h-5.59l-2.7 2.7A1 1 0 0 1 9 17.99V15H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z" />
                                </svg>
                                <span>{commentCount}</span>
                            </span>
                        </div>
                    </article>

                    <hr className="my-8 border-gray-200 dark:border-white/10" />

                    <section className="mt-6" aria-label={t('catch.comments')}>
                        <h2 className="text-base font-semibold text-gray-900 dark:text-white mb-4">
                            {t('catch.comments')} {commentCount}
                        </h2>

                        <div className="flex-shrink-0 mb-6 pb-4 border-b border-gray-200 dark:border-white/10">
                            <CommentInput
                                onSubmit={currentUserId ? handleCreateComment : undefined}
                                placeholder={t('user.board.commentPlaceholder')}
                                userAvatar={initialCurrentUserAvatar}
                                isLoggedIn={!!currentUserId}
                            />
                        </div>

                        {commentsLoading ? (
                            <CommentsListSkeleton />
                        ) : comments.length > 0 ? (
                            <div className="space-y-4">
                                {comments.map((comment) => (
                                    <CommentItem
                                        key={comment.id}
                                        comment={comment}
                                        onReply={currentUserId ? handleReply : undefined}
                                        onDelete={handleDelete}
                                        userAvatar={initialCurrentUserAvatar}
                                        isLoggedIn={!!currentUserId}
                                        currentUserId={currentUserId ?? undefined}
                                        videoOwnerId={userId}
                                    />
                                ))}
                            </div>
                        ) : (
                            <p className="py-8 text-center text-sm text-gray-500 dark:text-gray-400">
                                {t('catch.commentsEmpty')}
                            </p>
                        )}
                    </section>
                </div>
            </section>

            {imageLightboxUrl && (
                <div
                    className="fixed inset-0 z-[320] flex items-center justify-center bg-black/80 p-4"
                    onClick={() => setImageLightboxUrl(null)}
                    role="dialog"
                    aria-modal="true"
                    aria-label={t('common.close')}
                >
                    <button
                        type="button"
                        className="absolute top-4 right-4 z-10 w-10 h-10 rounded-full bg-black/50 hover:bg-black/70 text-white inline-flex items-center justify-center"
                        onClick={() => setImageLightboxUrl(null)}
                        aria-label={t('common.close')}
                    >
                        <FaXmark className="w-5 h-5" />
                    </button>
                    <Image
                        src={imageLightboxUrl}
                        alt=""
                        width={1200}
                        height={900}
                        className="max-w-full max-h-[90vh] w-auto h-auto object-contain rounded-lg"
                        onClick={(e) => e.stopPropagation()}
                        draggable={false}
                        unoptimized
                    />
                </div>
            )}
        </main>
    )
}
