import * as React from 'react';
import { useState } from 'react';
import { Dimensions, FlatList, Modal } from 'react-native';
import { Normalize } from '../../utils/normalize';
import CaretRight from '../../icons/CaretRight';
import { Box } from '../Box';
import { Text } from '../Text';
import { TouchableComponent } from '../TouchableComponent';
import { ListHeaderComponent } from './components/ListHeaderComponent';
import { ListBottomComponent } from './components/ListBottomComponent';
import { RadioButton } from './components/RadioButton';
import { useTheme } from '../../theme/ThemeProvider';
import type { VariantProps } from '@shopify/restyle';
import type { Theme } from './../../theme/theme';

export interface ISelect {
  label: string;
  value: string | number;
}
type SelectProps = {
  items: ISelect[];
  placeholder: string;
  setState: ({ value, label }: ISelect) => void;
  animationType?: AnimationType;
  disabled?: boolean;
  height?: number;
  variant?: VariantProps<Theme, 'textVariants'>['variant'];
  withLabel?: boolean;
  modalBody?: (
    items: any,
    setModalVisible: React.Dispatch<React.SetStateAction<boolean>>
  ) => JSX.Element;
  customHeader?: (
    setModalVisible: React.Dispatch<React.SetStateAction<boolean>>
  ) => JSX.Element;
  state: ISelect | null;
  modalTitle?: string;
  full?: boolean;
};

type AnimationType = 'none' | 'slide' | 'fade';
type selectVariants = 'disabled' | 'unfilled' | 'filled';

const windowHeight = Dimensions.get('window').height;
const HEADER_HEIGHT = Normalize(64);
const MAX_HEIGHT = windowHeight - HEADER_HEIGHT;

export const SelectPicker = ({
  items,
  placeholder,
  setState,
  animationType = 'fade',
  disabled = false,
  state,
  height = Normalize(44),
  withLabel = true,
  variant = 'body',
  modalBody,
  customHeader,
  full = false,
}: SelectProps) => {
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [currentState, setcurrentState] = useState<ISelect | null>(state);

  React.useEffect(() => {
    console.log(state);
    if (!modalVisible) setcurrentState(state);
    return () => {
      setcurrentState(null);
    };
  }, [modalVisible, state]);

  const typeStyle: () => selectVariants = () => {
    if (disabled) return 'disabled';
    else if (state) return 'filled';
    else return 'unfilled';
  };

  const { colors } = useTheme();

  return (
    <React.Fragment>
      <TouchableComponent
        disabled={disabled}
        onPress={() => setModalVisible(true)}
        alignSelf="center"
        paddingLeft={'spacing-s'}
        paddingRight={'spacing-xms'}
        paddingHorizontal={'spacing-s'}
        borderRadius={Normalize(4)}
        flexDirection="row"
        justifyContent="space-between"
        alignItems="center"
        backgroundColor={disabled ? 'gray25' : 'white'}
        width="100%"
        minHeight={height}
        borderColor={
          typeStyle() === 'disabled' || typeStyle() === 'unfilled'
            ? 'gray60'
            : 'gray100'
        }
        borderWidth={1}
        testID="SelectPicker"
      >
        <Box>
          {!state ? (
            <Text color={'gray200'} variant={variant}>
              {placeholder}
            </Text>
          ) : null}
          {state && state.value && withLabel ? (
            <Text
              color={disabled ? 'gray200' : 'darkBlueGray'}
              variant={'SubHead'}
            >
              {placeholder}
            </Text>
          ) : null}
          {state && state.label ? (
            <Text
              color={disabled ? 'gray200' : 'yankeesBlue'}
              variant={variant}
            >
              {state.label}
            </Text>
          ) : null}
        </Box>
        <CaretRight
          rotation={90}
          color={disabled ? colors.gray200 : colors.yankeesBlue}
        />
      </TouchableComponent>
      <Modal
        animationType={animationType}
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => setModalVisible(false)}
      >
        <Box
          width={'100%'}
          height={'100%'}
          // eslint-disable-next-line react-native/no-inline-styles
          style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}
        >
          <Box
            position="absolute"
            width={'100%'}
            height={full ? '100%' : 'auto'}
            maxHeight={full ? '100%' : MAX_HEIGHT}
            bottom={0}
            backgroundColor="white"
            borderTopLeftRadius={Normalize(4)}
            borderTopRightRadius={Normalize(4)}
            flexDirection={'column'}
            justifyContent="flex-end"
          >
            {customHeader ? (
              customHeader(setModalVisible)
            ) : (
              <ListHeaderComponent
                placeholder={placeholder}
                setModalVisible={setModalVisible}
              />
            )}
            {modalBody ? (
              modalBody(items, setModalVisible)
            ) : (
              <>
                <FlatList
                  data={items}
                  keyExtractor={(_: any, index: number) =>
                    `modal-item-${index}`
                  }
                  scrollEnabled={true}
                  renderItem={({ item }: any) => {
                    const isItemChecked = currentState?.value === item.value;
                    return (
                      <TouchableComponent
                        px={'spacing-s'}
                        width="100%"
                        height={Normalize(44)}
                        justifyContent="space-between"
                        alignItems={'center'}
                        flexDirection={'row'}
                        onPress={() => {
                          setcurrentState(Object.assign({}, item));
                        }}
                      >
                        <Text variant="body" color="yankeesBlue">
                          {item.label}
                        </Text>
                        <RadioButton checked={isItemChecked} />
                      </TouchableComponent>
                    );
                  }}
                />
                <ListBottomComponent
                  setModalVisible={setModalVisible}
                  setState={setState}
                  currentState={currentState}
                />
              </>
            )}
          </Box>
        </Box>
      </Modal>
    </React.Fragment>
  );
};
