import { DeleteFilled, PlusCircleFilled } from "@ant-design/icons";
import { Button, Col, Popover, Row, Select, Space, Spin } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectJobReadOnly } from "../../redux/application/application.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import DataLabel from "../data-label/data-label.component";
import InstanceRenderManager from "../../utils/instanceRenderMgr";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  jobRO: selectJobReadOnly
});
const mapDispatchToProps = () => ({});

const iconStyle = { marginLeft: ".3rem" };

export function JobEmployeeAssignments({
  bodyshop,
  jobRO,
  body,
  refinish,
  prep,
  csr,
  handleAdd,
  handleRemove,
  loading
}) {
  const { t } = useTranslation();

  // Which assignment popover is currently open: "body" | "prep" | "refinish" | "csr" | null
  const [openOperation, setOpenOperation] = useState(null);

  // Current selection inside the popover
  const [selected, setSelected] = useState({ employeeid: null, name: null });

  const employeeOptions = (bodyshop?.employees || [])
    .filter((emp) => emp.active)
    .map((emp) => ({
      value: emp.id,
      label: `${emp.first_name} ${emp.last_name}`
    }));

  const getPopupContainer = () => document.querySelector("#time-ticket-modal") || document.body;

  const openFor = (operation) => {
    if (jobRO) return;
    setSelected({ employeeid: null, name: null });
    setOpenOperation(operation);
  };

  const close = () => {
    setOpenOperation(null);
    setSelected({ employeeid: null, name: null });
  };

  const renderAssigner = (operation) => {
    if (jobRO) {
      return <PlusCircleFilled disabled style={iconStyle} />;
    }

    const popContent = (
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Select
            style={{ width: 220 }}
            options={employeeOptions}
            value={selected.employeeid}
            placeholder={t("employees.actions.select")}
            allowClear
            showSearch={{
              optionFilterProp: "label"
            }}
            onChange={(value, option) => {
              if (!value) {
                setSelected({ employeeid: null, name: null });
                return;
              }
              setSelected({ employeeid: value, name: option?.label || null });
            }}
          />
        </Col>

        <Col span={24}>
          <Space wrap>
            <Button
              type="primary"
              disabled={!selected.employeeid}
              onClick={() => {
                handleAdd({ operation, employeeid: selected.employeeid, name: selected.name });
                close();
              }}
            >
              {t("allocations.actions.assign")}
            </Button>
            <Button onClick={close}>Close</Button>
          </Space>
        </Col>
      </Row>
    );

    return (
      <Popover
        destroyOnHidden
        trigger="click"
        open={openOperation === operation}
        onOpenChange={(open) => {
          // Important: let Popover drive close on outside click
          if (open) openFor(operation);
          else close();
        }}
        content={popContent}
        getPopupContainer={getPopupContainer}
      >
        <span
          role="button"
          tabIndex={0}
          onClick={(e) => {
            // Prevent the click from being re-interpreted as "outside"
            e.preventDefault();
            e.stopPropagation();
            openFor(operation);
          }}
          onKeyDown={(e) => {
            if (e.key === "Enter" || e.key === " ") {
              e.preventDefault();
              openFor(operation);
            }
          }}
          style={{ display: "inline-flex", alignItems: "center" }}
        >
          <PlusCircleFilled style={iconStyle} />
        </span>
      </Popover>
    );
  };

  return (
    <Spin spinning={loading}>
      <DataLabel label={t("jobs.fields.employee_body")}>
        {body ? (
          <div>
            <span>{`${body.first_name || ""} ${body.last_name || ""}`}</span>
            <DeleteFilled
              disabled={jobRO}
              style={iconStyle}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                if (!jobRO) handleRemove("body");
              }}
            />
          </div>
        ) : (
          renderAssigner("body")
        )}
      </DataLabel>

      <DataLabel label={t("jobs.fields.employee_prep")}>
        {prep ? (
          <div>
            <span>{`${prep.first_name || ""} ${prep.last_name || ""}`}</span>
            <DeleteFilled
              disabled={jobRO}
              style={iconStyle}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                if (!jobRO) handleRemove("prep");
              }}
            />
          </div>
        ) : (
          renderAssigner("prep")
        )}
      </DataLabel>

      <DataLabel label={t("jobs.fields.employee_refinish")}>
        {refinish ? (
          <div>
            <span>{`${refinish.first_name || ""} ${refinish.last_name || ""}`}</span>
            <DeleteFilled
              disabled={jobRO}
              style={iconStyle}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                if (!jobRO) handleRemove("refinish");
              }}
            />
          </div>
        ) : (
          renderAssigner("refinish")
        )}
      </DataLabel>

      <DataLabel
        label={t(
          InstanceRenderManager({
            imex: "jobs.fields.employee_csr",
            rome: "jobs.fields.employee_csr_writer"
          })
        )}
      >
        {csr ? (
          <div>
            <span>{`${csr.first_name || ""} ${csr.last_name || ""}`}</span>
            <DeleteFilled
              disabled={jobRO}
              style={iconStyle}
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                if (!jobRO) handleRemove("csr");
              }}
            />
          </div>
        ) : (
          renderAssigner("csr")
        )}
      </DataLabel>
    </Spin>
  );
}

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