import { useState } from "react";
import { useMutation } from "@apollo/client/react";
import { Button, Form, Popover, Select, Space } from "antd";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { UPDATE_LINE_BULK_ASSIGN } from "../../graphql/jobs-lines.queries";
import { selectJobReadOnly } from "../../redux/application/application.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { insertAuditTrail } from "../../redux/application/application.actions";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { logImEXEvent } from "../../firebase/firebase.utils.js";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  jobRO: selectJobReadOnly
});
const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation }) => dispatch(insertAuditTrail({ jobid, operation }))
});
export default connect(mapStateToProps, mapDispatchToProps)(JoblineBulkAssign);

export function JoblineBulkAssign({ setSelectedLines, selectedLines, insertAuditTrail, bodyshop, jobRO, job }) {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  const { t } = useTranslation();
  const [assignLines] = useMutation(UPDATE_LINE_BULK_ASSIGN);
  const notification = useNotification();

  const handleConvert = async (values) => {
    try {
      setLoading(true);
      logImEXEvent("joblines_bulk_assign", {});
      const result = await assignLines({
        variables: {
          jobline: {
            assigned_team: values.assigned_team
          },
          ids: selectedLines.map((l) => l.id)
        }
      });
      if (result.errors) {
        notification.error({
          title: t("parts_dispatch.errors.creating", {
            error: JSON.stringify(result.errors)
          })
        });
      } else {
        //Insert the audit trail here.

        const teamName = bodyshop.employee_teams.find((et) => et.id === values.assigned_team)?.name;

        const hours = selectedLines.reduce((acc, val) => (acc += val.mod_lb_hrs), 0);

        insertAuditTrail({
          jobid: job.id,
          operation: AuditTrailMapping.assignedlinehours(teamName, hours.toFixed(1))
        });
        setSelectedLines([]);
        setVisible(false);
      }
    } catch (error) {
      notification.error({
        title: t("parts_dispatch.errors.creating", {
          error: error
        })
      });
    } finally {
      setLoading(false);
    }
  };

  const popMenu = (
    <div>
      <Form layout="vertical" form={form} onFinish={handleConvert}>
        <Form.Item
          name={"assigned_team"}
          label={t("joblines.fields.assigned_team")}
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            }
          ]}
        >
          <Select
            showSearch={{
              optionFilterProp: "label",
              filterOption: (input, option) => option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }}
            style={{ width: 200 }}
            options={bodyshop.employee_teams.map((team) => ({
              value: team.id,
              label: team.name
            }))}
          />
        </Form.Item>

        <Space wrap>
          <Button type="danger" onClick={() => form.submit()} loading={loading}>
            {t("general.actions.save")}
          </Button>
          <Button onClick={() => setVisible(false)}>{t("general.actions.cancel")}</Button>
        </Space>
      </Form>
    </div>
  );

  return (
    <Popover open={visible} content={popMenu}>
      <Button disabled={selectedLines.length === 0 || jobRO} loading={loading} onClick={() => setVisible(true)}>
        {t("joblines.actions.assign_team", { count: selectedLines.length })}
      </Button>
    </Popover>
  );
}
