import { useMutation } from "@apollo/client/react";
import { Button, Form, Popconfirm, Select } from "antd";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

export function JobsAdminClass({ bodyshop, job }) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [updateJob] = useMutation(UPDATE_JOB);
  const notification = useNotification();

  const handleFinish = async (values) => {
    setLoading(true);
    const result = await updateJob({
      variables: { jobId: job.id, job: values }
    });

    if (!result.errors) {
      notification.success({ title: t("jobs.successes.save") });
    } else {
      notification.error({
        title: t("jobs.errors.saving", {
          error: JSON.stringify(result.errors)
        })
      });
    }
    setLoading(false);
    //Get the owner details, populate it all back into the job.
  };

  useEffect(() => {
    //form.resetFields();
  }, [form, job]);

  return (
    <div>
      <Form onFinish={handleFinish} autoComplete={"off"} form={form} layout="vertical" initialValues={job}>
        <Form.Item
          name={["class"]}
          label={t("jobs.fields.class")}
          rules={[
            {
              required: bodyshop.enforce_class
              //message: t("general.validation.required"),
            }
          ]}
        >
          <Select
            options={bodyshop.md_classes.map((s) => ({
              value: s,
              label: s
            }))}
          />
        </Form.Item>
      </Form>

      <Popconfirm title={t("jobs.labels.changeclass")} onConfirm={() => form.submit()}>
        <Button loading={loading} type="primary">
          {t("general.actions.save")}
        </Button>
      </Popconfirm>
    </div>
  );
}
