import { useMutation } from "@apollo/client";
import {
  Button,
  Card,
  Form,
  Input,
  Menu,
  notification,
  Popover,
  Select,
  Space,
} from "antd";
import moment from "moment";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { INSERT_MANUAL_APPT } from "../../graphql/appointments.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import FormDateTimePickerComponent from "../form-date-time-picker/form-date-time-picker.component";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(JobsDetailHeaderAddEvent);

export function JobsDetailHeaderAddEvent({ bodyshop, jobid, ...props }) {
  const { t } = useTranslation();
  const [insertAppointment] = useMutation(INSERT_MANUAL_APPT);

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

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

    setLoading(true);
    try {
      insertAppointment({
        variables: {
          apt: { ...values, isintake: false, jobid, bodyshopid: bodyshop.id },
        },
        refetchQueries: ["QUERY_ALL_ACTIVE_APPOINTMENTS"],
      });
      notification.open({
        type: "success",
        message: t("appointments.successes.created"),
      });
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
      setVisibility(false);
    }
  };

  const overlay = (
    <Card>
      <div>
        <Form form={form} layout="vertical" onFinish={handleFinish}>
          <Form.Item
            label={t("appointments.fields.title")}
            name="title"
            rules={[
              {
                required: true,
                //message: t("general.validation.required"),
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item label={t("appointments.fields.note")} name="note">
            <Input />
          </Form.Item>
          <Form.Item
            label={t("appointments.fields.start")}
            name="start"
            rules={[
              {
                required: true,
                //message: t("general.validation.required"),
              },
            ]}
          >
            <FormDateTimePickerComponent
              onBlur={() => {
                const start = form.getFieldValue("start");
                form.setFieldsValue({ end: start.add(30, "minutes") });
              }}
            />
          </Form.Item>
          <Form.Item
            label={t("appointments.fields.end")}
            name="end"
            rules={[
              {
                required: true,
                //message: t("general.validation.required"),
              },
              ({ getFieldValue }) => ({
                async validator(rule, value) {
                  if (value) {
                    const { start } = form.getFieldsValue();
                    if (moment(start).isAfter(moment(value))) {
                      return Promise.reject(
                        t("employees.labels.endmustbeafterstart")
                      );
                    } else {
                      return Promise.resolve();
                    }
                  } else {
                    return Promise.resolve();
                  }
                },
              }),
            ]}
          >
            <FormDateTimePickerComponent />
          </Form.Item>
          <Form.Item label={t("appointments.fields.color")} name="color">
            <Select>
              {bodyshop.appt_colors.map((col, idx) => (
                <Select.Option key={idx} value={col.color.hex}>
                  {col.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

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

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

  return (
    <Popover content={overlay} visible={visibility}>
      <Menu.Item {...props} onClick={handleClick}>
        {t("appointments.labels.manualevent")}
      </Menu.Item>
    </Popover>
  );
}
