import React from 'react';
import { useHistory } from 'react-router-dom';
import { Form, Formik } from 'formik';
import Button from '../components/Button';
import Input from '../components/Input';
import Page, { Action } from './Page';
import { post } from '../requests';

const TransfersUpload: React.FC = () => {
  const history = useHistory();

  const handleSubmitFile = () => {
    const reader = new FileReader();
    const file = document.getElementById('file').files[0];
    reader.readAsDataURL(file);
    reader.onload = (e: any) => {
      const uri = e.target.result;
      post('/uploads', { uri })
        .then(() => history.push('/transfers'));
    };
  };

  const actions: Action[] = [
    { name: 'Назад', variant: 'outlined', onClick: history.goBack },
    { name: 'Загрузить', type: 'submit', form: 'form' },
  ];

  return (
    <Page
      title="Загрузить выписку"
      actions={actions}
    >
      <Formik onSubmit={handleSubmitFile} initialValues={{}}>
        <Form id="form">
          <Input name="file" type="file" accept=".pdf" label="Прикрепите файл" id="file" />
        </Form>
      </Formik>
    </Page>
  );
};

export default TransfersUpload;
