import { Input, Table } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import PhoneFormatter from "../../utils/PhoneFormatter";
import { alphaSort } from "../../utils/sorters";

export default function OwnersListComponent({ loading, owners, refetch }) {
  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" }
  });

  const { t } = useTranslation();

  const columns = [
    {
      title: t("owners.fields.name"),
      dataIndex: "name",
      key: "name",
      // onFilter: (value, record) => record.ro_number.includes(value),
      // filteredValue: state.filteredInfo.text || null,
      sorter: (a, b) => alphaSort(a.ownr_ln, b.ownr_ln),
      sortOrder:
        state.sortedInfo.columnKey === "name" && state.sortedInfo.order,

      render: (text, record) => (
        <Link to={"/manage/owners/" + record.id}>
          {`${record.ownr_fn} ${record.ownr_ln}`}
        </Link>
      )
    },
    {
      title: t("owners.fields.ownr_ph1"),
      dataIndex: "ownr_ph1",
      key: "ownr_ph1",
      sorter: (a, b) => alphaSort(a.ownr_ph1, b.ownr_ph1),
      sortOrder:
        state.sortedInfo.columnKey === "ownr_ph1" && state.sortedInfo.order,
      render: (text, record) => {
        return <PhoneFormatter>{record.ownr_ph1}</PhoneFormatter>;
      }
    },
    {
      title: t("owners.fields.ownr_ea"),
      dataIndex: "ownr_ea",
      key: "ownr_ea"
    },
    {
      title: t("owners.fields.address"),
      dataIndex: "address",
      key: "address",
      render: (text, record) => {
        return (
          <div>{`${record.ownr_addr1 || ""} ${record.ownr_addr2 ||
            ""} ${record.ownr_city || ""} ${record.ownr_st ||
            ""} ${record.ownr_zip || ""}`}</div>
        );
      }
    }
  ];

  const handleTableChange = (pagination, filters, sorter) => {
    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
  };
//TODO Implement searching & pagination
  return (
    <Table
      loading={loading}
      title={() => {
        return (
          <Input.Search
            placeholder="Search..."
            onSearch={value => {
              console.log(value);
            }}
            enterButton
          />
        );
      }}
      size="small"
      pagination={{ position: "top" }}
      columns={columns.map(item => ({ ...item }))}
      rowKey="id"
      dataSource={owners}
      onChange={handleTableChange}
    />
  );
}
