import { Button } from "antd";
import queryString from "query-string";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router-dom";
import ConfigListEmptyState from "../layout-form-row/config-list-empty-state.component.jsx";
import LayoutFormRow from "../layout-form-row/layout-form-row.component";
import ResponsiveTable from "../responsive-table/responsive-table.component";

export default function ShopEmployeeTeamsListComponent({
  loading,
  employee_teams,
  onRequestTeamChange,
  selectedTeamId
}) {
  const { t } = useTranslation();
  const history = useNavigate();
  const search = queryString.parse(useLocation().search);

  const navigateToTeam = (employeeTeamId) => {
    if (onRequestTeamChange) {
      onRequestTeamChange(employeeTeamId);
      return;
    }

    history({
      search: queryString.stringify({
        ...search,
        employeeTeamId
      })
    });
  };

  const clearTeamSelection = () => {
    const { employeeTeamId, ...nextSearch } = search;
    void employeeTeamId;
    history({
      search: queryString.stringify(nextSearch)
    });
  };

  const handleOnRowClick = (record) => {
    if (record) {
      navigateToTeam(record.id);
    } else {
      clearTeamSelection();
    }
  };
  const columns = [
    {
      title: t("employee_teams.fields.name"),
      dataIndex: "name",
      key: "name"
    }
  ];

  return (
    <LayoutFormRow
      title={t("bodyshop.labels.employee_teams")}
      actions={[
        <Button key="new-team" type="primary" block onClick={() => navigateToTeam("new")}>
          {t("employee_teams.actions.new")}
        </Button>
      ]}
    >
      {employee_teams.length === 0 ? (
        <ConfigListEmptyState actionLabel={t("employee_teams.actions.new")} />
      ) : (
        <ResponsiveTable
          loading={loading}
          pagination={{ placement: "top" }}
          columns={columns}
          mobileColumnKeys={["name"]}
          rowKey="id"
          dataSource={employee_teams}
          rowSelection={{
            onSelect: (props) => navigateToTeam(props.id),
            type: "radio",
            selectedRowKeys: [selectedTeamId || search.employeeTeamId]
          }}
          onRow={(record) => {
            return {
              onClick: () => {
                handleOnRowClick(record);
              }
            };
          }}
        />
      )}
    </LayoutFormRow>
  );
}
