import React, { FC, useContext, useState } from 'react';
import {
  Text as RNText,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import { Icon } from '../Icon';
import { useScaleSize, Text } from '../Text';
import { useComponentId } from '../Application';
import { ApplicationContext, MiniAppContext } from '../Context';
import { Badge } from '../Badge';
import { Colors } from '../Consts';
import styles from './styles';
import { TitleProps } from './types';
import { Typography } from '../Text/types';

const Title: FC<TitleProps> = ({
  accessibilityLabel,
  title = 'Title',
  type = 'section',
  size = 'medium',
  icon,
  description,
  iconColor = null,
  iconAlign = 'top',
  showRightAction = false,
  showTrailingAction = false,
  badgeLabel,
  buttonTitle,
  onPressRightAction = () => {},
  onPressTrailingAction = () => {},
  buttonSize = 'small',
  textOnly = false,
  style,
}) => {
  const { theme } = useContext(ApplicationContext);
  const context = useContext<any>(MiniAppContext);
  const [badgeWidth, setBadgeWidth] = useState(0);
  const [contentWidth, setContentWidth] = useState(0);

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

  const size18 = useScaleSize(18);
  const size22 = useScaleSize(22);
  // Dynamic styles using useScaleSize hook
  const dynamicStyles = {
    card_small: {
      fontSize: useScaleSize(14),
      lineHeight: useScaleSize(20),
    },
    card_medium: {
      fontSize: useScaleSize(16),
      lineHeight: useScaleSize(22),
    },
    card_large: {
      fontSize: useScaleSize(18),
      lineHeight: useScaleSize(26),
    },
    section_medium: {
      fontSize: useScaleSize(20),
      lineHeight: useScaleSize(28),
    },
    section_small: {
      fontSize: useScaleSize(16),
      lineHeight: useScaleSize(22),
    },
    section_large: {
      fontSize: useScaleSize(24),
      lineHeight: useScaleSize(34),
    },
  };

  const styleSheet: {
    [key: string]: any;
  } = { ...styles, ...dynamicStyles };
  const typography = `${type}_${size}`;
  const isSection = type === 'section';
  const numberOfLines = showTrailingAction || !!badgeLabel ? 1 : 2;
  const buttonTypo: Typography =
    buttonSize === 'small' ? 'action_xs_bold' : 'action_s_bold';
  const flexStyle: ViewStyle = showTrailingAction ? { maxWidth: '95%' } : {};
  const componentName = 'Title';

  const { componentId } = useComponentId(
    `${componentName}/${title}`,
    accessibilityLabel,
  );

  const renderIcon = () => {
    if (!icon) return null;

    let iconStyle: ViewStyle = {
      justifyContent: 'flex-start',
    };

    if (iconAlign === 'middle') {
      iconStyle = { justifyContent: 'center' };
    }

    if (iconAlign === 'bottom') {
      iconStyle = { justifyContent: 'flex-end' };
    }

    return (
      <View
        accessibilityLabel={componentId + '|icon'}
        style={[styles.iconView, iconStyle]}
      >
        <Icon color={iconColor} source={icon} />
      </View>
    );
  };

  const renderContent = () => {
    return (
      <View style={styles.contentView}>
        <View
          onLayout={e => {
            if (e.nativeEvent.layout.width !== contentWidth) {
              setContentWidth(e.nativeEvent.layout.width);
            }
          }}
          style={[styles.iconLeftView, flexStyle]}
        >
          <RNText
            allowFontScaling={false}
            accessibilityLabel={componentId + '|title-text'}
            numberOfLines={numberOfLines}
            style={[
              styleSheet[typography],
              styles.title,
              {
                maxWidth:
                  contentWidth > 0 ? contentWidth - badgeWidth : undefined,
              },
            ]}
          >
            {title}
          </RNText>
          {badgeLabel && (
            <View
              onLayout={e => {
                if (e.nativeEvent.layout.width !== badgeWidth) {
                  setBadgeWidth(e.nativeEvent.layout.width);
                }
              }}
              style={{
                alignItems: 'center',
              }}
            >
              <Badge
                style={styles.badge}
                label={badgeLabel}
                accessibilityLabel={componentId + '|badge'}
              />
            </View>
          )}
          {renderActionLeft()}
        </View>
        {description && (
          <Text
            accessibilityLabel={componentId + '|description-text'}
            style={styles.description}
            color={theme.colors.text.secondary}
            typography={'description_default_regular'}
          >
            {description}
          </Text>
        )}
      </View>
    );
  };

  const renderActionLeft = () => {
    return (
      <TouchableOpacity
        accessibilityLabel={componentId + '|trailing-touch'}
        onPress={onPressTrailingAction}
        style={styles.iconLeftView}
        hitSlop={{ top: 10, bottom: 10, left: 50, right: 10 }}
      >
        {showTrailingAction && !showRightAction && (
          <View
            style={[
              styles.iconLeft,
              {
                backgroundColor: isSection
                  ? Colors.black_06 + '99'
                  : Colors.black_06 + '4D',
              },
            ]}
          >
            <Icon
              source={'arrow_chevron_right_small'}
              size={size18}
              color={theme.colors.text.default}
            />
          </View>
        )}
      </TouchableOpacity>
    );
  };

  const renderActionRight = () => {
    if (!showRightAction || showTrailingAction) return false;

    const lineHeight = styleSheet[typography].lineHeight;

    return (
      <View
        style={{
          height: lineHeight,
          justifyContent: 'center',
        }}
      >
        {!buttonTitle ? (
          <TouchableOpacity
            onPress={onPressRightAction}
            style={[
              styles.iconRight,
              {
                backgroundColor: theme.colors.primary + '0F',
              },
            ]}
            accessibilityLabel={componentId + '|label-right-action-touch'}
          >
            <Icon
              source={'arrow_chevron_right_small'}
              size={size22}
              color={theme.colors.primary}
            />
          </TouchableOpacity>
        ) : (
          <TouchableOpacity
            onPress={onPressRightAction}
            accessibilityLabel={componentId + '|label-right-action-touch'}
          >
            <Text
              color={theme.colors.primary}
              typography={buttonTypo}
              accessibilityLabel={componentId + '|label-right-action-text'}
            >
              {buttonTitle}
            </Text>
          </TouchableOpacity>
        )}
      </View>
    );
  };

  if (textOnly) {
    return (
      <View style={isSection && styles.margin}>
        <RNText
          allowFontScaling={false}
          accessibilityLabel={componentId + '|title-text'}
          numberOfLines={numberOfLines}
          style={[styleSheet[typography], styles.title]}
        >
          {title}
        </RNText>
      </View>
    );
  }

  return (
    <View
      style={[
        style,
        styles.wrapper,
        isSection && styles.margin,
        showBaseLineDebug && styles.debugBaseLine,
      ]}
      accessibilityLabel={componentId}
    >
      {renderIcon()}
      {renderContent()}
      {renderActionRight()}
    </View>
  );
};

export { Title };
export type { TitleProps };
