import * as React from "react";
import { memo } from "react";
import { View } from "react-native";

import { Channel, ChannelItem } from "../channel";
import { Loading } from "../loading";
import { LandingItem } from "../landing/landing";
import { Landing } from "../landing";
import { VideoItem } from "../video/video";
import { VideoPreview } from "../video/video-preview";
import { useFirebase } from "../../hooks/use-firebase/useFirebase";
import { ScrollView } from "react-native-gesture-handler";
import { PageContext } from "./page-context";

export const Page = memo(
  ({
    id,
    onVideoPress,
    onChangeChannel,
  }: {
    id: string;
    onVideoPress?: (video: VideoItem) => void;
    onChangeChannel?: (channel: ChannelItem) => void;
  }) => {
    const { loading, data } = useFirebase<
      ChannelItem | LandingItem | VideoItem
    >(`/objects/${id}`);

    const getComponentFromType = () => {
      if (data) {
        if (data.type === "video") {
          return <VideoPreview id={data._id} />;
        } else if (data.type === "channel") {
          return <Channel item={data}></Channel>;
        } else {
          return data.data.landing_content?.map((item, index) => (
            <Landing key={index} item={item} />
          ));
        }
      }
    };

    return (
      <PageContext.Provider
        value={{
          onChangeChannel: (channel) => {
            if (onChangeChannel) onChangeChannel(channel);
          },
          onVideoPress: (vdeoItem) => {
            if (onVideoPress) onVideoPress(vdeoItem);
          },
        }}
      >
        <ScrollView>
          <View style={{ flex: 1, padding: 10 }}>
            {loading ? <Loading /> : getComponentFromType()}
          </View>
        </ScrollView>
      </PageContext.Provider>
    );
  }
);
