import { SyncOutlined } from "@ant-design/icons";
import { Button, Card, Input, Space, Tag } from "antd";
import queryString from "query-string";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useLocation } from "react-router-dom";
import { alphaSort } from "../../utils/sorters";
import ResponsiveTable from "../responsive-table/responsive-table.component";

export default function VendorsListComponent({ handleNewVendor, loading, handleOnRowClick, vendors, refetch }) {
  const search = queryString.parse(useLocation().search);
  const { selectedvendor } = search;

  const [state, setState] = useState({
    sortedInfo: {},
    filteredInfo: { text: "" }
  });
  const [searchText, setSearchText] = useState("");
  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.phone"),
      dataIndex: "phone",
      key: "phone",
      width: "10%",
      sorter: (a, b) => alphaSort(a.phone, b.phone),
      sortOrder: state.sortedInfo.columnKey === "phone" && state.sortedInfo.order
    },
    {
      title: t("vendors.fields.city"),
      dataIndex: "city",
      key: "city"
    },
    {
      title: t("vendors.fields.tags"),
      dataIndex: "tags",
      key: "tags",
      render: (text, record) => (
        <Space>
          {record?.tags?.map((tag, idx) => (
            <Tag key={idx}>{tag}</Tag>
          ))}
        </Space>
      )
    }
  ];

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

  const filteredVendors = vendors
    ? searchText === ""
      ? vendors
      : vendors.filter(
          (j) =>
            (j.name || "").toString().toLowerCase().includes(searchText.toLowerCase()) ||
            (j.phone || "").toLowerCase().includes(searchText.toLowerCase()) ||
            (j.city || "").toLowerCase().includes(searchText.toLowerCase())
        )
    : [];

  return (
    <Card
      extra={
        <Space wrap>
          <Button onClick={handleNewVendor}>{t("vendors.actions.new")}</Button>
          <Button onClick={() => refetch()} icon={<SyncOutlined />} />
          <Input.Search
            placeholder={t("general.labels.search")}
            onChange={(e) => {
              setSearchText(e.target.value);
            }}
            value={searchText}
            enterButton
          />
        </Space>
      }
    >
      <ResponsiveTable
        loading={loading}
        pagination={{ placement: "top" }}
        columns={columns}
        mobileColumnKeys={["name", "phone", "city"]}
        rowKey="id"
        onChange={handleTableChange}
        dataSource={filteredVendors}
        rowSelection={{
          onSelect: handleOnRowClick,
          type: "radio",
          selectedRowKeys: [selectedvendor]
        }}
        onRow={(record) => {
          return {
            onClick: () => {
              handleOnRowClick(record);
            }
          };
        }}
      />
    </Card>
  );
}
