import { DeleteFilled, PlusCircleFilled } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import {
  Button,
  Col,
  notification,
  Popover,
  Row,
  Select,
  Space,
  Spin,
} from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
import { insertAuditTrail } from "../../redux/application/application.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AuditTrailMapping from "../../utils/AuditTrailMappings";

const iconStyle = { marginLeft: ".3rem" };
const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation }) =>
    dispatch(insertAuditTrail({ jobid, operation })),
});

export function ProductionListEmpAssignment({
  insertAuditTrail,
  bodyshop,
  record,
  type,
}) {
  const { t } = useTranslation();
  const [updateJob] = useMutation(UPDATE_JOB);
  const [loading, setLoading] = useState(false);

  const handleAdd = async (assignment) => {
    setLoading(true);
    const { operation, employeeid, name } = assignment;
    logImEXEvent("job_assign_employee", { operation });

    let empAssignment = determineFieldName(operation);

    const result = await updateJob({
      variables: { jobId: record.id, job: { [empAssignment]: employeeid } },

      //   awaitRefetchQueries: true,
    });

    insertAuditTrail({
      jobid: record.id,
      operation: AuditTrailMapping.jobassignmentchange(empAssignment, name),
    });

    if (!!result.errors) {
      notification["error"]({
        message: t("jobs.errors.assigning", {
          message: JSON.stringify(result.errors),
        }),
      });
    }
    setLoading(false);
  };
  const handleRemove = async (operation) => {
    setLoading(true);
    logImEXEvent("job_unassign_employee", { operation });

    let empAssignment = determineFieldName(operation);
    const result = await updateJob({
      variables: { jobId: record.id, job: { [empAssignment]: null } },

      awaitRefetchQueries: true,
    });

    insertAuditTrail({
      jobid: record.id,
      operation: AuditTrailMapping.jobassignmentremoved(empAssignment),
    });

    if (!!result.errors) {
      notification["error"]({
        message: t("jobs.errors.assigning", {
          message: JSON.stringify(result.errors),
        }),
      });
    }
    setLoading(false);
  };

  const [assignment, setAssignment] = useState({
    operation: null,
    employeeid: null,
  });

  const [visibility, setVisibility] = useState(false);
  const onChange = (e, option) => {
    setAssignment({ ...assignment, employeeid: e, name: option.name });
  };

  const popContent = (
    <Row gutter={[16, 16]}>
      <Col span={24}>
        <Select
          id="employeeSelector"
          showSearch
          style={{ width: 200 }}
          optionFilterProp="children"
          onChange={onChange}
          filterOption={(input, option) =>
            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >=
            0
          }
        >
          {bodyshop.employees
            .filter((emp) => emp.active)
            .map((emp) => (
              <Select.Option
                value={emp.id}
                key={emp.id}
                name={`${emp.first_name} ${emp.last_name}`}
              >
                {`${emp.first_name} ${emp.last_name}`}
              </Select.Option>
            ))}
        </Select>
      </Col>
      <Col span={24}>
        <Space wrap>
          <Button
            type="primary"
            disabled={!assignment.employeeid}
            onClick={() => {
              handleAdd(assignment);
              setVisibility(false);
            }}
          >
            Assign
          </Button>
          <Button onClick={() => setVisibility(false)}>Close</Button>
        </Space>
      </Col>
    </Row>
  );

  let theEmployee;

  if (record[type])
    theEmployee = bodyshop.employees.find((e) => e.id === record[type]);

  return (
    <Popover destroyTooltipOnHide content={popContent} visible={visibility}>
      <Spin spinning={loading}>
        {record[type] ? (
          <div>
            <span>{`${theEmployee.first_name || ""} ${
              theEmployee.last_name || ""
            }`}</span>
            <DeleteFilled
              style={iconStyle}
              onClick={() => handleRemove(type)}
            />
          </div>
        ) : (
          <PlusCircleFilled
            style={iconStyle}
            onClick={() => {
              setAssignment({ operation: type });
              setVisibility(true);
            }}
          />
        )}
      </Spin>
    </Popover>
  );
}

const determineFieldName = (operation) => {
  switch (operation) {
    case "employee_body":
      return "employee_body";
    case "employee_prep":
      return "employee_prep";
    case "employee_refinish":
      return "employee_refinish";
    case "employee_csr":
      return "employee_csr";
    default:
      return null;
  }
};

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