import { CheckCircleFilled, EyeInvisibleFilled } from "@ant-design/icons";
import { Button, List, Popover } from "antd";
import { useCallback, useMemo, useState } from "react";
import { useMutation } from "@apollo/client/react";
import { useTranslation } from "react-i18next";
import { UPDATE_JOB_LINE_SUBLET } from "../../graphql/jobs-lines.queries";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

export default function ProductionSubletsManageComponent({ subletJobLines }) {
  const { t } = useTranslation();
  const [updateJobLine] = useMutation(UPDATE_JOB_LINE_SUBLET);
  const [loading, setLoading] = useState(false);
  const notification = useNotification();

  const subletCount = useMemo(
    () => ({
      total: subletJobLines.filter((s) => !s.sublet_ignored).length,
      outstanding: subletJobLines.filter((s) => !s.sublet_ignored && !s.sublet_completed).length
    }),
    [subletJobLines]
  );

  const handleSubletMark = useCallback(
    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({
          title: t("joblines.errors.updating", {
            message: JSON.stringify(result.errors)
          })
        });
      } else {
        notification.success({
          title: t("joblines.successes.updated")
        });
      }
      setLoading(false);
    },
    [updateJobLine, t, notification]
  );

  const popContent = useMemo(
    () => (
      <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"}
                  icon={<CheckCircleFilled style={{ color: s.sublet_completed ? "green" : undefined }} />}
                />,
                <Button
                  key="sublet"
                  loading={loading}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleSubletMark(s, "ignore");
                  }}
                  type={s.sublet_ignored ? "primary" : "ghost"}
                  icon={<EyeInvisibleFilled style={{ color: s.sublet_ignored ? "tomato" : undefined }} />}
                />
              ]}
            >
              <List.Item.Meta title={s.line_desc} />
            </List.Item>
          )}
        />
      </div>
    ),
    [subletJobLines, loading, handleSubletMark]
  );

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