import { useMutation } from "@apollo/client/react";
import { UPDATE_APPOINTMENT } from "../../graphql/appointments.queries";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { Dropdown } from "antd";
import { DownOutlined } from "@ant-design/icons";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({});

export function ScheduleEventColor({ bodyshop, event }) {
  const [updateAppointment] = useMutation(UPDATE_APPOINTMENT);
  const { t } = useTranslation();
  const notification = useNotification();

  const onClick = async ({ key }) => {
    const result = await updateAppointment({
      variables: {
        appid: event.id,
        app: { color: key === "null" ? null : key }
      }
    });

    if (!result.errors) {
      notification.success({ title: t("appointments.successes.saved") });
    } else {
      notification.error({
        title: t("appointments.errors.saving", {
          error: JSON.stringify(result.errors)
        })
      });
    }
  };

  const selectedColor =
    event.color &&
    bodyshop.appt_colors &&
    bodyshop.appt_colors.filter((color) => color.color.hex === event.color)[0]?.label;

  const menu = {
    defaultSelectedKeys: [event.color],
    onClick: onClick,
    items: [
      ...(bodyshop.appt_colors || []).map((color) => ({
        key: color.color.hex,
        label: color.label,
        style: { color: color.color.hex }
      })),
      { type: "divider" },
      { key: "null", label: t("general.actions.clear") }
    ]
  };

  return (
    <Dropdown menu={menu}>
      <a href=" #" onClick={(e) => e.preventDefault()}>
        {selectedColor}
        <DownOutlined />
      </a>
    </Dropdown>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ScheduleEventColor);
