import React, { useContext } from 'react';
import {
  Animated,
  Dimensions,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import { ApplicationContext, MiniAppContext } from '../../Context';
import { exportFontFamily, Text, useScaleSize } from '../../Text';
import { Colors, Radius, Spacing, Styles } from '../../Consts';
import {
  TitleJourneyProps,
  TitleLocationProps,
  TitleUserProps,
} from '../types';
import { Image } from '../../Image';
import { Icon } from '../../Icon';
import { Skeleton } from '../../Skeleton';

/**
 * default header title used for nav
 */
const HeaderTitle: React.FC<any> = props => {
  const context = useContext<any>(MiniAppContext);

  const showBaseLineDebug = context?.features?.showBaseLineDebug ?? false;

  const opacity = props.animatedValue?.interpolate(
    props.interpolate ?? {
      inputRange: [0, 200],
      outputRange: [0, 1],
      extrapolate: 'clamp',
    },
  );

  return (
    <View
      pointerEvents={'none'}
      style={[
        {
          justifyContent: 'center',
          maxWidth: Dimensions.get('window').width - 172,
        },
        showBaseLineDebug && styles.debugBaseLine,
      ]}
    >
      <Animated.Text
        {...props}
        allowFontScaling={false}
        accessibilityLabel={'title_navigation_header'}
        style={[
          {
            fontSize: useScaleSize(15),
            lineHeight: useScaleSize(22),
            fontWeight: 'bold',
          },
          {
            fontFamily: exportFontFamily('bold', 'action_xs_bold'),
            opacity,
            color: props.tintColor,
          },
        ]}
        numberOfLines={1}
      />
    </View>
  );
};

/**
 * Title custom for header
 * @constructor
 */
const TitleCustom: React.FC<any> = ({ type, data, ...props }) => {
  switch (type) {
    case 'user':
      return <TitleUser {...(data as TitleUserProps)} {...props} />;
    case 'location':
      return <TitleLocation {...(data as TitleLocationProps)} {...props} />;
    case 'journey':
      return <TitleJourney {...(data as TitleJourneyProps)} {...props} />;
    default:
      return <View />;
  }
};

/**
 * Header user title
 * @constructor
 */
const TitleUser: React.FC<TitleUserProps> = ({
  title,
  subTitle,
  image: image,
  tintColor,
  dotColor,
  onPress,
  verify,
  icons,
  isLoading,
}) => {
  const { theme } = useContext(ApplicationContext);
  const maxWidth = Dimensions.get('window').width - 172;
  const getShortName = (name: string) => {
    const words = name.split(' ');
    const lastTwoWords = words.slice(-2);
    return lastTwoWords.map(word => word.charAt(0).toUpperCase()).join('');
  };

  const renderImage = () => {
    const avatarWidth = Spacing.XXL;
    if (Array.isArray(image) && image.length > 0) {
      switch (image.length) {
        case 1: {
          return image.map((i: string) => (
            <Image
              key={`avatar-${i}`}
              source={{ uri: i }}
              style={styles.circle}
            />
          ));
        }
        case 2: {
          return (
            <View style={[Styles.flex, styles.groupAvtContainer]}>
              <Image
                source={{ uri: image[0] }}
                style={[
                  styles.circleMedium,
                  { position: 'absolute', top: 0, right: 0, zIndex: 0 },
                ]}
              />
              <Image
                source={{ uri: image[1] }}
                style={[
                  styles.circleMedium,
                  { position: 'absolute', left: 0, bottom: 0, zIndex: 1 },
                ]}
              />
            </View>
          );
        }
        case 3: {
          return (
            <View style={[Styles.flex, styles.groupAvtContainer]}>
              <Image
                source={{ uri: image[0] }}
                style={[
                  styles.circleSmall,
                  { position: 'absolute', bottom: 2, right: 2, zIndex: 0 },
                ]}
              />
              <Image
                source={{ uri: image[1] }}
                style={[
                  styles.circleSmall,
                  {
                    position: 'absolute',
                    top: 2,
                    left: avatarWidth / 2 - 16 / 2,
                    zIndex: 1,
                  },
                ]}
              />
              <Image
                source={{ uri: image[2] }}
                style={[
                  styles.circleSmall,
                  { position: 'absolute', left: 2, bottom: 2, zIndex: 2 },
                ]}
              />
            </View>
          );
        }
        case 4: {
          return (
            <View style={[Styles.flex, styles.groupAvtContainer]}>
              <Image
                source={{ uri: image[0] }}
                style={[
                  styles.circleSmall,
                  { position: 'absolute', bottom: 2, left: 2, zIndex: 0 },
                ]}
              />
              <Image
                source={{ uri: image[1] }}
                style={[
                  styles.circleSmall,
                  { position: 'absolute', bottom: 2, right: 2, zIndex: 1 },
                ]}
              />
              <Image
                source={{ uri: image[2] }}
                style={[
                  styles.circleSmall,
                  { position: 'absolute', top: 2, right: 2, zIndex: 2 },
                ]}
              />
              <Image
                source={{ uri: image[2] }}
                style={[
                  styles.circleSmall,
                  { position: 'absolute', top: 2, left: 2, zIndex: 3 },
                ]}
              />
            </View>
          );
        }
        default: {
          return (
            <View style={[Styles.flex, styles.groupAvtContainer]}>
              <Image
                source={{ uri: image[0] }}
                style={[
                  styles.circleSmall,
                  { position: 'absolute', left: 2, bottom: 2, zIndex: 0 },
                ]}
              />
              <Image
                source={{ uri: image[1] }}
                style={[
                  styles.circleSmall,
                  { position: 'absolute', top: 2, right: 2, zIndex: 2 },
                ]}
              />
              <Image
                source={{ uri: image[2] }}
                style={[
                  styles.circleSmall,
                  { position: 'absolute', left: 2, top: 2, zIndex: 3 },
                ]}
              />
              <View
                style={[
                  styles.circleSmall,
                  {
                    position: 'absolute',
                    bottom: 2,
                    right: 2,
                    zIndex: 1,
                    backgroundColor: Colors.pink_09,
                  },
                ]}
              >
                <Text
                  color={Colors.pink_03}
                  typography={'description_xs_regular'}
                >
                  {`+${image.length - 3}`}
                </Text>
              </View>
            </View>
          );
        }
      }
    }

    if (typeof image === 'string' && image) {
      return <Image source={{ uri: image }} style={styles.circle} />;
    }

    return (
      <View
        style={[
          styles.imageContainer,
          { borderColor: theme.colors.border.default },
        ]}
      >
        <Text color={Colors.pink_03} typography={'description_xs_regular'}>
          {getShortName(title)}
        </Text>
      </View>
    );
  };

  const renderVerifyIcon = () => {
    if (icons && icons.length > 0) {
      return (
        <View style={[Styles.row]}>
          {icons.map(icon => (
            <Image
              key={`verified-icon-${icon}`}
              source={{
                uri: icon,
              }}
              style={styles.verifiedIcon}
            />
          ))}
        </View>
      );
    }
  };

  const renderShimmer = () => {
    return (
      <View style={Styles.row}>
        <View
          style={[
            styles.imageContainer,
            {
              borderColor: theme.colors.border.default,
              marginRight: Spacing.M / 2,
            },
          ]}
        >
          <Skeleton />
        </View>
        <View style={Styles.flex}>
          <View style={styles.shimmerTitle}>
            <Skeleton />
          </View>
          <View style={{ height: Spacing.XXS }} />
          <View style={styles.shimmerDescription}>
            <Skeleton />
          </View>
        </View>
      </View>
    );
  };

  if (verify) {
    console.warn(`Warning: The verify value "${verify}" is deprecated.`);
  }

  if (isLoading) {
    return renderShimmer();
  }

  return (
    <TouchableOpacity
      style={{
        justifyContent: 'center',
        maxWidth: maxWidth - (icons?.length ?? 0) * 16,
      }}
      onPress={onPress}
      disabled={onPress === undefined}
    >
      <View
        style={[Styles.row, { maxWidth: maxWidth - (icons?.length ?? 0) * 16 }]}
      >
        <View>
          {renderImage()}
          {!!dotColor && (
            <View style={[styles.dotAvatar, { backgroundColor: dotColor }]} />
          )}
        </View>
        <View style={{ marginLeft: 6 }}>
          <View style={Styles.row}>
            <Text
              typography="action_xs_bold"
              color={tintColor}
              numberOfLines={1}
            >
              {title}
            </Text>
            {renderVerifyIcon()}
          </View>
          {!!subTitle && (
            <Text
              typography="description_xs_regular"
              color={tintColor}
              numberOfLines={1}
            >
              {subTitle}
            </Text>
          )}
        </View>
      </View>
    </TouchableOpacity>
  );
};

/**
 * Header user title
 * @constructor
 */
const TitleLocation: React.FC<TitleLocationProps> = ({
  tintColor,
  location,
  description,
  onPress,
  isLoading,
}) => {
  const maxWidth = Dimensions.get('window').width - 172;
  const renderShimmer = () => {
    return (
      <View style={Styles.flex}>
        <View style={styles.shimmerDescription}>
          <Skeleton />
        </View>
        <View style={{ height: Spacing.XXS }} />
        <View style={styles.shimmerTitle}>
          <Skeleton />
        </View>
      </View>
    );
  };
  if (isLoading) {
    return renderShimmer();
  }
  return (
    <TouchableOpacity
      style={{
        justifyContent: 'center',
        maxWidth: maxWidth,
        alignItems: 'flex-start',
      }}
      onPress={onPress}
    >
      {!!description && (
        <Text
          typography="description_xs_regular"
          color={tintColor}
          numberOfLines={1}
        >
          {description}
        </Text>
      )}
      <View style={Styles.row}>
        <Text typography="action_xs_bold" color={tintColor} numberOfLines={1}>
          {location}
        </Text>
        <Icon
          source={'16_arrow_chevron_down_small'}
          size={16}
          style={{ marginHorizontal: Spacing.XS }}
        />
      </View>
    </TouchableOpacity>
  );
};

/**
 * Header user title
 * @constructor
 */
const TitleJourney: React.FC<TitleJourneyProps> = ({
  start,
  end,
  description,
  icon,
  iconColor,
  tintColor,
  onPress,
  isLoading,
}) => {
  const { width } = Dimensions.get('screen');
  const maxWidth = Dimensions.get('window').width - 172;
  const startWidth = width * 0.25;
  const endWidth = width * 0.75 - 212;
  const renderShimmer = () => {
    return (
      <View style={Styles.flex}>
        <View style={styles.shimmerTitle}>
          <Skeleton />
        </View>
        <View style={{ height: Spacing.XXS }} />
        <View style={styles.shimmerDescription}>
          <Skeleton />
        </View>
      </View>
    );
  };
  if (isLoading) {
    return renderShimmer();
  }
  return (
    <TouchableOpacity
      style={{
        justifyContent: 'center',
        maxWidth: maxWidth,
      }}
      onPress={onPress}
    >
      <View style={styles.rowJourney}>
        <View style={Styles.row}>
          <Text
            typography="action_xs_bold"
            style={{ maxWidth: startWidth }}
            color={tintColor}
            numberOfLines={1}
          >
            {start}
          </Text>
          <Icon
            source={icon}
            size={16}
            color={iconColor ?? tintColor}
            style={{ marginHorizontal: Spacing.S, marginVertical: Spacing.XXS }}
          />
          {!!end && (
            <Text
              style={{ maxWidth: endWidth }}
              typography="action_xs_bold"
              color={tintColor}
              numberOfLines={1}
            >
              {end}
            </Text>
          )}
        </View>
        <Icon
          source={'16_arrow_chevron_down_small'}
          size={16}
          color={tintColor}
          style={{ marginHorizontal: Spacing.XS, marginVertical: Spacing.XXS }}
        />
      </View>
      {!!description && (
        <View style={styles.rowJourney}>
          <Text
            typography="description_xs_regular"
            color={tintColor}
            numberOfLines={1}
          >
            {description}
          </Text>
        </View>
      )}
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  rowJourney: { flexDirection: 'row', width: '100%', alignItems: 'flex-start' },
  verifiedDot: {
    width: 4,
    height: 4,
    borderRadius: 2,
    backgroundColor: Colors.green_03,
    position: 'absolute',
    alignSelf: 'center',
  },
  circle: {
    width: 32,
    height: 32,
    borderRadius: 16,
    borderWidth: 0.5,
    borderColor: Colors.black_04,
  },
  circleMedium: {
    width: 24,
    height: 24,
    borderRadius: 16,
    borderWidth: 0.5,
    borderColor: Colors.black_04,
  },
  circleSmall: {
    width: 16,
    height: 16,
    borderRadius: 16,
    borderWidth: 0.5,
    borderColor: Colors.black_04,
  },
  groupAvtContainer: {
    width: Spacing.XXL,
    height: Spacing.XXL,
    position: 'relative',
  },
  imageContainer: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: Colors.pink_09,
    borderWidth: 0.5,
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'hidden',
  },
  dotAvatar: {
    position: 'absolute',
    width: 12,
    height: 12,
    borderRadius: 6,
    bottom: -2,
    right: -2,
    borderWidth: 2,
    borderColor: Colors.black_01,
  },
  verifiedIcon: { width: 16, height: 16, marginLeft: Spacing.XS },
  shimmerTitle: {
    height: 18,
    width: 120,
    borderRadius: Radius.XS,
    overflow: 'hidden',
  },
  shimmerDescription: {
    height: 12,
    width: 120,
    borderRadius: Radius.XS,
    overflow: 'hidden',
  },
  debugBaseLine: { borderWidth: 1, borderColor: Colors.green_06 },
});

export { HeaderTitle, TitleCustom };
