import * as React from "react";
import { useEffect, memo } from "react";
import { Image, TouchableOpacity, Easing } from "react-native";
import useChannelSelect from "../../components/channel-select/hooks/use-channel-select";
import useGetAbsoluteUrl from "../../hooks/use-get-absolute-url";
import { useFirebases } from "../../hooks/use-firebase/useFirebase";
import { ChannelItem } from "../channel";
import Modal from "react-native-modal";
import { useSiteSettings } from "../../providers/site";
import {
  ChannelContainer,
  ChannelItemContainer,
  Head,
  ChannelSelectedLine,
  ShowChannel,
} from "./styled";
import Typography from "../ui/typography";
import Icon from "react-native-vector-icons/MaterialIcons";
import { SafeAreaView } from "react-native-safe-area-context";
const myIcon = <Icon name="arrow-drop-up" size={40} color="white" />;
export interface Channel<T> {
  imgUri: string;
  title: string;
  metadata: T;
}

export type Props<T> = {
  visible: boolean;
  onClose: () => void;
  channels: Channel<T>[];
  channelSelectedIndex: number;
  onChannelPress: (channel: Channel<T>, index: number) => void;
};
const easing = Easing.bezier(0.34, 1.56, 0.64, 1);
function ChannelSelect<T>({
  visible,
  onClose,
  channels,
  channelSelectedIndex,
  onChannelPress,
}: Props<T>) {
  const { style: siteStyle } = useSiteSettings();

  return (
    <Modal
      useNativeDriver
      animationIn="fadeInDown"
      animationInTiming={150}
      animationOut="fadeOutUp"
      animationOutTiming={150}
      style={{
        margin: 0,
      }}
      isVisible={visible}
    >
      <SafeAreaView
        style={{
          height: "100%",
          backgroundColor: siteStyle.title_background_color,
        }}
      >
        <TouchableOpacity onPress={onClose} activeOpacity={0.8}>
          <Head style={{ backgroundColor: siteStyle.title_background_color }}>
            <Typography color="white" variant="body1">
              CHANNELS
            </Typography>
            {myIcon}
          </Head>
        </TouchableOpacity>
        <ChannelContainer>
          {channels.map((channel, index) => (
            <ChannelItemContainer
              key={index}
              activeOpacity={0.8}
              onPress={() => {
                onChannelPress(channel, index);
              }}
            >
              <ShowChannel duration={0.2} delay={index * 0.05} easing={easing}>
                <Image
                  style={{ width: 180, height: 120 }}
                  resizeMode="contain"
                  source={{ uri: channel.imgUri }}
                />
              </ShowChannel>
              {channelSelectedIndex === index ? <ChannelSelectedLine /> : null}
            </ChannelItemContainer>
          ))}
        </ChannelContainer>
      </SafeAreaView>
    </Modal>
  );
}

export type ChannelSelectProps = {
  open: boolean;
  onClose: () => void;
  onChannelPress?: (channel: ChannelItem) => void;
};

export default memo(({ onClose, open, onChannelPress }: ChannelSelectProps) => {
  const {
    regions: {
      "channel-select": { pages },
    },
  } = useSiteSettings();
  const fetchedPages = useFirebases<ChannelItem>(
    pages.map((page) => `/objects/${page.page._id}`)
  );

  const getAbsoluteUrl = useGetAbsoluteUrl();
  const { channelSelect, currentChannel } = useChannelSelect<ChannelItem>(
    fetchedPages
      .filter(({ loading }) => !loading)
      .map(({ data: channel }) => ({
        title: channel.seo.title,
        imgUri: getAbsoluteUrl(
          channel.data.channel_select_active_image_url || ""
        ),
        metadata: channel,
      })),
    (channel) => {},
    open
  );

  useEffect(() => {
    if (currentChannel)
      if (onChannelPress) onChannelPress(currentChannel.metadata);
    onClose();
  }, [currentChannel ? currentChannel.metadata._id : undefined]);

  return (
    <ChannelSelect
      visible={open}
      onClose={onClose}
      channels={channelSelect.channels}
      channelSelectedIndex={channelSelect.channelSelectedIndex}
      onChannelPress={channelSelect.onChannelPress}
    />
  );
});
