import { Select } from "antd";
import { useEffect, useState } from "react";
import { useMutation } from "@apollo/client/react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { UPDATE_JOB_LINE } from "../../graphql/jobs-lines.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

export function JobLineStatusPopup({ bodyshop, jobline, disabled }) {
  const [editing, setEditing] = useState(false);
  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState(jobline.status);
  const [updateJob] = useMutation(UPDATE_JOB_LINE);
  const { t } = useTranslation();
  const notification = useNotification();

  useEffect(() => {
    if (editing) setStatus(jobline.status);
  }, [editing, jobline.status]);

  const handleChange = (e) => {
    setStatus(e);
  };

  const handleSave = async () => {
    setLoading(true);
    const result = await updateJob({
      variables: { lineId: jobline.id, line: { status: status || "" } }
    });

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

  if (editing)
    return (
      <div>
        <LoadingSpinner loading={loading}>
          <Select
            autoFocus
            allowClear
            popupMatchSelectWidth={100}
            value={status}
            onSelect={handleChange}
            onBlur={handleSave}
            onClear={() => handleChange(null)}
            options={Object.values(bodyshop.md_order_statuses).map((s, idx) => ({
              key: idx,
              value: s,
              label: s
            }))}
          />
        </LoadingSpinner>
      </div>
    );
  return (
    <div style={{ width: "100%", minHeight: "1rem", cursor: "pointer" }} onClick={() => !disabled && setEditing(true)}>
      {jobline.status}
    </div>
  );
}

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