import {
  ActionDivider,
  AddBtn,
  DetailLink,
  EditLink,
  LoadingData,
  Pagination,
  SearchForm,
  SortIconWithNone,
  TableActionGroup,
} from "@/components/common";
import { BasePage, Header } from "@/components/layout";
import { useCustomersController } from "@/pages/customers/useCustomersController";
import { HandleError } from "@/pages/others";
import { settings } from "@/utils/settings";
import { useState } from "@wordpress/element";
import { __ } from "@wordpress/i18n";
import { Table } from "react-bootstrap";

export const Customers = () => {
  const {
    data,
    error,
    isLoading,
    search,
    changeSortByName,
    setPage,
    setSearchText,
  } = useCustomersController();
  const [selectedId, setSelectedId] = useState();

  if (error) return <HandleError error={error} />;
  if (isLoading) return <LoadingData />;

  return (
    <BasePage>
      <Header title={__("Customers", "yoyaku-manager")}>
        <AddBtn />
      </Header>
      <SearchForm searchText={search.search} setSearchText={setSearchText} />

      <Table striped hover>
        <thead>
          <tr>
            <th width="33%" onClick={changeSortByName}>
              {__("Name", "yoyaku-manager")}
              <SortIconWithNone order={search?.order} />
            </th>
            <th width="34%">{__("Email", "yoyaku-manager")}</th>
            <th>{__("Phone", "yoyaku-manager")}</th>
          </tr>
        </thead>
        <tbody>
          {data.items.map((customer) => (
            <tr
              key={customer.id}
              onMouseEnter={() => setSelectedId(customer.id)}
              onMouseLeave={() => setSelectedId(null)}
            >
              <td>
                {`${customer.first_name} ${customer.last_name}`}
                <TableActionGroup isVisible={selectedId === customer.id}>
                  <DetailLink id={customer.id} />
                  {settings.canWrite() && <ActionDivider />}
                  <EditLink id={customer.id} />
                </TableActionGroup>
              </td>
              <td>{customer.email}</td>
              <td>{customer.phone}</td>
            </tr>
          ))}
        </tbody>
      </Table>

      <Pagination
        currentPage={search.page}
        numPages={data.num_pages}
        setPage={setPage}
      />
    </BasePage>
  );
};
