import { Form, notification } from "antd";
import React, { useState } from "react";
import { useMutation, useQuery } from "react-apollo";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
  DELETE_EMPLOYEE,
  INSERT_EMPLOYEES,
  QUERY_EMPLOYEES,
  UPDATE_EMPLOYEE
} from "../../graphql/employees.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import ShopEmployeeComponent from "./shop-employees.component";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

function ShopEmployeesContainer({ bodyshop }) {
  const [form] = Form.useForm();
  const { t } = useTranslation();
  const employeeState = useState(null);
  const { loading, error, data, refetch } = useQuery(QUERY_EMPLOYEES, {
    fetchPolicy: "network-only"
  });

  const [updateEmployee] = useMutation(UPDATE_EMPLOYEE);
  const [insertEmployees] = useMutation(INSERT_EMPLOYEES);
  const [deleteEmployee] = useMutation(DELETE_EMPLOYEE);
  const handleDelete = id => {
    deleteEmployee({ variables: { id: id } })
      .then(r => {
        notification["success"]({
          message: t("employees.successes.delete")
        });
        //TODO Better way to reset the field decorators?
        employeeState[1](null);
        refetch().then(r => form.resetFields());
      })
      .catch(error => {
        notification["error"]({
          message: t("employees.errors.delete")
        });
      });
  };

  const handleFinish = values => {
    if (employeeState[0].id) {
      //Update a record.
      updateEmployee({
        variables: { id: employeeState[0].id, employee: values }
      })
        .then(r => {
          notification["success"]({
            message: t("employees.successes.save")
          });
          //TODO Better way to reset the field decorators?
          employeeState[1](null);
          refetch().then(r => form.resetFields());
        })
        .catch(error => {
          notification["error"]({
            message: t("employees.errors.save")
          });
        });
    } else {
      //New record, insert it.
      insertEmployees({
        variables: { employees: [{ ...values, shopid: bodyshop.id }] }
      }).then(r => {
        notification["success"]({
          message: t("employees.successes.save")
        });
        //TODO Better way to reset the field decorators?
        employeeState[1](null);
        refetch().catch(error => {
          notification["error"]({
            message: t("employees.errors.save")
          });
        });
      });
    }
  };

  if (error) return <AlertComponent message={error.message} type="error" />;

  return (
    <ShopEmployeeComponent
      handleFinish={handleFinish}
      handleDelete={handleDelete}
      form={form}
      loading={loading}
      employeeState={employeeState}
      employees={data ? data.employees : []}
    />
  );
}
export default connect(mapStateToProps, null)(ShopEmployeesContainer);
