// React
import React, { useEffect, useRef, forwardRef, useImperativeHandle } from "react";


// UI
import "@/components/Base/KPlayer/KPlayer.css";

// @ts-ignore
import KPlayerScript from "@/components/Base/KPlayer/KPlayerScript";


// Interface
import { Ref } from "react";

export interface KPlayerSong {
  id: number
  title: string
  artist: string
  album: string
  alias: string
  cover: string
  link: string
  lyric: string
  sub_lyric: string
}

export interface KPlayerProps {}

export interface KPlayerRef {
  add: (songs: KPlayerSong[]) => void
  remove: () => void
}

type IContainer = typeof KPlayerScript


// Components
function KPlayer(props: KPlayerProps, ref: Ref<KPlayerRef>) {
  const playerRef = useRef<IContainer>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  useImperativeHandle(ref, () => ({
    add: (songs) => {
      playerRef.current && playerRef.current.add(songs);
    },
    remove: () => {
      playerRef.current && playerRef.current.remove();
    }
  }));

  useEffect(() => {
    if (!containerRef.current) return;

    playerRef.current = new KPlayerScript({
      container: containerRef.current,
      playlist: [],
      show_list: true
    });

    return () => {
      // Todo
      // kp.destroy();
    }

  }, []);

  return (
    <div ref={containerRef}></div>
  )
}

export default forwardRef(KPlayer);
