import { SyncOutlined } from "@ant-design/icons";
import { useQuery } from "@apollo/client/react";
import { Button, Card, Input, Modal, Space, Typography } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { QUERY_SCOREBOARD_PAGINATED } from "../../graphql/scoreboard.queries";
import { DateFormatter } from "../../utils/DateFormatter";
import { pageLimit } from "../../utils/config";
import { alphaSort, dateSort } from "../../utils/sorters";
import AlertComponent from "../alert/alert.component";
import OwnerNameDisplay, { OwnerNameDisplayFunction } from "../owner-name-display/owner-name-display.component";
import ScoreboardEntryEdit from "../scoreboard-entry-edit/scoreboard-entry-edit.component";
import ScoreboardRemoveButton from "../scoreboard-remove-button/scorebard-remove-button.component";

export default function ScoreboardJobsList() {
  const { t } = useTranslation();
  const [state, setState] = useState({
    open: false,
    search: "",
    current: 1,
    pageSize: pageLimit
  });

  const { loading, error, data, refetch } = useQuery(QUERY_SCOREBOARD_PAGINATED, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
    skip: !state.open,
    variables: {
      search: state.search !== "" ? `%${state.search}%` : null,
      offset: state.current ? (state.current - 1) * state.pageSize : 0,
      limit: state.pageSize,
      order: [
        {
          date: "desc"
        }
      ]
    }
  });

  const columns = [
    {
      title: t("jobs.fields.ro_number"),
      dataIndex: "ro_number",
      key: "ro_number",
      sorter: (a, b) => alphaSort(a.job.ro_number, b.job.ro_number),
      render: (text, record) => (
        <Link to={"/manage/jobs/" + record.job.id}>{record.job.ro_number || t("general.labels.na")}</Link>
      )
    },
    {
      title: t("jobs.fields.owner"),
      dataIndex: "owner",
      key: "owner",
      ellipsis: true,
      sorter: (a, b) => alphaSort(OwnerNameDisplayFunction(a.job), OwnerNameDisplayFunction(b.job)),
      render: (text, record) => <OwnerNameDisplay ownerObject={record.job} />
    },
    {
      title: t("jobs.fields.vehicle"),
      dataIndex: "vehicle",
      key: "vehicle",
      ellipsis: true,
      sorter: (a, b) =>
        alphaSort(
          `${a.job.v_model_yr || ""} ${a.job.v_make_desc || ""} ${a.job.v_model_desc || ""}`,
          `${b.job.v_model_yr || ""} ${b.job.v_make_desc || ""} ${b.job.v_model_desc || ""}`
        ),
      render: (text, record) => (
        <span>{`${record.job.v_model_yr || ""} ${record.job.v_make_desc || ""} ${record.job.v_model_desc || ""}`}</span>
      )
    },
    {
      title: t("scoreboard.fields.date"),
      dataIndex: "date",
      key: "date",
      sorter: (a, b) => dateSort(a.date, b.date),
      render: (text, record) => <DateFormatter>{record.date}</DateFormatter>
    },
    {
      title: t("scoreboard.fields.bodyhrs"),
      dataIndex: "bodyhrs",
      key: "bodyhrs",
      sorter: (a, b) => Number(a.bodyhrs) - Number(b.bodyhrs)
    },
    {
      title: t("scoreboard.fields.painthrs"),
      dataIndex: "painthrs",
      key: "painthrs",
      sorter: (a, b) => Number(a.painthrs) - Number(b.painthrs)
    },
    {
      title: t("general.labels.actions"),
      dataIndex: "actions",
      key: "actions",
      render: (text, record) => (
        <Space>
          <ScoreboardEntryEdit entry={record} style={{ zIndex: 15 }} />
          <ScoreboardRemoveButton scoreboardId={record.id} />
        </Space>
      )
    }
  ];

  return (
    <>
      <Modal
        open={state.open}
        destroyOnHidden
        width="80%"
        closable={false}
        cancelButtonProps={{ style: { display: "none" } }}
        onOk={() =>
          setState((state) => ({
            ...state,
            open: false,
            current: 1,
            search: ""
          }))
        }
      >
        {error && <AlertComponent type="error" title={JSON.stringify(error)} />}
        <Card
          extra={
            <Space align="middle" wrap>
              <Button onClick={() => refetch()} icon={<SyncOutlined />} />

              <Typography.Title level={4}>
                {t("general.labels.searchresults", { search: state.search })}
              </Typography.Title>
              <Input.Search
                placeholder={t("jobs.fields.ro_number")}
                allowClear
                onSearch={(value) => {
                  setState((state) => ({ ...state, search: value }));
                }}
                //value={state.search}
                enterButton
              />
            </Space>
          }
        >
          <ResponsiveTable
            columns={columns}
            mobileColumnKeys={["ro_number", "owner", "vehicle", "date", "actions"]}
            rowKey="id"
            dataSource={data ? data.scoreboard : []}
            loading={loading}
            onClick={(e) => e.stopPropagation()}
            onChange={(tableArgs) => setState((state) => ({ ...state, ...tableArgs }))}
            pagination={{
              placement: "top",
              pageSize: state.pageSize || pageLimit,
              current: state.current || 1,
              total: data ? data.scoreboard_aggregate.aggregate.count : 0
            }}
          />
        </Card>
      </Modal>
      <Button onClick={() => setState((state) => ({ ...state, open: true }))}>{t("scoreboard.labels.entries")}</Button>
    </>
  );
}
