import React, { useState } from 'react';
import YCImage from './YCImage';
import Button from './Button';

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

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

interface YounifyServicesProps
{
  onBrowseRequest: (services: StreamingService[]) => void | undefined
}

const YounifyServices = React.forwardRef((props: YounifyServicesProps, ref) =>
{
  const connect = Connect.shared;
  const [servicesState, setServicesState] = useState<StreamingService[]>([]);

  const linkOrManageService = async (service: StreamingService) =>
  {
    if (service.link?.isBroken ?? true)
      await connect.linkService(service, null);
    else
      await connect.manageLinkedService(service, null);

    updateService(service);
  };

  const unlinkService = async (service: StreamingService) =>
  {
    try
    {
      await connect.unlinkService(service, null);
      updateService(service);
    }
    catch (e)
    {
      Alert.alert(JSON.stringify(e));
    }
  };

  const updateService = (service: StreamingService) =>
  {
    setServicesState(o => o.map(v => v.equals(service) ? service : v));
  };

  React.useImperativeHandle(ref, () => ({
    async fetchServices()
    {
      try
      {
        let services = await connect.fetchServices(null);
        setServicesState(services);
      }
      catch (e: any)
      {
        console.log('YounifyServices: fetch services failed: ' + e);
      }
    },

    updateService(service: StreamingService)
    {
      updateService(service);
    }
  }));

  return(
    <View style={ styles.servicesView }>
      <ActivityIndicator animating={ servicesState.length == 0 } style={ styles.servicesLoadingIndicator }/>
      <FlatList
        style={ styles.servicesList }
        keyExtractor={ (service: StreamingService) => service.name }
        data={ servicesState }
        renderItem=
        {
          ({ item }: ListRenderItemInfo<StreamingService>) =>
          (
            <TouchableOpacity onPress={ () => { linkOrManageService(item) } }>
              <View style={ [ styles.serviceView ] }>
                <YCImage name="serviceImage" connect={ connect } url={ item.smallThumbnailUrl } style={ styles.serviceImage }/>
                { item.link?.isBroken && (<Image source={ require('./brokenServiceWarning.png') } style={ styles.serviceBrokenImage } />) }
                <View>
                    <Text style={ styles.serviceText }>{ item.name }</Text>
                    <Text style={ styles.serviceText }>{ item.link?.username }</Text>
                    <Text style={ styles.serviceText }>{ item.link?.profileName }</Text>
                </View>
                { item.link && (
                  <View style={ styles.serviceButtons }>
                    <Button title="Browse" onPress={ () => props.onBrowseRequest([item]) } />
                    <Button title="Logout" onPress={ () => unlinkService(item) } />
                  </View>
                ) }
              </View>
            </TouchableOpacity >
          )
        }
        ItemSeparatorComponent={ () => <View style={ styles.servicesListSeparator } /> }/>
        { (servicesState.length > 0) && (
          <Button title="Browse all" onPress={ async () =>
          {
            var services = await connect.fetchLinkedServices(null);
            props.onBrowseRequest(services);
          }}/>
        )}
    </View>
  )
});

const styles = StyleSheet.create(
{
  servicesView:
  {
    paddingTop: 20,
    paddingLeft: 10,
    paddingRight: 10,
    flex: 1,
  },
  servicesLoadingIndicator:
  {
    position: 'absolute',
    top: '50%',
    left: '50%'
  },
  servicesList:
  {
  },
  servicesListSeparator:
  {
    height: 5
  },
  serviceView:
  {
    flexDirection: 'row',
    gap: 6,
  },
  serviceImage:
  {
    width: 50,
    height: 50
  },
  serviceBrokenImage:
  {
    width: 20,
    height: 20,
    position: 'absolute',
    top: 30,
    left: 30
  },
  serviceText:
  {
    fontSize: 12
  },
  serviceButtons:
  {
    height: 30,
    position: 'absolute',
    right: 0,
    gap: 6,
    flexDirection: 'row'
  }
});

export default YounifyServices;