import { CheckCircleFilled, EyeInvisibleFilled } from "@ant-design/icons";
import { Button, List, notification, Popover } from "antd";
import React, { useMemo, useState } from "react";
import { useMutation } from "@apollo/client";
import { useTranslation } from "react-i18next";
import { UPDATE_JOB_LINE_SUBLET } from "../../graphql/jobs-lines.queries";
export default function ProductionSubletsManageComponent({ subletJobLines }) {
  const { t } = useTranslation();
  const [updateJobLine] = useMutation(UPDATE_JOB_LINE_SUBLET);
  const [loading, setLoading] = useState(false);
  const subletCount = useMemo(() => {
    return {
      total: subletJobLines.filter((s) => !s.sublet_ignored).length,
      outstanding: subletJobLines.filter(
        (s) => !s.sublet_ignored && !s.sublet_completed
      ).length,
    };
  }, [subletJobLines]);

  const handleSubletMark = async (sublet, action) => {
    setLoading(true);

    const result = await updateJobLine({
      variables: {
        jobId: sublet.jobid,
        now: new Date(),
        lineId: sublet.id,
        line: {
          sublet_completed:
            action === "complete" ? !sublet.sublet_completed : false,
          sublet_ignored: action === "ignore" ? !sublet.sublet_ignored : false,
        },
      },
    });

    if (!!result.errors) {
      notification["error"]({
        message: t("joblines.errors.updating", {
          message: JSON.stringify(result.errors),
        }),
      });
    } else {
      notification["success"]({
        message: t("joblines.successes.updated"),
      });
    }
    setLoading(false);
  };

  const popContent = (
    <div style={{ minWidth: "20rem" }}>
      <List
        onClick={(e) => e.stopPropagation()}
        dataSource={subletJobLines}
        renderItem={(s) => (
          <List.Item
            actions={[
              <Button
                key="complete"
                loading={loading}
                onClick={(e) => {
                  e.stopPropagation();
                  handleSubletMark(s, "complete");
                }}
                type={s.sublet_completed ? "primary" : "ghost"}
              >
                <CheckCircleFilled
                  color={s.sublet_completed ? "green" : null}
                />
              </Button>,
              <Button
                key="sublet"
                loading={loading}
                onClick={(e) => {
                  e.stopPropagation();
                  handleSubletMark(s, "ignore");
                }}
                type={s.sublet_ignored ? "primary" : "ghost"}
              >
                <EyeInvisibleFilled
                  color={s.sublet_ignored ? "tomato" : null}
                />
              </Button>,
            ]}
          >
            <List.Item.Meta title={s.line_desc} />
          </List.Item>
        )}
      />
    </div>
  );

  return (
    <Popover
      trigger={["click"]}
      content={popContent}
      style={{ cursor: "pointer" }}
      placement="bottom"
      title={t("production.labels.sublets")}
    >
      <span style={{ color: subletCount.outstanding > 0 ? "tomato" : "" }}>{`${
        subletCount.total - subletCount.outstanding
      } / ${subletCount.total}`}</span>
    </Popover>
  );
}
