import { useState } from 'react';
import { AiOutlineEdit } from 'react-icons/ai';
import { SingleDatepicker } from 'chakra-dayzed-datepicker';
import { Text, Box, IconButton } from '@chakra-ui/react';

import { convertDateToString } from '../../utilities/functions';

function EditableDatePicker({ value, name, onChange, isEditabled }) {
  const [isEdit, setIsEdit] = useState(false);
  const date = typeof value === 'string' ? new Date(value) : value;

  const handleOnDateChange = (value) => {
    onChange({ target: { name, value: value } });
    setIsEdit(false);
  };

  const boxProps = isEditabled && {
    boxShadow: 'sm',
    bg: 'gray.900',
    borderRadius: 'md',
  };

  return isEdit ? (
    <SingleDatepicker defaultIsOpen={true} closeOnSelect name={name} date={date} onDateChange={handleOnDateChange} />
  ) : (
    <Box width="full" display="flex" justifyContent="space-between" opacity={0.5} padding="1" {...boxProps}>
      <Text flex="1" as="span" onClick={() => setIsEdit(true)}>
        {convertDateToString(value)}
      </Text>
      {isEditabled && <IconButton onClick={() => setIsEdit(true)} icon={<AiOutlineEdit />} />}
    </Box>
  );
}

export default EditableDatePicker;
