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

const TransfersUpload: React.FC = () => {
  const history = useHistory();
  const [file, setFile] = useState<File>();

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setFile(event.target?.files?.[0]);
  };

  const handleSubmitFile = () => {
    const reader = new FileReader();
    if (file) {
      reader.readAsDataURL(file);
      reader.onload = (event: ProgressEvent<FileReader>) => {
        const uri = event.target?.result;
        post('/uploads', { uri }).then(history.goBack);
      };
    }
  };

  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="Прикрепите файл"
            onChange={handleChange}
          />
        </Form>
      </Formik>
    </Page>
  );
};

export default TransfersUpload;
