import { SyncOutlined } from "@ant-design/icons";
import { Button, Card } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import queryString from "query-string";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { DateFormatter } from "../../utils/DateFormatter";
import { pageLimit } from "../../utils/config";
import { alphaSort, dateSort } from "../../utils/sorters";
import OwnerNameDisplay, { OwnerNameDisplayFunction } from "../owner-name-display/owner-name-display.component";

export default function CsiResponseListPaginated({ refetch, loading, responses, total }) {
  const search = queryString.parse(useLocation().search);
  const { responseid } = search;
  const history = useNavigate();
  const { t } = useTranslation();
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" },
    page: ""
  });

  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),
      sortOrder: state.sortedInfo.columnKey === "ro_number" && state.sortedInfo.order,
      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_name",
      key: "owner_name",
      sorter: (a, b) => alphaSort(OwnerNameDisplayFunction(a.job), OwnerNameDisplayFunction(b.job)),
      sortOrder: state.sortedInfo.columnKey === "owner_name" && state.sortedInfo.order,
      render: (text, record) => {
        return record.job.ownerid ? (
          <Link to={"/manage/owners/" + record.job.ownerid}>
            <OwnerNameDisplay ownerObject={record.job} />
          </Link>
        ) : (
          <span>
            <OwnerNameDisplay ownerObject={record.job} />
          </span>
        );
      }
    },
    {
      title: t("csi.fields.completedon"),
      dataIndex: "completedon",
      key: "completedon",
      ellipsis: true,
      sorter: (a, b) => dateSort(a.completedon, b.completedon),
      sortOrder: state.sortedInfo.columnKey === "completedon" && state.sortedInfo.order,
      render: (text, record) => {
        return record.completedon ? <DateFormatter>{record.completedon}</DateFormatter> : null;
      }
    }
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    setState({
      ...state,
      filteredInfo: filters,
      sortedInfo: sorter,
      page: pagination.current
    });
  };

  const handleOnRowClick = (record) => {
    if (record) {
      if (record.id) {
        search.responseid = record.id;
        history({ search: queryString.stringify(search) });
      }
    } else {
      delete search.responseid;
      history({ search: queryString.stringify(search) });
    }
  };

  return (
    <Card extra={<Button onClick={() => refetch()} icon={<SyncOutlined />} />}>
      <ResponsiveTable
        loading={loading}
        pagination={{ placement: "top", pageSize: pageLimit, current: parseInt(state.page || 1), total: total }}
        columns={columns}
        mobileColumnKeys={["ro_number", "owner_name", "completedon"]}
        rowKey="id"
        dataSource={responses}
        onChange={handleTableChange}
        rowSelection={{
          onSelect: (record) => {
            handleOnRowClick(record);
          },
          selectedRowKeys: [responseid],
          type: "radio"
        }}
      />
    </Card>
  );
}
