'use client'

import { useState } from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { FaPlay, FaVolumeUp, FaVolumeMute, FaVolumeDown } from 'react-icons/fa'
import { FiPause, FiUser } from 'react-icons/fi'
import { MdVerified } from 'react-icons/md'
import { useTranslation } from 'react-i18next'
import CatchVideoPlayer from './CatchVideoPlayer'
import type { CatchVideo } from './types'

interface DesktopVideoPlayerProps {
    video: CatchVideo
    isCurrent: boolean
    isPlaying: boolean
    volume: number
    isMuted: boolean
    onPlayToggle: () => void
    onMuteToggle: () => void
    onVolumeChange: (volume: number) => void
    formatViews?: (views: number) => string
}

export default function DesktopVideoPlayer({
    video,
    isCurrent,
    isPlaying,
    volume,
    isMuted,
    onPlayToggle,
    onMuteToggle,
    onVolumeChange,
    formatViews,
}: DesktopVideoPlayerProps) {
    const { t } = useTranslation()

    // States
    const [showVolume, setShowVolume] = useState(false)
    const [controlsVisible, setControlsVisible] = useState(true)
    const [hoverTopControls, setHoverTopControls] = useState(false)

    const volumePct = Math.round((isMuted ? 0 : volume) * 100)
    const sliderStyle = { ['--p' as any]: `${volumePct}%` }
    const defaultFormatViews = (views: number) => views.toLocaleString()
    const format = formatViews || defaultFormatViews

    return (
        <div
            className="relative w-full h-full bg-black dark:bg-[#0c0d0e] overflow-hidden"
            style={{
                scrollSnapAlign: 'start',
                scrollSnapStop: 'always',
            }}
        >
            <div className="absolute inset-0 flex items-center justify-center">
                <div className="relative w-full h-full">
                    <CatchVideoPlayer
                        video={video}
                        src={video.src}
                        isCurrent={isCurrent}
                        isPlaying={isPlaying}
                        volume={volume}
                        isMuted={isMuted}
                        onPlayStateChange={(playing) => {
                            if (playing !== isPlaying) {
                                onPlayToggle()
                            }
                        }}
                        onVolumeChange={onVolumeChange}
                        onControlsVisibilityChange={setControlsVisible}
                        forceControlsVisible={hoverTopControls}
                    />
                    {isCurrent && (
                        <>
                            <div
                                className={`absolute top-4 left-4 z-20 transition-[opacity,transform] duration-200 ease-out ${controlsVisible ? 'opacity-100 translate-y-0' : 'opacity-0 -translate-y-2 pointer-events-none'
                                    }`}
                                onMouseEnter={() => setHoverTopControls(true)}
                                onMouseLeave={() => setHoverTopControls(false)}
                            >
                                <button
                                    onClick={(e) => {
                                        e.stopPropagation()
                                        onPlayToggle()
                                    }}
                                    className="w-[48px] h-[48px] flex items-center justify-center bg-black/50 rounded-full text-white hover:bg-black/70 transition-colors"
                                >
                                    {isPlaying ? (
                                        <FiPause className="w-5 h-5" />
                                    ) : (
                                        <FaPlay className="w-5 h-5 ml-1" />
                                    )}
                                </button>
                            </div>
                            <div
                                className={`absolute top-4 left-16 flex items-center z-20 ml-2 transition-[opacity,transform] duration-200 ease-out ${controlsVisible ? 'opacity-100 translate-y-0' : 'opacity-0 -translate-y-2 pointer-events-none'
                                    }`}
                                onMouseEnter={() => {
                                    setHoverTopControls(true)
                                    setShowVolume(true)
                                }}
                                onMouseLeave={() => {
                                    setHoverTopControls(false)
                                    setShowVolume(false)
                                }}
                                onClick={(e) => {
                                    e.stopPropagation()
                                    setShowVolume((v) => !v)
                                }}
                            >
                                <div className="flex max-h-12">
                                    <div
                                        className={`relative flex items-center gap-3 h-12 flex-1 min-w-0 max-w-[168px] rounded-[50px] ${showVolume ? 'pointer-events-auto' : 'pointer-events-none'}`}
                                    >
                                        <div
                                            className={`absolute h-12 z-0 bg-black/30 rounded-[50px] transition-[width] duration-200 ease-linear ${showVolume ? 'w-full' : 'w-12'}`}
                                            aria-hidden="true"
                                        />

                                        <button
                                            className="relative z-10 pointer-events-auto cursor-pointer flex items-center min-w-9 justify-end bg-transparent border-none outline-none py-3"
                                            aria-label={isMuted ? t('room.player.unmute') : t('room.player.mute')}
                                            title={isMuted ? t('room.player.unmute') : t('room.player.mute')}
                                            onClick={(e) => {
                                                e.stopPropagation()
                                                onMuteToggle()
                                            }}
                                        >
                                            <span className="text-white">
                                                {isMuted || volume === 0 ? (
                                                    <FaVolumeMute className="w-5 h-5" />
                                                ) : volume < 0.5 ? (
                                                    <FaVolumeDown className="w-5 h-5" />
                                                ) : (
                                                    <FaVolumeUp className="w-5 h-5" />
                                                )}
                                            </span>
                                        </button>

                                        <div
                                            className={`relative z-10 flex items-center min-w-0 pr-3 transition-[visibility,opacity,flex-basis] ${showVolume ? 'visible opacity-100 basis-full duration-300' : 'invisible opacity-0 basis-0 duration-150'}`}
                                            onClick={(e) => e.stopPropagation()}
                                        >
                                            <input
                                                aria-label={t('room.player.volume')}
                                                title={t('room.player.volume')}
                                                type="range"
                                                min={0}
                                                max={100}
                                                value={volumePct}
                                                style={sliderStyle}
                                                className="flex-grow min-w-0 bg-transparent cursor-pointer appearance-none py-1
                                                  [&::-webkit-slider-runnable-track]:h-[2px] [&::-webkit-slider-runnable-track]:rounded-[12px]
                                                  [&::-webkit-slider-runnable-track]:bg-[linear-gradient(to_right,#fff_0,#fff_var(--p),rgba(255,255,255,0.3)_var(--p),rgba(255,255,255,0.3)_100%)]
                                                  [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:mt-[-7px]
                                                  [&::-moz-range-track]:h-[2px] [&::-moz-range-track]:rounded-[12px]
                                                  [&::-moz-range-track]:bg-[linear-gradient(to_right,#fff_0,#fff_var(--p),rgba(255,255,255,0.3)_var(--p),rgba(255,255,255,0.3)_100%)]
                                                  [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-white [&::-moz-range-thumb]:border-0"
                                                onChange={(e) => onVolumeChange(e.currentTarget.valueAsNumber / 100)}
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </>
                    )}
                    {video.status === 'adult' && (
                        <div className="absolute top-4 right-4 bg-red-500 text-white px-3 py-1 rounded-full text-xs font-semibold z-20">
                            {t('catch.adult')}
                        </div>
                    )}
                    {isCurrent && (
                        <div className="absolute bottom-0 left-0 right-0 w-full px-2 py-3 z-10">
                            <div className="flex items-center gap-3 mb-2">
                                {video.userId ? (
                                    <Link
                                        href={`/user/${encodeURIComponent(video.userId)}`}
                                        className="relative w-10 h-10 rounded-full overflow-hidden bg-gradient-to-br from-gray-200 to-gray-300 dark:from-gray-700 dark:to-gray-800 flex-shrink-0 hover:opacity-80 transition-opacity"
                                    >
                                        {video.profile ? (
                                            <Image
                                                src={video.profile}
                                                alt={video.nickname}
                                                fill
                                                className="pointer-events-none"
                                                unoptimized
                                            />
                                        ) : (
                                            <div className="absolute inset-0 flex items-center justify-center">
                                                <FiUser className="w-5 h-5 text-gray-400" />
                                            </div>
                                        )}
                                    </Link>
                                ) : (
                                    <div className="relative w-10 h-10 rounded-full overflow-hidden bg-gradient-to-br from-gray-200 to-gray-300 dark:from-gray-700 dark:to-gray-800 flex-shrink-0">
                                        {video.profile ? (
                                            <Image
                                                src={video.profile}
                                                alt={video.nickname}
                                                fill
                                                className="pointer-events-none"
                                                unoptimized
                                            />
                                        ) : (
                                            <div className="absolute inset-0 flex items-center justify-center">
                                                <FiUser className="w-5 h-5 text-gray-400" />
                                            </div>
                                        )}
                                    </div>
                                )}
                                <div className="min-w-0">
                                    {video.userId ? (
                                        <Link
                                            href={`/user/${encodeURIComponent(video.userId)}`}
                                            className="text-white dark:text-white font-semibold text-sm flex items-center gap-1.5 truncate select-none"
                                        >
                                            @{video.nickname}
                                            {video.verified && (
                                                <MdVerified
                                                    className="w-4 h-4 text-cyan-400 flex-shrink-0"
                                                    title={t('catch.verified')}
                                                />
                                            )}
                                        </Link>
                                    ) : (
                                        <div className="text-white dark:text-white font-semibold text-sm flex items-center gap-1.5 truncate select-none">
                                            @{video.nickname}
                                            {video.verified && (
                                                <MdVerified
                                                    className="w-4 h-4 text-cyan-400 flex-shrink-0"
                                                    title={t('catch.verified')}
                                                />
                                            )}
                                        </div>
                                    )}
                                    {video.followers !== undefined && (
                                        <div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 select-none">
                                            {format(video.followers)}{t('explore.followers')}
                                        </div>
                                    )}
                                </div>
                                <button className="px-4 py-1.5 bg-white text-black hover:bg-gray-800 dark:hover:bg-gray-200 rounded-full text-sm font-semibold inline-flex items-center gap-1.5 transition-colors flex-shrink-0">
                                    {t('explore.follow')}
                                </button>
                            </div>
                            <p className="text-white dark:text-white text-sm line-clamp-2">
                                {video.title}
                            </p>
                        </div>
                    )}
                </div>
            </div>
        </div>
    )
}

