'use client'

import { useState, useRef, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
import { FiX, FiChevronLeft, FiChevronRight } from 'react-icons/fi'
import { FaDiscord, FaTelegram, FaFacebook, FaInstagram, FaWhatsapp, FaEnvelope } from 'react-icons/fa'
import { FaXTwitter } from 'react-icons/fa6'
import { SiLine } from 'react-icons/si'
import { RiKakaoTalkFill } from 'react-icons/ri'

interface SharePanelProps {
    isOpen: boolean
    onClose: () => void
    videoUrl: string
    videoTitle?: string
    lockBodyScroll?: boolean
    /** ???????? iframe ????? */
    embedIframeHtml?: string
}

const scrollBtnClass =
    'absolute top-1/2 -translate-y-1/2 z-10 w-8 h-8 flex items-center justify-center rounded-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-neutral-900 text-black dark:text-white shadow-md hover:bg-gray-100 dark:hover:bg-neutral-800 transition-colors'

function copyBtnClass(done: boolean): string {
    return done
        ? 'bg-neutral-600 text-white dark:bg-neutral-300 dark:text-black'
        : 'bg-black text-white hover:bg-neutral-800 dark:bg-white dark:text-black dark:hover:bg-neutral-200'
}

export default function SharePanel({
    isOpen,
    onClose,
    videoUrl,
    videoTitle,
    lockBodyScroll = true,
    embedIframeHtml = '',
}: SharePanelProps) {
    const { t } = useTranslation()
    const [copied, setCopied] = useState(false)
    const [embedCopied, setEmbedCopied] = useState(false)
    const panelRef = useRef<HTMLDivElement>(null)
    const scrollContainerRef = useRef<HTMLDivElement>(null)
    const [canScrollLeft, setCanScrollLeft] = useState(false)
    const [canScrollRight, setCanScrollRight] = useState(true)
    const [isClosing, setIsClosing] = useState(false)
    const prevBodyOverflowRef = useRef<string | null>(null)

    useEffect(() => {
        if (!lockBodyScroll) return

        if (isOpen) {
            if (prevBodyOverflowRef.current === null) {
                prevBodyOverflowRef.current = document.body.style.overflow
            }
            document.body.style.overflow = 'hidden'
            setIsClosing(false)
        } else if (prevBodyOverflowRef.current !== null) {
            document.body.style.overflow = prevBodyOverflowRef.current
            prevBodyOverflowRef.current = null
        }

        return () => {
            if (prevBodyOverflowRef.current !== null) {
                document.body.style.overflow = prevBodyOverflowRef.current
                prevBodyOverflowRef.current = null
            }
        }
    }, [isOpen, lockBodyScroll])

    const handleClose = () => {
        setIsClosing(true)
        setTimeout(() => {
            onClose()
            setIsClosing(false)
        }, 200)
    }

    const checkScroll = () => {
        const container = scrollContainerRef.current
        if (!container) return

        const { scrollLeft, scrollWidth, clientWidth } = container
        setCanScrollLeft(scrollLeft > 0)
        setCanScrollRight(scrollLeft < scrollWidth - clientWidth - 10)
    }

    useEffect(() => {
        const container = scrollContainerRef.current
        if (!container) return

        checkScroll()
        container.addEventListener('scroll', checkScroll)
        window.addEventListener('resize', checkScroll)

        return () => {
            container.removeEventListener('scroll', checkScroll)
            window.removeEventListener('resize', checkScroll)
        }
    }, [isOpen])

    const scrollLeft = () => {
        const container = scrollContainerRef.current
        if (container) {
            const itemWidth = 80
            const scrollAmount = Math.min(itemWidth * 2, container.scrollLeft)
            container.scrollBy({
                left: -scrollAmount,
                behavior: 'smooth',
            })
        }
    }

    const scrollRight = () => {
        const container = scrollContainerRef.current
        if (container) {
            const itemWidth = 80
            const remainingScroll = container.scrollWidth - container.scrollLeft - container.clientWidth
            const scrollAmount = Math.min(itemWidth * 2, remainingScroll)
            container.scrollBy({
                left: scrollAmount,
                behavior: 'smooth',
            })
        }
    }

    const handleCopy = async () => {
        try {
            await navigator.clipboard.writeText(videoUrl)
            setCopied(true)
            setTimeout(() => {
                setCopied(false)
            }, 2000)
        } catch (err) {
            console.error('Failed to copy:', err)
        }
    }

    const handleCopyEmbed = async () => {
        const code = String(embedIframeHtml ?? '').trim()
        if (!code) return
        try {
            await navigator.clipboard.writeText(code)
            setEmbedCopied(true)
            setTimeout(() => setEmbedCopied(false), 2000)
        } catch (err) {
            console.error('Failed to copy embed code:', err)
        }
    }

    const shareOptions = [
        {
            id: 'discord',
            name: 'Discord',
            icon: FaDiscord,
            color: 'bg-[#5865F2]',
            action: () => {
                handleCopy()
            },
        },
        {
            id: 'line',
            name: 'LINE',
            icon: SiLine,
            color: 'bg-[#00C300]',
            action: () => {
                window.open(`https://social-plugins.line.me/lineit/share?url=${encodeURIComponent(videoUrl)}`, '_blank')
            },
        },
        {
            id: 'telegram',
            name: 'Telegram',
            icon: FaTelegram,
            color: 'bg-[#0088cc]',
            action: () => {
                window.open(`https://t.me/share/url?url=${encodeURIComponent(videoUrl)}&text=${encodeURIComponent(videoTitle || '')}`, '_blank')
            },
        },
        {
            id: 'facebook',
            name: 'Facebook',
            icon: FaFacebook,
            color: 'bg-[#1877F2]',
            action: () => {
                window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(videoUrl)}`, '_blank')
            },
        },
        {
            id: 'instagram',
            name: 'Instagram',
            icon: FaInstagram,
            color: 'bg-gradient-to-br from-[#833AB4] via-[#FD1D1D] to-[#FCB045]',
            action: () => {
                handleCopy()
            },
        },
        {
            id: 'twitter',
            name: 'X',
            icon: FaXTwitter,
            color: 'bg-black',
            action: () => {
                window.open(`https://twitter.com/intent/tweet?url=${encodeURIComponent(videoUrl)}&text=${encodeURIComponent(videoTitle || '')}`, '_blank')
            },
        },
        {
            id: 'whatsapp',
            name: 'WhatsApp',
            icon: FaWhatsapp,
            color: 'bg-[#25D366]',
            action: () => {
                window.open(`https://wa.me/?text=${encodeURIComponent(videoTitle || '')} ${videoUrl}`, '_blank')
            },
        },
        {
            id: 'email',
            name: t('catch.sharePanel.email'),
            icon: FaEnvelope,
            color: 'bg-gray-500',
            action: () => {
                window.location.href = `mailto:?subject=${encodeURIComponent(videoTitle || '')}&body=${encodeURIComponent(videoUrl)}`
            },
        },
        {
            id: 'kakaotalk',
            name: 'KakaoTalk',
            icon: RiKakaoTalkFill,
            color: 'bg-[#FEE500]',
            iconClass: 'text-black',
            action: () => {
                window.open(`https://story.kakao.com/share?url=${encodeURIComponent(videoUrl)}`, '_blank')
            },
        },
    ]

    if (!isOpen && !isClosing) return null

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

            <div
                ref={panelRef}
                className={`fixed left-1/2 top-1/2 w-[90%] max-w-[500px] bg-white dark:bg-black border border-gray-200 dark:border-gray-800 rounded-xl shadow-xl z-[10000] ${isClosing ? 'animate-share-panel-exit' : isOpen ? 'animate-share-panel-enter' : 'opacity-0'}`}
            >
                <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-800">
                    <h2 className="text-xl font-semibold text-black dark:text-white">
                        {t('catch.share')}
                    </h2>
                    <button
                        type="button"
                        onClick={handleClose}
                        className="p-2 rounded-full text-black dark:text-white hover:bg-gray-100 dark:hover:bg-neutral-900 transition-colors"
                        aria-label={t('common.cancel')}
                    >
                        <FiX className="w-5 h-5" />
                    </button>
                </div>

                <div className="px-6 py-6">
                    <div className="relative">
                        {canScrollLeft && (
                            <button
                                type="button"
                                onClick={scrollLeft}
                                className={`left-0 ${scrollBtnClass}`}
                                aria-label={t('common.previous')}
                            >
                                <FiChevronLeft className="w-5 h-5" />
                            </button>
                        )}

                        {canScrollRight && (
                            <button
                                type="button"
                                onClick={scrollRight}
                                className={`right-0 ${scrollBtnClass}`}
                                aria-label={t('common.next')}
                            >
                                <FiChevronRight className="w-5 h-5" />
                            </button>
                        )}

                        <div
                            ref={scrollContainerRef}
                            className="flex items-start gap-4 overflow-x-auto pb-2 hide-scrollbar"
                            style={{
                                scrollbarWidth: 'none',
                                msOverflowStyle: 'none',
                                paddingLeft: '8px',
                                paddingRight: '8px',
                                scrollBehavior: 'smooth',
                                WebkitOverflowScrolling: 'touch',
                            }}
                        >
                            {shareOptions.map((option) => {
                                const Icon = option.icon
                                return (
                                    <button
                                        key={option.id}
                                        type="button"
                                        onClick={option.action}
                                        className="flex flex-col items-center gap-2 flex-shrink-0 group px-2 py-2"
                                    >
                                        <div
                                            className={`w-14 h-14 rounded-full ${option.color} flex items-center justify-center ${option.iconClass ?? 'text-white'} shadow-md group-hover:scale-110 transition-transform duration-200`}
                                        >
                                            <Icon className="w-7 h-7" />
                                        </div>
                                        <span className="text-xs text-black dark:text-white text-center max-w-[80px]">
                                            {option.name}
                                        </span>
                                    </button>
                                )
                            })}
                        </div>
                    </div>

                    <div className="mt-6 flex items-center gap-2 flex-nowrap">
                        <input
                            type="text"
                            value={videoUrl}
                            readOnly
                            className="flex-1 min-w-0 px-4 py-3 bg-gray-100 dark:bg-neutral-900 border border-gray-300 dark:border-gray-600 rounded-lg text-sm text-black dark:text-white focus:outline-none focus:ring-2 focus:ring-black/20 dark:focus:ring-white/25"
                        />
                        <button
                            type="button"
                            onClick={handleCopy}
                            className={`flex-shrink-0 whitespace-nowrap min-w-[88px] px-4 md:px-6 py-3 rounded-lg font-semibold text-sm transition-all duration-200 ${copyBtnClass(copied)}`}
                        >
                            {copied ? t('catch.sharePanel.copied') : t('catch.sharePanel.copy')}
                        </button>
                    </div>

                    {embedIframeHtml ? (
                        <div className="mt-6 border-t border-gray-200 dark:border-gray-800 pt-5">
                            <h3 className="text-sm font-semibold text-black dark:text-white mb-1">
                                {t('catch.sharePanel.embedTitle')}
                            </h3>
                            <p className="text-xs text-neutral-500 dark:text-neutral-400 mb-3">
                                {t('catch.sharePanel.embedHint')}
                            </p>
                            <textarea
                                readOnly
                                rows={4}
                                value={embedIframeHtml}
                                className="w-full resize-none rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-100 dark:bg-neutral-900 px-3 py-2 text-xs font-mono text-black dark:text-white focus:outline-none focus:ring-2 focus:ring-black/20 dark:focus:ring-white/25"
                            />
                            <button
                                type="button"
                                onClick={handleCopyEmbed}
                                className={`mt-2 w-full rounded-lg px-4 py-2.5 text-sm font-semibold transition-colors ${copyBtnClass(embedCopied)}`}
                            >
                                {embedCopied ? t('catch.sharePanel.copied') : t('catch.sharePanel.copy')}
                            </button>
                        </div>
                    ) : null}
                </div>
            </div>
        </>
    )

    if (typeof window !== 'undefined') {
        return createPortal(panelContent, document.body)
    }

    return null
}
