import { useMutation } from "@apollo/client/react";
import { Button, Card, Form, Input, Popover, Select, 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 { INSERT_MANUAL_APPT, UPDATE_APPOINTMENT } 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 = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(ScheduleManualEvent);

export function ScheduleManualEvent({ bodyshop, event }) {
  const { t } = useTranslation();
  const [insertAppointment] = useMutation(INSERT_MANUAL_APPT);
  const [updateAppointment] = useMutation(UPDATE_APPOINTMENT);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [visibility, setVisibility] = useState(false);
  //   const [callQuery, { loading: entryLoading, data: entryData }] = useLazyQuery(
  //     QUERY_SCOREBOARD_ENTRY
  //   );

  useEffect(() => {
    if (visibility && event) {
      form.setFieldsValue(event);
    }
  }, [visibility, form, event]);

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

    setLoading(true);
    try {
      if (event?.id) {
        updateAppointment({
          variables: { appid: event.id, app: values },
          refetchQueries: ["QUERY_ALL_ACTIVE_APPOINTMENTS"]
        });
      } else {
        insertAppointment({
          variables: {
            apt: { ...values, isintake: false, bodyshopid: bodyshop.id }
          },
          refetchQueries: ["QUERY_ALL_ACTIVE_APPOINTMENTS"]
        });
      }
      form.resetFields();
      setVisibility(false);
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(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 />
          </Form.Item>
          <Form.Item
            label={t("appointments.fields.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();
                  }
                }
              })
            ]}
          >
            <FormDateTimePickerComponent />
          </Form.Item>
          <Form.Item label={t("appointments.fields.color")} name="color">
            <Select
              options={bodyshop.appt_colors.map((col) => ({
                value: col.color.hex,
                label: col.label
              }))}
            />
          </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>
      </div>
    </Card>
  );

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

  return (
    <Popover content={overlay} open={visibility}>
      <Button loading={loading} onClick={handleClick}>
        {event ? t("appointments.actions.reschedule") : t("appointments.labels.manualevent")}
      </Button>
    </Popover>
  );
}
