import React, { useState } from "react";

import { useMutation } from "@apollo/client";
import { Button, Form, notification, 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, selectCurrentUser } from "../../redux/user/user.selectors";
import { insertAuditTrail } from "../../redux/application/application.actions";
import AuditTrailMapping from "../../utils/AuditTrailMappings";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  jobRO: selectJobReadOnly,
  currentUser: selectCurrentUser
});
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,
  currentUser
}) {
  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 handleConvert = async (values) => {
    try {
      setLoading(true);
      const result = await assignLines({
        variables: {
          jobline: {
            assigned_team: values.assigned_team
          },
          ids: selectedLines.map((l) => l.id)
        }
      });
      if (result.errors) {
        notification.open({
          type: "error",
          message: 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.open({
        type: "error",
        message: 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
            style={{ width: 200 }}
            optionFilterProp="children"
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >
            {bodyshop.employee_teams.map((team) => (
              <Select.Option value={team.id} key={team.id} name={team.name}>
                {team.name}
              </Select.Option>
            ))}
          </Select>
        </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>
  );
}
