import React, { useState } from 'react';
import { useNavigation } from '@react-navigation/native';
import YCImage from './YCImage';
import Button from './Button';

import
{
  StyleSheet,
  View,
  Text,
  Alert,
  FlatList,
  ActivityIndicator,
  TouchableOpacity,
  type ListRenderItemInfo,
} from 'react-native';

import
{
  Connect,
  CancellationTicket,
  StreamingContentType,
  type StreamingContent,
  type StreamingService
} from 'react-native-younify-connect-sdk';

interface YounifyBrowseProps
{
  onDetailsRequest: (content: StreamingContent) => void | undefined
  onServiceUpdateRequest: (service: StreamingService) => void | undefined
}

const YounifyBrowse = React.forwardRef((props: YounifyBrowseProps, ref) =>
{
  const connect = Connect.shared;
  const navigation = useNavigation();

  interface BrowseState
  {
    content: StreamingContent[];
    isLoading: boolean;
  }

  const [browseState, setBrowseState] = useState<BrowseState>();
  const [cancellationState, setCancellationState] = useState<CancellationTicket>();

  const browseContent = async (item: StreamingContent) =>
  {
    try
    {
      if (item.type.toString() == StreamingContentType[StreamingContentType.Video])
      {
        props.onDetailsRequest(item);
        return;
      }

      let children: StreamingContent[] = [];
      setBrowseState({ content: [], isLoading: true });

      try
      {
        children = await connect.fetchContentChildren(item, null);
      }
      finally
      {
        setBrowseState({ content: children, isLoading: false });
      }
    }
    catch (e: any)
    {
      console.log("browse content failed: " + e);
      Alert.alert(e);
    }
  };

  const searchContent = async (services: StreamingService[], searchTerms: string ) =>
  {
    var searchResults: StreamingContent[] = [];
    setBrowseState({ content: [], isLoading: true });

    try
    {
      let cancellationTicket = new CancellationTicket();
      setCancellationState(cancellationTicket);

      await connect.searchContent(
        services,
        searchTerms,
        cancellationTicket,
        (service, content, error) =>
        {
          console.log('search content service: ' + service.name + ', content count: ' + content.length + ', error: ' + (error ? error.message : 'none'));
          searchResults = [...searchResults, ...content];
          setBrowseState({ content: searchResults, isLoading: true } );
          props.onServiceUpdateRequest(service);
        });
    }
    catch (e: any)
    {
      console.log('search failed: ' + e);
      Alert.alert(e);
    }

    setBrowseState({ content: searchResults, isLoading: false } );
  };

  React.useImperativeHandle(ref, () => ({
    async browseContent(item: StreamingContent)
    {
      await browseContent(item);
    },
    async searchContent(services: StreamingService[], searchTerm: string)
    {
      await searchContent(services, searchTerm);
    }
  }));

  return(
    <View style={ styles.browseView }>
      <View style={ styles.backButtonView }>
        <Button title=" < Back " onPress={ () =>
          {
            if (cancellationState)
              cancellationState.cancel();

            navigation.goBack()
          }} />
      </View>
      <ActivityIndicator animating={ browseState?.isLoading } />
      <FlatList
        data={ browseState?.content }
        renderItem=
        {
          ({ item }: ListRenderItemInfo<StreamingContent>) =>
            (
              <TouchableOpacity onPress={ () => { browseContent(item); } }>
                <View style={ [ styles.serviceView ] }>
                  <YCImage name="browseImage" connect={ connect } url={ item.smallThumbnailUrl!! } style={ styles.contentItemSmallImage } />
                  <View>
                      <Text>{ item.title }</Text>
                  </View>
                </View>
              </TouchableOpacity>
            )
        }
        ItemSeparatorComponent={ () => <View style={ styles.servicesListSeparator } /> } />
    </View>
  )
});

const styles = StyleSheet.create
(
  {
    backButtonView:
    {
      alignItems: 'flex-start',
    },
    serviceView:
    {
      flexDirection: 'row',
      gap: 6,
    },
    contentItemSmallImage:
    {
      width: 86,
      height: 48,
    },
    servicesListSeparator:
    {
      height: 5
    },
    browseView:
    {
      paddingTop: 20,
      paddingLeft: 10,
      paddingRight: 10,
      flex: 1,
    }
  }
);

export default YounifyBrowse;