import { EditFilled, SaveFilled } from "@ant-design/icons";
import { useMutation } from "@apollo/client/react";
import { Button, Input, Space } from "antd";
import { 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";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({
  //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 notification = useNotification();

  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({
          title: t("jobs.errors.saving", {
            error: JSON.stringify(result.errors)
          })
        });
      }

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

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

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