import React, { useContext } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import { Formik } from 'formik';
import _ from 'lodash';
import Page from '../containers/Page';
import hooks from '../hooks/useAPIClient';
import useQuery from '../hooks/useQuery';
import { post, patch, del } from '../requests';
import ServiceContext, { Action } from './ServiceContext';

interface Params {
  id: string;
}

const ServiceItem: React.FC = () => {
  const service = useContext(ServiceContext);
  const history = useHistory();
  const query = useQuery();
  const { id } = useParams<Params>();
  const { data: item, mutate } = hooks[service.route].useItem(id);

  const handleDelete = () => del(`/${service.route}/${id}`)
    .then(() => history.push(`/${service.route}`));

  const onSubmit = (values: any) => {
    const promise = id
      ? patch(`/${service.route}/${id}`, values)
      : post(`/${service.route}`, values);
    return promise.then(response => {
      mutate(response.data);
      history.push(`/${service.route}`);
    });
  };

  const actions: Action[] = _.compact([
    { name: 'Назад', variant: 'outlined', onClick: history.goBack },
    id && { name: 'Удалить', variant: 'outlined', onClick: handleDelete },
    { name: 'Сохранить', type: 'submit', form: 'form' },
  ]);

  return (
    <Page
      title={id ? item?.name : `Новый ${service.nameSingular}`}
      actions={actions}
      className="grid lg:grid-cols-2"
    >
      {(!id || item) && (
        <Formik
          initialValues={_.defaults(item, query, service.default)}
          onSubmit={onSubmit}
          children={service.Form}
        />
      )}
      {item && service.Panel && <service.Panel item={item} mutate={mutate} />}
    </Page>
  );
};

export default ServiceItem;
