import * as React from "react";
import { useCallback, memo, useContext } from "react";
import { View, Image, TouchableOpacity, ActivityIndicator } from "react-native";
import { VideoItem } from "./video";
import { Loading } from "../loading";
import { SiteImage } from "../site-image";
import { formatDistanceStrict } from "date-fns";
import { style } from "./style";
import { ContentText } from "../content-text";
import { useFirebase } from "../../hooks/use-firebase/useFirebase";
import PremiumLabel from "./premium-label";
import { PageContext } from "../page/page-context";
import * as welcomeScreen from "../../assets/images/no-thumbnail.png";
export interface VideoPreviewProps {
  id: string;
  detailsPosition?: "right" | "bottom";
  onPress?: (video: VideoItem) => any;
}

export const VideoPreview = memo(
  ({ id, detailsPosition = "right", onPress }: VideoPreviewProps) => {
    const page = useContext(PageContext);
    const { loading, data } = useFirebase<VideoItem>(`/objects/${id}`);

    const goToVideo = () => {
      page.onVideoPress(data as VideoItem);
    };
    const thumbnail =
      data?.data.metadata?.snippet?.thumbnails.medium.url ||
      data?.renderer.thumbnail;

    return loading ? (
      <Loading />
    ) : (
      <TouchableOpacity
        onPress={goToVideo}
        style={{
          ...style.container,
          ...(detailsPosition === "bottom" ? { flexDirection: "column" } : {}),
        }}
      >
        {data?.renderer?.subscriptions ? <PremiumLabel /> : null}

        <View
          style={{
            ...style.thumbnail,
            ...(detailsPosition === "bottom" ? { marginRight: 0 } : {}),
          }}
        >
          {thumbnail ? (
            <SiteImage
              resizeMethod="resize"
              src={thumbnail}
              setOriginalSize
              fit
            />
          ) : (
            <ActivityIndicator size="large" color="#0000ff" />
          )}
          {data?.data?.metadata?.contentDetails?.duration ? (
            <ContentText style={style.duration}>
              {data?.data?.metadata?.contentDetails?.duration}
            </ContentText>
          ) : null}
        </View>
        <View style={style.details}>
          <ContentText
            style={style.title}
            numberOfLines={detailsPosition === "bottom" ? 1 : undefined}
          >
            {data?.data.name}
          </ContentText>
          <ContentText style={style.time}>
            {formatDistanceStrict(new Date(data?.created || 0), new Date())} ago
          </ContentText>
        </View>
      </TouchableOpacity>
    );
  }
);
