import { useState } from "react";
import { QUERY_ALL_VENDORS } from "../../graphql/vendors.queries";
import { useQuery } from "@apollo/client/react";
import queryString from "query-string";
import { useLocation, useNavigate } from "react-router-dom";
import { Input } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { useTranslation } from "react-i18next";
import { alphaSort } from "../../utils/sorters";
import AlertComponent from "../alert/alert.component";

export default function BillsVendorsList() {
  const search = queryString.parse(useLocation().search);
  const history = useNavigate();

  const { loading, error, data } = useQuery(QUERY_ALL_VENDORS, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  const { t } = useTranslation();

  const [state, setState] = useState({
    sortedInfo: {},
    search: ""
  });

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

  const columns = [
    {
      title: t("vendors.fields.name"),
      dataIndex: "name",
      key: "name",
      sorter: (a, b) => alphaSort(a.name, b.name),
      sortOrder: state.sortedInfo.columnKey === "name" && state.sortedInfo.order
    },
    {
      title: t("vendors.fields.cost_center"),
      dataIndex: "cost_center",
      key: "cost_center",
      sorter: (a, b) => alphaSort(a.cost_center, b.cost_center),
      sortOrder: state.sortedInfo.columnKey === "cost_center" && state.sortedInfo.order
    },
    {
      title: t("vendors.fields.city"),
      dataIndex: "city",
      key: "city"
    }
  ];

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

  const handleSearch = (e) => {
    setState({ ...state, search: e.target.value });
  };

  if (error) return <AlertComponent title={error.message} type="error" />;

  const dataSource = state.search
    ? data.vendors.filter(
        (v) =>
          (v.name || "").toLowerCase().includes(state.search.toLowerCase()) ||
          (v.cost_center || "").toLowerCase().includes(state.search.toLowerCase()) ||
          (v.city || "").toLowerCase().includes(state.search.toLowerCase())
      )
    : (data && data.vendors) || [];

  return (
    <ResponsiveTable
      loading={loading}
      title={() => {
        return (
          <div>
            <Input value={state.search} onChange={handleSearch} placeholder={t("general.labels.search")} allowClear />
          </div>
        );
      }}
      dataSource={dataSource}
      pagination={{ placement: "top" }}
      columns={columns}
      mobileColumnKeys={["name", "cost_center", "city"]}
      rowKey="id"
      onChange={handleTableChange}
      rowSelection={{
        onSelect: (record) => {
          handleOnRowClick(record);
        },
        selectedRowKeys: [search.vendorid],
        type: "radio"
      }}
      onRow={(record) => {
        return {
          onClick: () => {
            handleOnRowClick(record);
          } // click row
        };
      }}
    />
  );
}
