import { useNavigate } from "@remix-run/react";
import type { ReactNode} from "react";
import { useEffect, useState } from "react";
import type { StationWithTagsClientSide } from "~/models/station.server";
import {  getStationUrl } from "~/utils";

export type StationPlayerProps = {
    station: StationWithTagsClientSide | null,
    nextPrevStationIds: {
        prev?: string;
        next?: string;
    },
};

export function StationPlayer({ station, nextPrevStationIds }: StationPlayerProps) {
    const [player, setPlayer] = useState<ReactNode | null>(null);
    const route = useNavigate();

    useEffect(() => {
        if (typeof window === 'undefined') return;
        const importComponent = async () => {
            if (!station) return;
            try {
                
                const module = await import('react-radio-player');
                const RadioBottomBarPlayer = module.RadioBottomBarPlayer;
                setPlayer(<RadioBottomBarPlayer 
                  streamUrl={station.streamUrl} 
                  title={station.name} 
                  description={station.description || undefined}
                  image={station.imgUrl}
                  isNextButtonDisabled={!nextPrevStationIds.next}
                  isPrevButtonDisabled={!nextPrevStationIds.prev}
                  onNextButtonClicked={() => {
                    if (!nextPrevStationIds.next) return;
                    route(getStationUrl(nextPrevStationIds.next))
                  }}
                  onPrevButtonClicked={() => {
                    if (!nextPrevStationIds.prev) return;
                    route(getStationUrl(nextPrevStationIds.prev))
                  }}
                  secondDescription={station.popularity ? <>&#9733;  {station.popularity}</> : undefined}
                  />);
            } catch (error) {
                console.log('rerrerer', error)
            }
        };
        importComponent()
    }, [station, nextPrevStationIds, route])
  
    if (!station || !player) {
        return <></>;
    }
    return (
        <div
            className="fixed bottom-0 right-0 w-full lg:w-[calc(100vw-20rem)] h-[90px] z-50">
                {player}
        </div>
    );
}
