import { useMutation } from "@apollo/client/react";
import { Button, Card, Dropdown, Form, Input, Space } from "antd";
import dayjs from "../../utils/day";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
import { INSERT_NEW_NOTE } from "../../graphql/notes.queries";
import { selectCurrentUser } from "../../redux/user/user.selectors";
import { DateFormatter } from "../../utils/DateFormatter";
import FormDateTimePickerComponent from "../form-date-time-picker/form-date-time-picker.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(ProductionLastContacted);

export function ProductionLastContacted({ currentUser, record }) {
  const [updateAlert] = useMutation(UPDATE_JOB);
  const [insertNote] = useMutation(INSERT_NEW_NOTE);
  const [open, setOpen] = useState(false);
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const notification = useNotification();

  const handleFinish = async ({ date_last_contacted, date_next_contact, note }) => {
    logImEXEvent("production_last_contacted");

    //e.stopPropagation();
    const res = await updateAlert({
      variables: {
        jobId: record.id,
        job: {
          date_last_contacted,
          ...(date_next_contact ? { date_next_contact } : {})
        }
      }
    });
    if (res.errors) {
      notification.error({
        title: t("jobs.errors.saving", {
          error: JSON.stringify(res.errors)
        })
      });
    }
    if (note && note.trim() !== "") {
      //Insert a note.
      const res2 = await insertNote({
        variables: {
          noteInput: {
            jobid: record.id,
            text: note,
            created_by: currentUser.email
          }
        }
      });
      if (res2.errors) {
        notification.error({
          title: t("notes.errors.inserting", {
            error: JSON.stringify(res.errors)
          })
        });
      }
    }
    if (record.refetch) record.refetch();

    setOpen(false);
  };

  useEffect(() => {
    if (open) {
      form.setFieldsValue({
        note: null,
        date_last_contacted: record.date_last_contacted && dayjs(record.date_last_contacted)
      });
    }
  }, [open, form, record.date_last_contacted]);

  const overlayMenu = {
    items: [
      {
        key: "overlay-item-1",
        label: (
          <Card style={{ padding: "1rem" }} onClick={(e) => e.stopPropagation()}>
            <Form form={form} onFinish={handleFinish} layout="vertical">
              <Form.Item name="date_last_contacted" label={t("jobs.fields.date_last_contacted")}>
                <FormDateTimePickerComponent />
              </Form.Item>
              <Form.Item name="date_next_contact" label={t("jobs.fields.date_next_contact")}>
                <FormDateTimePickerComponent />
              </Form.Item>
              <Form.Item label={t("notes.labels.notetoadd")} name="note">
                <Input.TextArea rows={4} />
              </Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  {t("general.actions.save")}
                </Button>
                <Button onClick={() => setOpen(false)}>{t("general.actions.close")}</Button>
              </Space>
            </Form>
          </Card>
        )
      }
    ]
  };

  return (
    <div>
      <Dropdown
        //trigger={["click"]}
        open={open}
        style={{
          height: "19px"
        }}
        menu={overlayMenu}
      >
        <div
          onClick={() => setOpen(true)}
          style={{
            height: "19px",
            cursor: "pointer"
          }}
        >
          <DateFormatter bordered={false}>{record.date_last_contacted}</DateFormatter>
        </div>
      </Dropdown>
    </div>
  );
}
