import { DownOutlined } from "@ant-design/icons";
import { Button, Card, Popover } from "antd";
import { useLazyQuery } from "@apollo/client/react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { QUERY_JOBS_IN_PRODUCTION } from "../../graphql/jobs.queries";
import { DateTimeFormatter } from "../../utils/DateFormatter";
import AlertComponent from "../alert/alert.component";
import LoadingSkeleton from "../loading-skeleton/loading-skeleton.component";
import "./schedule-production-list.styles.scss";
import OwnerNameDisplay from "../owner-name-display/owner-name-display.component";

export default function ScheduleProductionList() {
  const { t } = useTranslation();
  const [callQuery, { loading, error, data }] = useLazyQuery(QUERY_JOBS_IN_PRODUCTION);

  const content = () => {
    return (
      <Card>
        <div onClick={(e) => e.stopPropagation()} className="jobs-in-production-table">
          {loading ? <LoadingSkeleton /> : null}
          {error ? <AlertComponent title={error.message} type="error" /> : null}
          {data ? (
            <table>
              <thead>
                <tr>
                  <th> {t("appointments.labels.ro_number")}</th>
                  <th> {t("appointments.labels.owner")}</th>
                  <th> {t("appointments.labels.vehicle")}</th>
                  <th> {t("appointments.labels.bp")}</th>
                  <th> {t("appointments.labels.scheduled_completion")}</th>
                </tr>
              </thead>
              <tbody>
                {data?.jobs
                  ? data.jobs.map((j) => (
                      <tr key={j.id}>
                        <td>
                          <Link to={`/manage/jobs/${j.id}`}>{j.ro_number}</Link>
                        </td>
                        <td>
                          <OwnerNameDisplay ownerObject={j} />
                        </td>
                        <td>{`${j.v_model_yr || ""} ${j.v_make_desc || ""} ${j.v_model_desc || ""}`}</td>
                        <td>{`${j.labhrs.aggregate.sum.mod_lb_hrs || "0"} / ${
                          j.larhrs.aggregate.sum.mod_lb_hrs || "0"
                        }`}</td>
                        <td>
                          <DateTimeFormatter>{j.scheduled_completion}</DateTimeFormatter>
                        </td>
                      </tr>
                    ))
                  : null}
              </tbody>
            </table>
          ) : null}
        </div>
      </Card>
    );
  };

  return (
    <Popover content={content} trigger="click" placement="bottomRight">
      <Button onClick={() => callQuery({ variables: {} })} icon={<DownOutlined />} iconPlacement="end">
        {t("appointments.labels.inproduction")}
      </Button>
    </Popover>
  );
}
