import { useMutation } from "@apollo/client/react";
import { Button, Card, Form, Popover, Space } from "antd";
import dayjs from "../../utils/day";
import { 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";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

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

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

    setLoading(true);
    if (!employee?.id) {
      notification.error({
        title: t("employees.errors.adding", { message: "Employee not loaded yet." })
      });
      return;
    }

    setLoading(true);
    const 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({
        title: t("employees.errors.adding", {
          message: JSON.stringify(result.errors)
        })
      });
    } else {
      notification.success({
        title: 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"),
            },
            () => ({
              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 = () => {
    setVisibility(true);
  };

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