import { useMutation } from "@apollo/client";
import { Button, Card, Form, notification, Popover, Space } from "antd";
import dayjs from "../../utils/day";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { INSERT_VACATION } from "../../graphql/employees.queries";
import DateTimePicker from "../form-date-time-picker/form-date-time-picker.component.jsx";

export default function ShopEmployeeAddVacation({ employee }) {
  const { t } = useTranslation();
  const [insertVacation] = useMutation(INSERT_VACATION);

  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [visibility, setVisibility] = useState(false);

  const handleFinish = async (values) => {
    logImEXEvent("employee_add_vacation");

    setLoading(true);
    let result;

    result = await insertVacation({
      variables: { vacation: { ...values, employeeid: employee.id } },
      update(cache, { data }) {
        cache.modify({
          id: cache.identify({ id: employee.id, __typename: "employees" }),
          fields: {
            employee_vacations(ex) {
              return [data.insert_employee_vacation_one, ...ex];
            }
          }
        });
      }
    });

    if (!!result.errors) {
      notification["error"]({
        message: t("employees.errors.adding", {
          message: JSON.stringify(result.errors)
        })
      });
    } else {
      notification["success"]({
        message: t("employees.successes.vacationadded")
      });
    }
    form.resetFields();
    setLoading(false);
    setVisibility(false);
  };

  const overlay = (
    <Card>
      <Form form={form} layout="vertical" onFinish={handleFinish}>
        <Form.Item
          label={t("employees.fields.vacation.start")}
          name="start"
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            }
          ]}
        >
          <DateTimePicker isDateOnly />
        </Form.Item>
        <Form.Item
          label={t("employees.fields.vacation.end")}
          name="end"
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            },
            ({ getFieldValue }) => ({
              async validator(rule, value) {
                if (value) {
                  const { start } = form.getFieldsValue();
                  if (dayjs(start).isAfter(dayjs(value))) {
                    return Promise.reject(t("employees.labels.endmustbeafterstart"));
                  } else {
                    return Promise.resolve();
                  }
                } else {
                  return Promise.resolve();
                }
              }
            })
          ]}
        >
          <DateTimePicker isDateOnly />
        </Form.Item>

        <Space wrap>
          <Button type="primary" htmlType="submit">
            {t("general.actions.save")}
          </Button>
          <Button onClick={() => setVisibility(false)}>{t("general.actions.cancel")}</Button>
        </Space>
      </Form>
    </Card>
  );

  const handleClick = (e) => {
    setVisibility(true);
  };

  return (
    <Popover content={overlay} open={visibility}>
      <Button loading={loading} disabled={!employee?.active} onClick={handleClick}>
        {t("employees.actions.addvacation")}
      </Button>
    </Popover>
  );
}
