import React, { type FC } from 'react';
import { StyleSheet, View, I18nManager, Platform } from 'react-native';
import RNPickerSelect from 'react-native-picker-select';
import { moderateScale } from 'react-native-size-matters';
import { withTheme, useTheme } from '../../core/theming';
import type { Theme } from '../../utils/types';
import { defaultScale } from '../../utils/Common';
import TButton from '../TButton/TButton';
import { fontFamilies } from '../../constants/fontFamilies';
import IconSVG from '../../assets/svgs';
import TTypography from '../TTypography/TTypography';
import { TypographyVariant } from '../TTypography/TTypographyEnum';

interface Prop {
  onPickerChange: (selectedValue: any, selectedIndex: number) => void;
  data: Array<any>;
  pickervalue: any;
  btnLabel: string;
  theme: Theme;
  placeholder?: Object;
  error?: boolean;
  errorText?: string;
  testID?: string;
  accessibilityLabel?: string;
  onClose?: () => void;
  disabled?: boolean;
}

const TPicker: FC<Prop> = ({
  onPickerChange,
  data,
  pickervalue,
  btnLabel,
  placeholder = {},
  errorText,
  error,
  testID,
  accessibilityLabel,
  onClose,
  disabled = false,
}): any => {
  const { colors } = useTheme();
  const styleWithProps = styles({ colors });
  const pickerRef = React.useRef<RNPickerSelect | null>();
  const onDonePress = () => {
    pickerRef.current?.togglePicker(true);
  };
  // eslint-disable-next-line react/no-unstable-nested-components
  const InputAccessoryView = () => {
    return (
      <View style={styleWithProps.viewStyle}>
        <TButton
          title={btnLabel}
          variant="tertiary"
          textColor={colors.textColor}
          onPress={onDonePress}
          backgroundColor={colors.black}
          style={styleWithProps.btnRightStyle}
        />
      </View>
    );
  };

  return (
    <>
      <View
        style={[
          styleWithProps.viewContainer,
          {
            borderColor: error ? colors.error : colors.separatorColor,
            borderWidth: 1,
          },
        ]}
      >
        <RNPickerSelect
          placeholder={placeholder}
          items={data}
          value={pickervalue}
          touchableWrapperProps={{
            testID: testID,
            accessible: true,
            accessibilityLabel: accessibilityLabel,
            onBlur: () => {
              if (onClose) {
                onClose();
              }
            },
          }}
          // @ts-ignore
          InputAccessoryView={InputAccessoryView}
          ref={(r) => (pickerRef.current = r)}
          // eslint-disable-next-line react/no-unstable-nested-components
          Icon={() => (
            <IconSVG
              name={'downarrow'}
              style={styleWithProps.iconStyle}
              height={16}
              width={16}
            />
          )}
          style={{
            inputIOSContainer: styleWithProps.inputIOSContainer,
            inputAndroidContainer: styleWithProps.inputAndroidContainer,
            modalViewBottom: {
              backgroundColor: colors.white,
            },
            inputIOS: styleWithProps.inputIOS,
            inputAndroid: styleWithProps.inputAndroid,
            placeholder: {
              color: colors.textColorLight,
            },
          }}
          onValueChange={(value, index) => onPickerChange(value, index)}
          pickerProps={{
            mode: 'dialog',
            itemStyle: styleWithProps.pickerItemStyle,
          }}
          useNativeAndroidPickerStyle={false}
          fixAndroidTouchableBug={true}
          onClose={() => {
            if (Platform.OS === 'ios') {
              if (onClose) {
                onClose();
              }
            }
          }}
          disabled={disabled}
        />
      </View>
      {errorText ? (
        <TTypography
          children={errorText}
          variant={TypographyVariant.PRIMARY}
          color={colors.error}
          fontSize={14}
          style={styleWithProps.errorTextStyle}
        />
      ) : null}
    </>
  );
};
const styles = (props: { colors: any }) =>
  StyleSheet.create({
    viewContainer: {
      width: '100%',
      backgroundColor: props.colors.white,
      borderColor: props.colors.separatorColor,
    },
    btnRightStyle: {
      marginRight: moderateScale(15, defaultScale),
    },
    btnLeftStyle: {
      marginLeft: moderateScale(15, defaultScale),
    },
    viewStyle: {
      flexDirection: 'row',
      justifyContent: 'flex-end',
      alignItems: 'center',
      backgroundColor: props.colors.white,
      height: moderateScale(44, defaultScale),
      borderBottomWidth: StyleSheet.hairlineWidth,
      borderBottomColor: props.colors.borderColor,
    },
    inputAndroid: {
      fontSize: 16,
      paddingVertical: moderateScale(8, defaultScale),
      flex: 1,
      paddingHorizontal: moderateScale(15, defaultScale),
      color: props.colors.textColor,
      textAlign: I18nManager.isRTL ? 'right' : 'left',
      fontFamily: I18nManager.isRTL
        ? `${fontFamilies.Fonts.primaryArabic}`
        : `${fontFamilies.Fonts.primary}-Regular`,
    },
    inputIOS: {
      fontSize: 16,
      paddingVertical: moderateScale(8, defaultScale),
      flex: 1,
      paddingHorizontal: moderateScale(15, defaultScale),
      color: props.colors.textColor,
      textAlign: I18nManager.isRTL ? 'right' : 'left',
      fontFamily: I18nManager.isRTL
        ? `${fontFamilies.Fonts.primaryArabic}`
        : `${fontFamilies.Fonts.primary}-Regular`,
    },
    inputIOSContainer: {
      width: '100%',
      height: moderateScale(48, defaultScale),
      paddingRight: moderateScale(8, defaultScale),
    },
    inputAndroidContainer: {
      width: '100%',
      height: moderateScale(48, defaultScale),
      paddingRight: moderateScale(22, defaultScale),
    },
    pickerItemStyle: {
      fontSize: 16,
      color: props.colors.black,
      fontFamily: I18nManager.isRTL
        ? `${fontFamilies.Fonts.primaryArabic}`
        : `${fontFamilies.Fonts.primary}-Regular`,
    },
    iconStyle: {
      top: moderateScale(18, defaultScale),
      right: moderateScale(20, defaultScale),
    },
    errorTextStyle: {
      marginTop: moderateScale(5, defaultScale),
    },
  });
export default withTheme(TPicker);
