import React from "react";

import { TableBody } from "@mui/material";

import { Header } from "../../../../components/Header";
import SearchBar from "../../../../components/SearchBar";
import { Table } from "../../../../components/Table";
import TableHead from "../../../../components/Table/TableHead";
import TableHeading from "../../../../components/Table/TableHeading";
import TableCard from "../../../../components/TableCard";
import { TitleBar } from "../../../../components/TitleBar";
import Content from "../../../../containers/Content";
import { useI18n } from "../../../../contexts/I18nContext";
import { useRouter } from "../../../../contexts/RouterContext";
import { LimitOffset, PageComponent } from "../../../../types";
import { PurchaseRow } from "../../components/PurchaseRow";
import { PurchaseDetail } from "../../types/purchase";

const PurchaseListPage: PageComponent<LimitOffset<PurchaseDetail>> = ({ data }) => {
  const { t } = useI18n();
  const { navigate } = useRouter();

  return (
    <>
      <Header>
        <TitleBar title="Purchases">
          <SearchBar
            defaultValue={new URLSearchParams(window.location.search).get("search") ?? ""}
            placeholder={t("Search by email, phone, or number…")}
            onSubmit={(input) => {
              if (input === "") {
                navigate("pos.purchase:list", {
                  replace: true,
                });
              } else {
                navigate("pos.purchase:list", {
                  query: {
                    search: input,
                  },
                  replace: true,
                });
              }
            }}
          />
        </TitleBar>
      </Header>

      <Content layout="fullWidth">
        <TableCard>
          <Table pagination count={data?.count}>
            <TableHead>
              <TableHeading width={60}>{t("Number")}</TableHeading>
              <TableHeading>{t("Items")}</TableHeading>
              <TableHeading>{t("Name")}</TableHeading>
              <TableHeading>{t("Email")}</TableHeading>
              <TableHeading align="right">{t("Total")}</TableHeading>
              <TableHeading>{t("Date")}</TableHeading>
            </TableHead>

            <TableBody>
              {data?.results.map((purchase) => (
                <PurchaseRow key={purchase.number} purchase={purchase} />
              ))}
            </TableBody>
          </Table>
        </TableCard>
      </Content>
    </>
  );
};

export default PurchaseListPage;
