'use client'

import { FiStar } from 'react-icons/fi'
import { FaHeart, FaRegHeart, FaStar } from 'react-icons/fa6'
import { formatViews } from '@/utils/format'
import { hoverTipBelowClass } from '@/lib/ui/hoverTipClass'

const HEART_FLY_ANIMATIONS = [
    'animate-heart-fly-1',
    'animate-heart-fly-2',
    'animate-heart-fly-3',
    'animate-heart-fly-4',
    'animate-heart-fly-5',
] as const

type Variant = 'desktop' | 'compact' | 'theater'

type SegmentPosition = 'only' | 'first' | 'middle' | 'last'

type Props = {
    variant: Variant
    showFollow: boolean
    showLike: boolean
    showFollowCount?: boolean
    followCountReadOnly?: boolean
    isFollowing: boolean
    isLiked: boolean
    followCount: number
    likeCount: number
    followTitle: string
    likeTitle: string
    onToggleFollow?: () => void
    onToggleLike?: () => void
    flyingStars: number[]
    flyingHearts: number[]
}

const grayPillHover =
    'hover:bg-[#e5e5e5] dark:hover:bg-white/[0.18] active:bg-[#d9d9d9] dark:active:bg-white/20'

function containerClass(variant: Variant): string {
    const base = 'inline-flex items-stretch overflow-visible select-none'
    if (variant === 'theater') {
        return `${base} h-10 rounded-[10px] border border-white/30 bg-black/20 shadow-sm`
    }
    if (variant === 'compact') {
        return `${base} h-9 rounded-[10px] border-0 bg-[#f2f2f2] dark:bg-white/[0.12]`
    }
    return `${base} h-9 rounded-[10px] border-0 bg-[#f2f2f2] dark:bg-white/[0.12]`
}

function segmentRadiusClass(variant: Variant, position: SegmentPosition): string {
    if (variant === 'theater') return ''
    if (position === 'only') return 'rounded-[10px]'
    if (position === 'first') return 'rounded-l-[10px]'
    if (position === 'last') return 'rounded-r-[10px]'
    return ''
}

function segmentClass(
    variant: Variant,
    position: SegmentPosition,
    interactive = true
): string {
    const tip = variant === 'theater' ? '' : ` ${hoverTipBelowClass}`
    const radius = segmentRadiusClass(variant, position)
    if (variant === 'theater') {
        const hover = interactive ? 'hover:bg-white/10 active:bg-white/15' : 'cursor-default'
        return `inline-flex items-center justify-center gap-1.5 h-full px-3 min-w-[48px] text-sm font-medium transition-colors ${radius} ${hover}`
    }
    if (variant === 'compact') {
        return `inline-flex items-center justify-center gap-1 h-full px-2.5 min-w-[44px] text-xs font-medium transition-colors ${radius} ${interactive ? grayPillHover : 'cursor-default'}${tip}`
    }
    return `inline-flex items-center justify-center gap-1.5 h-full px-3 min-w-[48px] text-sm font-medium transition-colors ${radius} ${interactive ? grayPillHover : 'cursor-default'}${tip}`
}

function dividerClass(variant: Variant): string {
    const color =
        variant === 'theater'
            ? 'bg-white/30'
            : 'bg-[#d9d9d9] dark:bg-white/20'
    return `w-px h-5 flex-shrink-0 self-center ${color}`
}

function textClass(variant: Variant, active: boolean, tone: 'follow' | 'like'): string {
    if (!active) {
        if (variant === 'theater') return 'text-white'
        return 'text-[#0f0f0f] dark:text-[#f1f1f1]'
    }
    return tone === 'follow'
        ? 'text-yellow-700 dark:text-yellow-400'
        : 'text-red-600 dark:text-red-400'
}

function iconTone(active: boolean, tone: 'follow' | 'like', variant: Variant): string {
    if (!active) {
        return variant === 'theater' ? 'text-white' : 'text-[#0f0f0f] dark:text-[#f1f1f1]'
    }
    return tone === 'follow' ? 'text-yellow-500 dark:text-yellow-400' : 'text-red-600 dark:text-red-400'
}

function FollowSegment({
    variant,
    position,
    interactive,
    isFollowing,
    followCount,
    followTitle,
    onToggleFollow,
    flyingStars,
}: {
    variant: Variant
    position: SegmentPosition
    interactive: boolean
    isFollowing: boolean
    followCount: number
    followTitle: string
    onToggleFollow?: () => void
    flyingStars: number[]
}) {
    const iconSize = 'w-5 h-5'
    const iconBox = variant === 'compact' ? 'w-5 h-5' : 'w-6 h-6'
    const className = segmentClass(variant, position, interactive)

    const inner = (
        <>
            <span
                className={`relative inline-flex items-center justify-center ${iconBox} ${iconTone(isFollowing, 'follow', variant)}`}
            >
                {interactive &&
                    flyingStars.map((id, index) => (
                        <span
                            key={id}
                            className={`absolute inset-0 flex items-center justify-center pointer-events-none ${HEART_FLY_ANIMATIONS[index] ?? HEART_FLY_ANIMATIONS[0]}`}
                        >
                            <FaStar className={`${iconSize} text-yellow-500 dark:text-yellow-400`} aria-hidden />
                        </span>
                    ))}
                {isFollowing ? (
                    <FaStar className={iconSize} aria-hidden />
                ) : (
                    <FiStar className={iconSize} aria-hidden />
                )}
            </span>
            <span className={textClass(variant, isFollowing, 'follow')}>{formatViews(followCount)}</span>
        </>
    )

    if (!interactive) {
        return (
            <div className={className} tip={followTitle} aria-label={followTitle}>
                {inner}
            </div>
        )
    }

    return (
        <button type="button" tip={followTitle} aria-label={followTitle} onClick={onToggleFollow} className={className}>
            {inner}
        </button>
    )
}

export default function LikeFollowActionGroup({
    variant,
    showFollow,
    showLike,
    showFollowCount = false,
    followCountReadOnly = false,
    isFollowing,
    isLiked,
    followCount,
    likeCount,
    followTitle,
    likeTitle,
    onToggleFollow,
    onToggleLike,
    flyingStars,
    flyingHearts,
}: Props) {
    const showLikeButton = showLike && Boolean(onToggleLike)
    const showFollowButton = showFollow && Boolean(onToggleFollow) && !showFollowCount
    const showFollowCountSegment = showFollowCount

    if (!showFollowButton && !showLikeButton && !showFollowCountSegment) return null

    const segmentCount =
        (showLikeButton ? 1 : 0) + (showFollowCountSegment ? 1 : 0) + (showFollowButton ? 1 : 0)

    const likePosition: SegmentPosition =
        segmentCount === 1 && showLikeButton
            ? 'only'
            : showLikeButton
              ? 'first'
              : 'middle'

    const followCountPosition: SegmentPosition =
        segmentCount === 1 && showFollowCountSegment
            ? 'only'
            : showFollowCountSegment && !showFollowButton
              ? 'last'
              : showFollowCountSegment
                ? 'middle'
                : 'middle'

    const followButtonPosition: SegmentPosition =
        segmentCount === 1 && showFollowButton ? 'only' : 'last'

    const showDividerAfterLike = showLikeButton && (showFollowButton || showFollowCountSegment)
    const showDividerBeforeFollowButton = showFollowCountSegment && showFollowButton

    const iconSize = 'w-5 h-5'
    const iconBox = variant === 'compact' ? 'w-5 h-5' : 'w-6 h-6'

    return (
        <div className="inline-flex overflow-visible" role="presentation">
            <div
                className={containerClass(variant)}
                role="group"
                aria-label={
                    showFollowButton && showLikeButton
                        ? `${likeTitle}, ${followTitle}`
                        : showLikeButton
                          ? likeTitle
                          : followTitle
                }
            >
                {showLikeButton && onToggleLike && (
                    <button
                        type="button"
                        tip={likeTitle}
                        aria-label={likeTitle}
                        onClick={onToggleLike}
                        className={segmentClass(variant, likePosition, true)}
                    >
                        <span
                            className={`relative inline-flex items-center justify-center ${iconBox} ${iconTone(isLiked, 'like', variant)}`}
                        >
                            {flyingHearts.map((id, index) => (
                                <span
                                    key={id}
                                    className={`absolute inset-0 flex items-center justify-center pointer-events-none ${HEART_FLY_ANIMATIONS[index] ?? HEART_FLY_ANIMATIONS[0]}`}
                                >
                                    <FaHeart className={`${iconSize} text-red-500 dark:text-red-400`} aria-hidden />
                                </span>
                            ))}
                            {isLiked ? (
                                <FaHeart className={iconSize} aria-hidden />
                            ) : (
                                <FaRegHeart className={iconSize} aria-hidden />
                            )}
                        </span>
                        <span className={textClass(variant, isLiked, 'like')}>{formatViews(likeCount)}</span>
                    </button>
                )}

                {showDividerAfterLike && <span className={dividerClass(variant)} aria-hidden />}

                {showFollowCountSegment && (
                    <FollowSegment
                        variant={variant}
                        position={followCountPosition}
                        interactive={!followCountReadOnly && Boolean(onToggleFollow)}
                        isFollowing={isFollowing}
                        followCount={followCount}
                        followTitle={followTitle}
                        onToggleFollow={followCountReadOnly ? undefined : onToggleFollow}
                        flyingStars={flyingStars}
                    />
                )}

                {showDividerBeforeFollowButton && <span className={dividerClass(variant)} aria-hidden />}

                {showFollowButton && onToggleFollow && (
                    <FollowSegment
                        variant={variant}
                        position={followButtonPosition}
                        interactive
                        isFollowing={isFollowing}
                        followCount={followCount}
                        followTitle={followTitle}
                        onToggleFollow={onToggleFollow}
                        flyingStars={flyingStars}
                    />
                )}
            </div>
        </div>
    )
}
