import type { FC } from 'react';
import React, { useEffect } from 'react';
import Hls from 'hls.js';
import { useTrackAudioQuery } from 'src/data/queries';

export interface Props {
    tuid: string;
    hls: Hls | null;
    setHls: (obj: Hls | null) => void;
    onPlay: () => void;
    onEnded: () => void;
}

export const ProductTrackAudioPlayer: FC<Props> = ({
    tuid,
    hls,
    setHls,
    onPlay,
    onEnded,
}) => {
    const { data } = useTrackAudioQuery({
        tuid,
        isCorrection: true,
    });

    const configureHls = (manifestUrl?: string | undefined | null) => {
        if (manifestUrl && Hls.isSupported()) {
            const config: {
                manifestLoadingTimeOut: number;
                manifestLoadingMaxRetry: number;
                xhrSetup?: (xhr: { withCredentials: boolean }) => void;
            } = {
                manifestLoadingTimeOut: 20000,
                manifestLoadingMaxRetry: 3,
            };
            // Quick fix to include credentials only when streaming content
            // from AWS.
            const url = new URL(manifestUrl);
            if (url.hostname.includes('aws')) {
                config.xhrSetup = (xhr: { withCredentials: boolean }) => {
                    // eslint-disable-next-line no-param-reassign
                    xhr.withCredentials = true;
                };
            }
            setHls(new Hls(config));
        }
        return () => setHls(null);
    };

    const loadAudio = (manifestUrl?: string | undefined | null) => {
        const playerElement = document.getElementById(
            `product-track-${tuid}-audio-player`
        );
        if (hls && manifestUrl && playerElement instanceof HTMLAudioElement) {
            hls.on(Hls.Events.MEDIA_ATTACHED, () => {
                hls.loadSource(manifestUrl);
                void playerElement.play();
            });
            hls.attachMedia(playerElement);
        }
    };

    // eslint-disable-next-line react-hooks/exhaustive-deps
    useEffect(() => configureHls(data?.track?.streamingAudioUrl), [data]);
    useEffect(() => {
        if (hls) {
            loadAudio(data?.track?.streamingAudioUrl);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [hls, data]);

    return (
        <div className="product-track-audio-player">
            {
                <audio
                    id={`product-track-${tuid}-audio-player`}
                    data-testid={`product-track-${tuid}-audio-player`}
                    onPlay={onPlay}
                    onEnded={onEnded}
                />
            }
        </div>
    );
};
