import { EditFilled, SaveFilled } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Button, Input, notification, Space } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { UPDATE_APPOINTMENT } from "../../graphql/appointments.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import DataLabel from "../data-label/data-label.component";

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

export function ScheduleEventNote({ event }) {
  const [editing, setEditing] = useState(false);
  const [note, setNote] = useState(event.note || "");
  const [loading, setLoading] = useState(false);
  const [updateAppointment] = useMutation(UPDATE_APPOINTMENT);
  const { t } = useTranslation();

  const toggleEdit = async () => {
    if (editing) {
      //Await the update
      setLoading(true);
      const result = await updateAppointment({
        variables: {
          appid: event.id,
          app: { note },
        },
      });

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

      setEditing(false);
    } else {
      setEditing(true);
    }
    setLoading(false);
  };

  return (
    <DataLabel label={t("appointments.fields.note")}>
      <Space flex>
        {!editing ? (
          event.note || ""
        ) : (
          <Input.TextArea
            rows={3}
            value={note}
            onChange={(e) => setNote(e.target.value)}
            style={{ maxWidth: "8vw" }}
          />
        )}
        <Button onClick={toggleEdit} loading={loading}>
          {editing ? <SaveFilled /> : <EditFilled />}
        </Button>
      </Space>
    </DataLabel>
  );
}
export default connect(mapStateToProps, mapDispatchToProps)(ScheduleEventNote);
