import { Input, Table, Button } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { alphaSort } from "../../utils/sorters";
export default function VendorsListComponent({
  selectedVendor,
  setSelectedVendor,
  handleNewVendor,
  loading,
  refetch,
  handleOnRowClick,
  vendors
}) {
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" }
  });

  const { t } = useTranslation();

  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.street1"),
      dataIndex: "street1",
      key: "street1",
      width: "10%",
      sorter: (a, b) => alphaSort(a.street1, b.street1),
      sortOrder:
        state.sortedInfo.columnKey === "street1" && state.sortedInfo.order
    },
    {
      title: t("vendors.fields.city"),
      dataIndex: "city",
      key: "city"
    }
  ];

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

  //TODO Implement search
  return (
    <div>
      <Table
        loading={loading}
        title={() => {
          return (
            <div>
              {" "}
              <Input.Search
                placeholder={t("general.labels.search")}
                onSearch={value => {
                  console.log(value);
                }}
                enterButton
              />
              <Button onClick={handleNewVendor}>
                {t("vendors.actions.new")}
              </Button>
            </div>
          );
        }}
        size="small"
        pagination={{ position: "top" }}
        columns={columns.map(item => ({ ...item }))}
        rowKey="id"
        onChange={handleTableChange}
        dataSource={vendors}
        rowSelection={{
          onSelect: record => {
            setSelectedVendor(record);
          },
          type: "radio",
          selectedRowKeys: selectedVendor ? selectedVendor.id : null
        }}
        onRow={(record, rowIndex) => {
          return {
            onClick: event => {
              handleOnRowClick(record);
            }
          };
        }}
      />
    </div>
  );
}
