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

export default function OwnersListComponent({ loading, owners, total, refetch }) {
  const search = queryString.parse(useLocation().search);
  const { page, pageSize } = search;
  const history = useNavigate();

  const currentPage = Number.parseInt(page || "1", 10);
  const parsedPageSize = Number.parseInt(pageSize || String(pageLimit), 10);
  const currentPageSize = Number.isNaN(parsedPageSize) ? pageLimit : parsedPageSize;

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

  const { t } = useTranslation();

  const columns = [
    {
      title: t("owners.fields.name"),
      dataIndex: "name",
      key: "name",
      render: (text, record) => (
        <Link to={"/manage/owners/" + record.id}>
          <OwnerNameDisplay ownerObject={record} />
        </Link>
      )
    },
    {
      title: t("owners.fields.ownr_ph1"),
      dataIndex: "ownr_ph1",
      key: "ownr_ph1",
      render: (text, record) => {
        return <PhoneFormatter type={record.ownr_ph1_ty}>{record.ownr_ph1}</PhoneFormatter>;
      }
    },
    {
      title: t("owners.fields.ownr_ph2"),
      dataIndex: "ownr_ph2",
      key: "ownr_ph2",
      render: (text, record) => {
        return <PhoneFormatter type={record.ownr_ph2_ty}>{record.ownr_ph2}</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) => {
    const nextPageSize = pagination?.pageSize || currentPageSize;
    const pageSizeChanged = nextPageSize !== currentPageSize;

    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
    const updatedSearch = {
      ...search,
      pageSize: nextPageSize,
      page: pageSizeChanged ? 1 : pagination.current,
      sortcolumn: sorter.columnKey,
      sortorder: sorter.order
    };
    history({ search: queryString.stringify(updatedSearch) });
  };
  return (
    <Card
      title={t("menus.header.owners")}
      extra={
        <Space wrap>
          {search.search && (
            <>
              <Typography.Title level={4}>
                {t("general.labels.searchresults", { search: search.search })}
              </Typography.Title>
              <Button
                onClick={() => {
                  delete search.search;
                  history({ search: queryString.stringify(search) });
                }}
              >
                {t("general.actions.clear")}
              </Button>
            </>
          )}
          <Button onClick={() => refetch()} icon={<SyncOutlined />} />
          <Input.Search
            placeholder={search.search || t("general.labels.search")}
            onSearch={(value) => {
              const updatedSearch = { ...search };
              if (value?.length >= 3) {
                updatedSearch.search = value;
              } else {
                delete updatedSearch.search;
              }
              history({ search: queryString.stringify(updatedSearch) });
            }}
            enterButton
          />
        </Space>
      }
    >
      <ResponsiveTable
        loading={loading}
        pagination={{ placement: "top", pageSize: currentPageSize, current: currentPage, showSizeChanger: true, total: total }}
        columns={columns}
        mobileColumnKeys={["name", "ownr_ph1", "ownr_ph2"]}
        rowKey="id"
        scroll={{ x: true }}
        dataSource={owners}
        onChange={handleTableChange}
      />
    </Card>
  );
}
