import { useMutation } from "@apollo/client/react";
import { Button, Card, Col, Row } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import dayjs from "../../utils/day";
import { useTranslation } from "react-i18next";
import { UPDATE_PARTS_DISPATCH_LINE } from "../../graphql/parts-dispatch.queries";
import { DateTimeFormatter } from "../../utils/DateFormatter";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

export default function PartsDispatchExpander({ dispatch }) {
  const { t } = useTranslation();
  const [updateDispatchLine] = useMutation(UPDATE_PARTS_DISPATCH_LINE);
  const notification = useNotification();

  const handleAccept = async ({ partsDispatchLineId }) => {
    const accepted_at = dayjs();
    const result = await updateDispatchLine({
      variables: { id: partsDispatchLineId, line: { accepted_at } },
      optimisticResponse: {
        update_parts_dispatch_lines_by_pk: {
          accepted_at,
          id: partsDispatchLineId
        }
      }
    });
    if (result.errors) {
      notification.error({
        title: t("parts_dispatch.errors.accepting", {
          error: JSON.stringify(result.errors)
        })
      });
    }
  };

  const columns = [
    {
      title: t("joblines.fields.part_qty"),
      dataIndex: "quantity",
      key: "quantity",
      width: "10%"
      //sorter: (a, b) => alphaSort(a.number, b.number),
    },
    {
      title: t("joblines.fields.line_desc"),
      dataIndex: "joblineid",
      key: "joblineid",
      //sorter: (a, b) => alphaSort(a.number, b.number),
      render: (text, record) => record.jobline.line_desc
    },
    {
      title: t("parts_dispatch_lines.fields.accepted_at"),
      dataIndex: "accepted_at",
      key: "accepted_at",
      width: "20%",

      //sorter: (a, b) => alphaSort(a.number, b.number),
      render: (text, record) =>
        record.accepted_at ? (
          <DateTimeFormatter>{record.accepted_at}</DateTimeFormatter>
        ) : (
          <Button onClick={() => handleAccept({ partsDispatchLineId: record.id })}>
            {t("parts_dispatch.actions.accept")}
          </Button>
        )
    }
  ];
  return (
    <Card>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <ResponsiveTable
            rowKey={"id"}
            dataSource={dispatch.parts_dispatch_lines}
            columns={columns}
            mobileColumnKeys={["quantity", "joblineid", "accepted_at"]}
          />
        </Col>
      </Row>
    </Card>
  );
}
