import * as React from "react";
import { useCallback, useContext } from "react";
import { View, TouchableOpacity } from "react-native";
import { ChannelItem } from "../channel";
import { SiteImage } from "../site-image";
import { Page as PageItem } from "./landing";
import { useFirebase } from "../../hooks/use-firebase/useFirebase";
import { PageContext } from "../page/page-context";

export interface PagesProps {
  pages: PageItem[];
}

const Page = ({ id }: { title: string; id: string }) => {
  const { onChangeChannel } = useContext(PageContext);
  const { loading, data } = useFirebase<ChannelItem>(`/objects/${id}`);
  const onItemPress = useCallback(() => {
    onChangeChannel(data as ChannelItem);
  }, [id]);

  return !loading && data ? (
    <TouchableOpacity onPress={onItemPress} style={{ flex: 1 }}>
      <SiteImage
        src={data.data.channel_select_active_image_url}
        setOriginalSize
        fit
      />
    </TouchableOpacity>
  ) : null;
};

export const Pages = ({ pages }: PagesProps) => {
  return (
    <View
      style={{
        flexDirection: "row",
        justifyContent: "space-evenly",
        marginBottom: 20,
      }}
    >
      {pages.map((item) => (
        <Page
          key={item.page._id}
          title={item.page.seo.title}
          id={item.page._id}
        ></Page>
      ))}
    </View>
  );
};
