import { Box, Flex } from '@chakra-ui/react';
import { LuTrash2 } from 'react-icons/lu';
import {
  MdEdit,
  MdKeyboardDoubleArrowDown,
  MdKeyboardDoubleArrowUp,
  MdRemove,
} from 'react-icons/md';
import { Route, Routes, useNavigate } from 'react-router-dom';

import { EmptyEnd } from '@/components/EmptyEnd';
import { PageLayout } from '@/components/Layout/PageLayout';
import { PageLayoutInfoCenter } from '@/components/Layout/PageLayoutInfoCenter';
import { DisplayMediaFullId } from '@/components/media/DisplayMediaFullId';
import { SeasonEditPopUp } from '@/components/popup/AlbumEditPopUp';
import { MediaEditPopUp } from '@/components/popup/TrackEditPopUp';
import { BUTTON_TOP_BAR_PROPERTY, TopBar } from '@/components/TopBar/TopBar';
import { Button } from '@/components/ui/button';
import { useColorModeValue } from '@/components/ui/color-mode';
import { BASE_WRAP_SPACING } from '@/constants/genericSpacing';
import { useActivePlaylistService } from '@/service/ActivePlaylist';

export const OnAirPage = () => {
  const { playInList } = useActivePlaylistService();
  const { playMediaList, MediaOffset, setNewPlaylist } =
    useActivePlaylistService();
  const navigate = useNavigate();
  const onSelectItem = (MediaId: number) => {
    let currentPlay = 0;
    if (!playMediaList) {
      console.log('Fail to get list of on air...');
      return;
    }
    for (let iii = 0; iii < playMediaList.length; iii++) {
      if (playMediaList[iii] === MediaId) {
        currentPlay = iii;
      }
    }
    playInList(currentPlay, playMediaList);
  };
  const removeMedia = (MediaId: number) => {
    let elementToRemoveOffset = 0;
    if (!playMediaList) {
      console.log('Fail to remove element of on air...');
      return;
    }
    const newList: number[] = [];
    for (let iii = 0; iii < playMediaList.length; iii++) {
      if (playMediaList[iii] === MediaId) {
        elementToRemoveOffset = iii;
      } else {
        newList.push(playMediaList[iii]);
      }
    }
    let newPlayed = MediaOffset;
    if (newPlayed != undefined) {
      if (elementToRemoveOffset < newPlayed) {
        newPlayed = newPlayed - 1;
      }
      playInList(newPlayed, newList);
    } else {
      setNewPlaylist(newList);
    }
  };
  const removePreviousMedia = (index: number) => {
    if (!playMediaList) {
      console.log('Fail to remove element of on air...');
      return;
    }
    const newList = playMediaList.slice(index);
    let newPlayed = MediaOffset;
    if (newPlayed != undefined) {
      if (index < newPlayed) {
        newPlayed = newPlayed - index;
      } else {
        newPlayed = 0;
      }
      playInList(newPlayed, newList);
    } else {
      setNewPlaylist(newList);
    }
  };
  const removeNextMedia = (index: number) => {
    if (!playMediaList) {
      console.log('Fail to remove element of on air...');
      return;
    }
    const newList = playMediaList.slice(0, index + 1);
    playInList(MediaOffset, newList);
  };

  const clean = () => {
    setNewPlaylist([]);
  };

  console.log(`playMediaList = ${JSON.stringify(playMediaList, null, 2)}`);
  if (!playMediaList || playMediaList.length == 0) {
    return (
      <>
        <TopBar title="Season detail" />
        <PageLayoutInfoCenter>
          No data is currently playing...
        </PageLayoutInfoCenter>
      </>
    );
  }
  return (
    <>
      <TopBar title="On Air ...">
        <Button {...BUTTON_TOP_BAR_PROPERTY} onClick={clean}>
          <LuTrash2 />
        </Button>
      </TopBar>
      <PageLayout>
        <Flex
          direction="column"
          gap={BASE_WRAP_SPACING}
          marginX="auto"
          padding="20px"
          width="80%"
        >
          {!playMediaList && <>No playing</>}
          {playMediaList &&
            playMediaList?.map((data, index) => (
              <Box
                minWidth="100%"
                //height="60px"
                border="1px"
                borderColor="brand.900"
                backgroundColor={useColorModeValue('#FFFFFF88', '#00000088')}
                key={data}
                padding="5px"
                as="button"
                _hover={{
                  boxShadow: 'outline-over',
                  bgColor: useColorModeValue('#FFFFFFF7', '#000000F7'),
                }}
              >
                <DisplayMediaFullId
                  MediaId={data}
                  onClick={() => onSelectItem(data)}
                  contextMenu={[
                    {
                      name: 'Edit',
                      icon: <MdEdit />,
                      onClick: () => {
                        navigate(`edit-Media/${data}`);
                      },
                    },
                    {
                      name: 'Remove previous',
                      icon: <MdKeyboardDoubleArrowUp />,
                      onClick: () => {
                        removePreviousMedia(index);
                      },
                    },
                    {
                      name: 'Remove',
                      icon: <MdRemove />,
                      onClick: () => {
                        removeMedia(data);
                      },
                    },
                    {
                      name: 'Remove After',
                      icon: <MdKeyboardDoubleArrowDown />,
                      onClick: () => {
                        removeNextMedia(index);
                      },
                    },
                  ]}
                />
              </Box>
            ))}
          <EmptyEnd />
        </Flex>
        <Routes>
          <Route path="edit-Media/:MediaId" element={<MediaEditPopUp />} />
          <Route path="edit-Season/:SeasonId" element={<SeasonEditPopUp />} />
        </Routes>
      </PageLayout>
    </>
  );
};
