import clsx from 'clsx';
import { AnimatePresence, HTMLMotionProps, motion, Variants } from 'motion/react';
import { Fragment, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { generatePath } from 'react-router';
import { Link } from 'react-router';

import styles from './full-screen-player-image.module.css';

import { useFastAverageColor } from '/@/renderer/hooks';
import { AppRoute } from '/@/renderer/router/routes';
import {
    calculateNextSong,
    subscribeCurrentTrack,
    usePlayerData,
    usePlayerStoreBase,
} from '/@/renderer/store';
import { useSettingsStore } from '/@/renderer/store/settings.store';
import { Badge } from '/@/shared/components/badge/badge';
import { Center } from '/@/shared/components/center/center';
import { Flex } from '/@/shared/components/flex/flex';
import { Group } from '/@/shared/components/group/group';
import { Icon } from '/@/shared/components/icon/icon';
import { Stack } from '/@/shared/components/stack/stack';
import { Text } from '/@/shared/components/text/text';
import { useSetState } from '/@/shared/hooks/use-set-state';

const imageVariants: Variants = {
    closed: {
        opacity: 0,
        transition: {
            duration: 0.8,
            ease: 'linear',
        },
    },
    initial: {
        opacity: 0,
    },
    open: (custom) => {
        const { isOpen } = custom;
        return {
            opacity: isOpen ? 1 : 0,
            transition: {
                duration: 0.4,
                ease: 'linear',
            },
        };
    },
};

const scaleImageUrl = (imageSize: number, url?: null | string) => {
    return url
        ?.replace(/&size=\d+/, `&size=${imageSize}`)
        .replace(/\?width=\d+/, `?width=${imageSize}`)
        .replace(/&height=\d+/, `&height=${imageSize}`);
};

const MotionImage = motion.img;

const ImageWithPlaceholder = ({
    className,
    ...props
}: HTMLMotionProps<'img'> & { placeholder?: string }) => {
    const nativeAspectRatio = useSettingsStore((store) => store.general.nativeAspectRatio);

    if (!props.src) {
        return (
            <Center
                style={{
                    background: 'var(--theme-colors-surface)',
                    borderRadius: 'var(--theme-card-default-radius)',
                    height: '100%',
                    width: '100%',
                }}
            >
                <Icon color="muted" icon="itemAlbum" size="25%" />
            </Center>
        );
    }

    return (
        <MotionImage
            className={clsx(styles.image, className)}
            style={{
                objectFit: nativeAspectRatio ? 'contain' : 'cover',
                width: nativeAspectRatio ? 'auto' : '100%',
            }}
            {...props}
        />
    );
};

export const FullScreenPlayerImage = () => {
    const mainImageRef = useRef<HTMLImageElement | null>(null);
    const [mainImageDimensions, setMainImageDimensions] = useState({ idealSize: 1 });

    const albumArtRes = useSettingsStore((store) => store.general.albumArtRes);

    const { currentSong, nextSong } = usePlayerData();
    const { background } = useFastAverageColor({
        algorithm: 'dominant',
        src: currentSong?.imageUrl,
        srcLoaded: true,
    });
    const imageKey = `image-${background}`;
    const [imageState, setImageState] = useSetState({
        bottomImage: scaleImageUrl(mainImageDimensions.idealSize, nextSong?.imageUrl),
        current: 0,
        topImage: scaleImageUrl(mainImageDimensions.idealSize, currentSong?.imageUrl),
    });

    const updateImageSize = useCallback(() => {
        if (mainImageRef.current) {
            const state = usePlayerStoreBase.getState();
            const playerData = state.getQueue();
            const currentIndex = state.player.index;
            const current = playerData.items[currentIndex];
            const next = calculateNextSong(currentIndex, playerData.items, state.player.repeat);

            setMainImageDimensions({
                idealSize:
                    albumArtRes ||
                    Math.ceil((mainImageRef.current as HTMLDivElement).offsetHeight / 100) * 100,
            });

            setImageState({
                bottomImage: scaleImageUrl(mainImageDimensions.idealSize, next?.imageUrl),
                current: 0,
                topImage: scaleImageUrl(mainImageDimensions.idealSize, current?.imageUrl),
            });
        }
    }, [mainImageDimensions.idealSize, setImageState, albumArtRes]);

    useLayoutEffect(() => {
        updateImageSize();
    }, [updateImageSize]);

    // Use ref to track current image state to avoid recreating subscription
    const imageStateRef = useRef(imageState);
    useEffect(() => {
        imageStateRef.current = imageState;
    }, [imageState]);

    useEffect(() => {
        const unsubSongChange = subscribeCurrentTrack(({ index, song }, prev) => {
            // Only update if the song actually changed
            if (song?._uniqueId === prev.song?._uniqueId) {
                return;
            }

            // Use ref to get current state without causing dependency issues
            const isTop = imageStateRef.current.current === 0;
            const state = usePlayerStoreBase.getState();
            const queue = state.getQueue();
            const currentSong = queue.items[index];
            const nextSong = calculateNextSong(index, queue.items, state.player.repeat);

            const currentImageUrl = scaleImageUrl(
                mainImageDimensions.idealSize,
                currentSong?.imageUrl,
            );
            const nextImageUrl = scaleImageUrl(mainImageDimensions.idealSize, nextSong?.imageUrl);

            setImageState({
                bottomImage: isTop ? currentImageUrl : nextImageUrl,
                current: isTop ? 1 : 0,
                topImage: isTop ? nextImageUrl : currentImageUrl,
            });
        });

        return () => {
            unsubSongChange();
        };
    }, [mainImageDimensions.idealSize, setImageState]);

    return (
        <Flex
            align="center"
            className={clsx(styles.playerContainer, 'full-screen-player-image-container')}
            direction="column"
            justify="flex-start"
            p="1rem"
        >
            <div className={styles.imageContainer} ref={mainImageRef}>
                <AnimatePresence initial={false} mode="sync">
                    {imageState.current === 0 && (
                        <ImageWithPlaceholder
                            animate="open"
                            className="full-screen-player-image"
                            custom={{ isOpen: imageState.current === 0 }}
                            draggable={false}
                            exit="closed"
                            initial="closed"
                            key={imageKey}
                            placeholder="var(--theme-colors-foreground-muted)"
                            src={imageState.topImage || ''}
                            variants={imageVariants}
                        />
                    )}

                    {imageState.current === 1 && (
                        <ImageWithPlaceholder
                            animate="open"
                            className="full-screen-player-image"
                            custom={{ isOpen: imageState.current === 1 }}
                            draggable={false}
                            exit="closed"
                            initial="closed"
                            key={imageKey}
                            placeholder="var(--theme-colors-foreground-muted)"
                            src={imageState.bottomImage || ''}
                            variants={imageVariants}
                        />
                    )}
                </AnimatePresence>
            </div>
            <Stack className={styles.metadataContainer} gap="md" maw="100%">
                <Text fw={900} lh="1.2" overflow="hidden" size="4xl" w="100%">
                    {currentSong?.name}
                </Text>
                <Text
                    component={Link}
                    isLink
                    overflow="hidden"
                    size="xl"
                    to={generatePath(AppRoute.LIBRARY_ALBUMS_DETAIL, {
                        albumId: currentSong?.albumId || '',
                    })}
                    w="100%"
                >
                    {currentSong?.album}
                </Text>
                <Text key="fs-artists">
                    {currentSong?.artists?.map((artist, index) => (
                        <Fragment key={`fs-artist-${artist.id}`}>
                            {index > 0 && (
                                <Text
                                    style={{
                                        display: 'inline-block',
                                        padding: '0 0.5rem',
                                    }}
                                >
                                    •
                                </Text>
                            )}
                            <Text
                                component={Link}
                                isLink
                                to={generatePath(AppRoute.LIBRARY_ALBUM_ARTISTS_DETAIL, {
                                    albumArtistId: artist.id,
                                })}
                            >
                                {artist.name}
                            </Text>
                        </Fragment>
                    ))}
                </Text>
                <Group justify="center" mt="sm">
                    {currentSong?.container && (
                        <Badge variant="transparent">{currentSong?.container}</Badge>
                    )}
                    {currentSong?.releaseYear && (
                        <Badge variant="transparent">{currentSong?.releaseYear}</Badge>
                    )}
                </Group>
            </Stack>
        </Flex>
    );
};
