import { Button } from "antd";
import queryString from "query-string";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router-dom";
import { alphaSort } from "../../utils/sorters";
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 ShopEmployeesListComponent({
  loading,
  employees,
  onRequestEmployeeChange,
  selectedEmployeeId
}) {
  const { t } = useTranslation();
  const history = useNavigate();
  const search = queryString.parse(useLocation().search);

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

  const navigateToEmployee = (employeeId) => {
    if (onRequestEmployeeChange) {
      onRequestEmployeeChange(employeeId);
      return;
    }

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

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

  const handleOnRowClick = (record) => {
    if (record) {
      navigateToEmployee(record.id);
    } else {
      clearEmployeeSelection();
    }
  };
  const handleTableChange = (pagination, filters, sorter) => {
    setState({ ...state, filteredInfo: filters, sortedInfo: sorter });
  };
  const columns = [
    {
      title: t("employees.labels.employee_number_short"),
      dataIndex: "employee_number",
      key: "employee_number",
      sorter: (a, b) => alphaSort(a.employee_number, b.employee_number),
      sortOrder: state.sortedInfo.columnKey === "employee_number" && state.sortedInfo.order
    },
    {
      title: t("employees.labels.name"),
      dataIndex: "employee_name",
      key: "employee_name",
      sorter: (a, b) =>
        alphaSort(
          `${a.first_name || ""} ${a.last_name || ""}`.trim(),
          `${b.first_name || ""} ${b.last_name || ""}`.trim()
        ),
      sortOrder: state.sortedInfo.columnKey === "employee_name" && state.sortedInfo.order,
      render: (text, record) => `${record.first_name || ""} ${record.last_name || ""}`.trim()
    },
    {
      title: t("employees.labels.rate_type"),
      dataIndex: "rate_type",
      key: "rate_type",
      sorter: (a, b) => Number(a.flat_rate) - Number(b.flat_rate),
      sortOrder: state.sortedInfo.columnKey === "rate_type" && state.sortedInfo.order,
      filters: [
        {
          text: t("employees.labels.flat_rate"),
          value: true
        },
        {
          text: t("employees.labels.straight_time"),
          value: false
        }
      ],
      onFilter: (value, record) => value === record.flat_rate,
      render: (text, record) =>
        record.flat_rate ? t("employees.labels.flat_rate") : t("employees.labels.straight_time")
    },
    {
      title: t("employees.labels.status"),
      dataIndex: "active",
      key: "active",
      sorter: (a, b) => Number(a.active) - Number(b.active),
      sortOrder: state.sortedInfo.columnKey === "active" && state.sortedInfo.order,
      filters: [
        {
          text: t("employees.labels.active"),
          value: true
        },
        {
          text: t("employees.labels.inactive"),
          value: false
        }
      ],
      onFilter: (value, record) => value === record.active,
      render: (text, record) => (record.active ? t("employees.labels.active") : t("employees.labels.inactive"))
    }
  ];
  return (
    <LayoutFormRow
      title={t("bodyshop.labels.employees")}
      actions={[
        <Button key="new-employee" type="primary" block onClick={() => navigateToEmployee("new")}>
          {t("employees.actions.new")}
        </Button>
      ]}
    >
      {employees.length === 0 ? (
        <ConfigListEmptyState actionLabel={t("employees.actions.new")} />
      ) : (
        <ResponsiveTable
          loading={loading}
          pagination={{ placement: "top" }}
          columns={columns}
          mobileColumnKeys={["employee_number", "employee_name", "active"]}
          rowKey="id"
          dataSource={employees}
          rowSelection={{
            onSelect: (props) => navigateToEmployee(props.id),
            type: "radio",
            selectedRowKeys: [selectedEmployeeId || search.employeeId]
          }}
          onChange={handleTableChange}
          onRow={(record) => {
            return {
              onClick: () => {
                handleOnRowClick(record);
              }
            };
          }}
        />
      )}
    </LayoutFormRow>
  );
}
