import React, { FC, useState } from 'react';
import { View } from 'react-native';

import { Input } from '../../Input';
import { Modal } from '../../Modal';
import { FlatList } from '../index';

type Props = {
  selectedObject?: (object: any) => void;
  headerTitle: string;
  defaultObject?: { name?: string };
  placeholder?: string;
  formikError?: any;
};

//TODO: rework to generic types

export const ModalFlatList: FC<Props> = ({
  selectedObject,
  headerTitle,
  defaultObject,
  placeholder,
  formikError
}) => {
  const [visible, setVisible] = useState(false);
  const [selectedFlatListObject, setSelectedFlatListObject] = useState<{ name?: string }>({});

  const onSelect = (object: { name: string }) => {
    setVisible(false);
    if (selectedObject) {
      selectedObject(object);
      setSelectedFlatListObject(object);
    }
  };

  return (
    <View>
      <Input
        header={headerTitle}
        isFocused={(b) => setVisible(b)}
        value={selectedFlatListObject?.name ?? defaultObject?.name}
        inputMode={'none'}
        placeholder={placeholder}
        formikError={formikError}
      />
      <Modal
        onRequestClose={() => setVisible(false)}
        headerTitle={headerTitle ?? 'Change me'}
        visible={visible}
      >
        <FlatList itemObject={(object) => onSelect(object)} />
      </Modal>
    </View>
  );
};
