import React, {forwardRef, ReactNode, useCallback} from 'react';
import {
  Text as BaseText,
  StyleProp,
  TextInput,
  View,
  ViewStyle,
} from 'react-native';
import {
  Colors,
  fontSz,
  formatAsCurrency,
  globalStyles,
  hp,
  ms,
  naira,
} from '../../utils';
import {Text} from '../Text';
import {CustomPressable} from '../Button';
import {useSDKConfig} from '../../contexts/SDKConfigContext';

interface CurrencyInputProps {
  value: string | number | null | undefined;
  onChange?: (text: string) => void;
  onChangeValue?: (value: number | React.SetStateAction<string> | null) => void;
  separator: string;
  delimiter: string;
  unit?: string;
  precision?: number;
  maxValue?: number;
  minValue?: number;
  ignoreNegative?: boolean;
  containerStyle?: any;
  wrapperStyle?: StyleProp<ViewStyle>;
  //
  label: any;
  bottomLabel?: any;
  placeholder: any;
  inputStyle?: any;
  prependComponent?: any;
  appendComponent?: any;
  onEndEditing?: any;
  onFocus?: any;
  secureTextEntry?: any;
  keyboardType?:
    | 'default'
    | 'email-address'
    | 'numeric'
    | 'phone-pad'
    | 'number-pad'
    | 'decimal-pad'
    | undefined;
  autoCompleteType?:
    | 'off'
    | 'birthdate-day'
    | 'birthdate-full'
    | 'birthdate-month'
    | 'birthdate-year'
    | 'cc-csc'
    | 'cc-exp'
    | 'cc-exp-day'
    | 'cc-exp-month'
    | 'cc-exp-year'
    | 'cc-number'
    | 'email'
    | 'gender'
    | 'name'
    | 'name-family'
    | 'name-given'
    | 'name-middle'
    | 'name-middle-initial'
    | 'name-prefix'
    | 'name-suffix'
    | 'password'
    | 'password-new'
    | 'postal-address'
    | 'postal-address-country'
    | 'postal-address-extended'
    | 'postal-address-extended-postal-code'
    | 'postal-address-locality'
    | 'postal-address-region'
    | 'postal-code'
    | 'street-address'
    | 'sms-otp'
    | 'tel'
    | 'tel-country-code'
    | 'tel-national'
    | 'tel-device'
    | 'username'
    | 'username-new'
    | 'off'
    | undefined;
  autoCapitalize?: 'none' | undefined;
  errorMsg?: string | ReactNode | undefined;
  multiline?: boolean | undefined;
  numberOfLines?: number;
  maxLength?: number;
  isLoading?: boolean;
  returnKeyLabel?: string;
  returnKeyType?: 'done' | 'go' | 'next' | 'search' | 'send';
  editable?: boolean;
  //
  topComponent?: any;
  onPressUseAllBalance?: () => void;
  balance?: number;
  showUseAllBalance?: boolean;
  walletAmount?: number;
  paymentAmount?: number;
  showAsterisk?: boolean;
  showCurrency?: boolean;
  hideBalance?: boolean;
}

export const CurrencyInputBase = forwardRef<any, CurrencyInputProps>(
  (props, ref) => {
    const {
      value,
      containerStyle,
      label,
      bottomLabel,
      placeholder,
      inputStyle,
      prependComponent,
      appendComponent,
      onChange,
      onEndEditing,
      onFocus,
      secureTextEntry,
      keyboardType = 'numeric',
      autoCompleteType = 'off',
      autoCapitalize = 'none',
      errorMsg = '',
      multiline = false,
      numberOfLines = 1,
      isLoading = false,
      returnKeyLabel,
      returnKeyType,
      editable = true,
      //
      onChangeValue,
      separator,
      delimiter,
      unit = '',
      precision = 0,
      maxValue,
      minValue,
      ignoreNegative,
      topComponent,
      maxLength,
      showAsterisk,
    } = props;

    const toCommaNumber = (text: string) => {
      return text.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    };

    const handleChangeText = useCallback((text: string) => {
      if (text.includes('.')) {
        const decimalParts = text.split('.')[1];
        const wholeNumber = text.split('.')[0].replace(/\D/g, '');
        const newValue = `${wholeNumber}.${decimalParts.substring(0, 2)}`;
        onChangeValue && onChangeValue(newValue);
      } else {
        const newValue = text.replace(/\D/g, '');
        const sanitizedValue = newValue === '0' ? '' : newValue;
        onChangeValue && onChangeValue(sanitizedValue);
      }
    }, []);

    return (
      <View
        style={{
          position: 'relative',
          paddingBottom: ms(8),
          ...containerStyle,
        }}>
        {/* label && icon */}
        <View style={globalStyles.rowBetween}>
          {typeof label === 'string' ? (
            <BaseText
              style={{
                fontSize: fontSz(14),
                fontFamily: 'Gordita-Regular',
                fontWeight: '400',
                color: Colors.inputBackgroundLight,
              }}>
              {label}
              {showAsterisk && (
                <Text
                  fontSize={fontSz(14)}
                  fontFamily="Gordita-Regular"
                  fontWeight="400"
                  text={'*'}
                  color={Colors.debitRed}
                />
              )}
            </BaseText>
          ) : (
            label
          )}
          {topComponent ?? topComponent}
        </View>

        {/* Text Input */}
        <View
          style={{
            flexDirection: 'row',
            height: hp(55),
            paddingHorizontal: ms(10),
            marginTop: ms(4),
            borderRadius: ms(8),
            borderColor:
              typeof errorMsg === 'string' && errorMsg?.length > 0
                ? Colors.error
                : '#F4F4F4',
            borderWidth: ms(1),
            backgroundColor: '#F4F4F4',
          }}>
          {/* {prependComponent} */}
          <View
            style={{
              justifyContent: 'center',
              marginLeft: ms(1.5),
              marginRight: ms(10),
            }}>
            <CustomPressable>
              <Text
                color={Colors.baseBlueText}
                fontWeight="500"
                fontSize={fontSz(14)}
                fontFamily="Gordita-Regular"
                // lineHeight={fontSz(14 * 1.3)}
                text={naira}
              />
            </CustomPressable>
          </View>

          <TextInput
            style={{
              flex: 1,
              ...inputStyle,
              color: Colors.baseBlueText,
              fontSize: fontSz(14),
              fontFamily: 'Gordita-Regular',
            }}
            placeholder={placeholder}
            value={value ? `${toCommaNumber(String(value))}` : ''}
            placeholderTextColor={'#C4C4C4'}
            onChangeText={handleChangeText}
            onEndEditing={text => onEndEditing(text)}
            onFocus={text => onFocus()}
            secureTextEntry={secureTextEntry}
            keyboardType={keyboardType}
            autoComplete={autoCompleteType}
            autoCapitalize={autoCapitalize}
            multiline={multiline}
            numberOfLines={numberOfLines}
            returnKeyLabel={returnKeyLabel}
            returnKeyType={returnKeyType}
            editable={editable}
            maxLength={maxLength}
          />

          {appendComponent}
        </View>
        {/* bottom message */}
        {typeof errorMsg === 'string' && errorMsg.length > 0 && (
          <Text
            style={{
              // paddingTop: ms(2.5),
              position: 'absolute',
              bottom: ms(-10),
              left: 0,
            }}
            fontSize={fontSz(14)}
            fontFamily="Gordita-Regular"
            fontWeight="400"
            text={`${errorMsg}`}
            color={Colors.error}
          />
        )}
        {typeof errorMsg === 'string' && errorMsg?.length === 0 && (
          <>
            {/* bottomLabel */}
            {typeof bottomLabel === 'string' ? (
              <Text
                fontSize={fontSz(14)}
                fontFamily="Gordita-Regular"
                fontWeight="400"
                text={`${bottomLabel}`}
                color={Colors.inputBackgroundLight}
                style={{
                  position: 'absolute',
                  bottom: ms(-10),
                  width: '100%',
                }}
              />
            ) : (
              bottomLabel
            )}
          </>
        )}
      </View>
    );
  },
);

const CurrencyInput: React.ForwardRefRenderFunction<any, CurrencyInputProps> = (
  props,
  ref,
) => {
  const {
    value,
    containerStyle,
    label,
    placeholder,
    inputStyle,
    prependComponent,
    appendComponent,
    onChange,
    onEndEditing,
    onFocus,
    secureTextEntry,
    keyboardType = 'numeric',
    autoCompleteType = 'off',
    autoCapitalize = 'none',
    errorMsg = '',
    multiline = false,
    numberOfLines = 1,
    isLoading = false,
    returnKeyLabel,
    returnKeyType,
    editable = true,
    //
    onChangeValue,
    separator,
    delimiter,
    unit = '',
    precision = 0,
    maxValue,
    minValue,
    ignoreNegative,
    topComponent,
    onPressUseAllBalance,
    balance,
    showUseAllBalance,
    walletAmount,
    paymentAmount,
    maxLength,
    showAsterisk,
    showCurrency,
    wrapperStyle,
    hideBalance,
  } = props;
  const {primaryColor} = useSDKConfig();

  const toCommaNumber = (text: string) => {
    return text.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  };

  const handleChangeText = useCallback((text: string) => {
    if (text.includes('.')) {
      const decimalParts = text.split('.')[1];
      const wholeNumber = text.split('.')[0].replace(/\D/g, '');
      const newValue = `${wholeNumber}.${decimalParts.substring(0, 2)}`;
      onChangeValue && onChangeValue(newValue);
    } else {
      const newValue = text.replace(/\D/g, '');
      const sanitizedValue = newValue === '0' ? '' : newValue;
      onChangeValue && onChangeValue(sanitizedValue);
    }
  }, []);

  return (
    <View
      style={{position: 'relative', paddingBottom: ms(8), ...containerStyle}}>
      {/* label && icon */}
      <View style={globalStyles.rowBetween}>
        <BaseText
          style={{
            fontSize: fontSz(14),
            fontFamily: 'Gordita-Regular',
            fontWeight: '400',
            color: Colors.inputBackgroundLight,
          }}>
          {label}
          {showAsterisk && (
            <Text
              fontSize={fontSz(14)}
              fontFamily="Gordita-Regular"
              fontWeight="400"
              text={'*'}
              color={Colors.debitRed}
            />
          )}
        </BaseText>
        {topComponent ?? topComponent}
      </View>

      {/* Text Input */}
      <View
        style={[
          {
            flexDirection: 'row',
            height: hp(55),
            paddingHorizontal: ms(10),
            marginTop: ms(4),
            borderRadius: ms(8),
            borderColor:
              typeof errorMsg === 'string' && errorMsg.length > 0
                ? Colors.error
                : '#F4F4F4',
            borderWidth: ms(1),
            backgroundColor: '#F4F4F4',
          },
          wrapperStyle,
        ]}>
        {/* {prependComponent} */}
        {showCurrency && (
          <View
            style={{
              justifyContent: 'center',
              marginLeft: ms(1.5),
              marginRight: ms(10),
            }}>
            <CustomPressable>
              <Text
                color={Colors.baseBlueText}
                fontWeight="500"
                fontSize={fontSz(14)}
                fontFamily="Gordita-Regular"
                // lineHeight={fontSz(14 * 1.3)}
                text={naira}
              />
            </CustomPressable>
          </View>
        )}

        <TextInput
          style={{
            flex: 1,
            ...inputStyle,
            color: Colors.baseBlueText,
            fontSize: fontSz(14),
            fontFamily: 'Gordita-Regular',
          }}
          placeholder={placeholder}
          value={value ? `${toCommaNumber(String(value))}` : ''}
          placeholderTextColor={'#C4C4C4'}
          onChangeText={handleChangeText}
          onEndEditing={text => onEndEditing(text)}
          onFocus={text => onFocus()}
          secureTextEntry={secureTextEntry}
          keyboardType={keyboardType}
          autoComplete={autoCompleteType}
          autoCapitalize={autoCapitalize}
          multiline={multiline}
          numberOfLines={numberOfLines}
          returnKeyLabel={returnKeyLabel}
          returnKeyType={returnKeyType}
          editable={editable}
          maxLength={maxLength}
        />

        {appendComponent}
      </View>
      {/* bottom message */}
      {errorMsg && (
        <>
          {typeof errorMsg === 'string' ? (
            <Text
              style={{
                // paddingTop: ms(2.5),
                position: 'absolute',
                bottom: ms(-10),
                left: 0,
              }}
              fontSize={fontSz(14)}
              fontFamily="Gordita-Regular"
              fontWeight="400"
              text={`${errorMsg}`}
              color={Colors.error}
            />
          ) : (
            errorMsg
          )}
        </>
      )}
      {typeof errorMsg === 'string' && errorMsg.length === 0 && !hideBalance && (
        <View
          style={[
            {
              position: 'absolute',
              bottom: ms(-10),
              width: '100%',
              // left: 0,
            },
          ]}>
          <View style={[globalStyles.rowBetween, {width: '100%'}]}>
            <BaseText
              style={{
                fontSize: fontSz(14),
                // lineHeight: fontSz(20),
                fontFamily: 'Gordita-Regular',
                fontWeight: '400',
                color: Colors.disabledButton,
                textAlign: 'left',
              }}>
              Balance{' '}
              <Text
                fontSize={fontSz(14)}
                fontFamily="Gordita-Regular"
                fontWeight="400"
                text={`${formatAsCurrency(Number(balance))}`}
                color={Colors.inputBackground}
              />
            </BaseText>

            {showUseAllBalance && (
              <CustomPressable
                activeOpacity={0.9}
                onPress={onPressUseAllBalance}
                style={{
                  alignSelf: 'flex-end',
                }}>
                <Text
                  fontSize={fontSz(14)}
                  fontFamily="Gordita-Regular"
                  fontWeight="400"
                  text={`${'Use all balance'}`}
                  color={primaryColor}
                  textAlign={'right'}
                />
              </CustomPressable>
            )}
          </View>
        </View>
      )}
    </View>
  );
};

export default forwardRef(CurrencyInput);
