"use client";

import { PoResult } from "@/app/api/po";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useRouter, useSearchParams } from "next/navigation";
import SearchBox, { Criterion } from "../SearchBox";
import SearchResults, { Column } from "../SearchResults";
import { EditNote } from "@mui/icons-material";
import { Button, Grid, Tab, Tabs, TabsProps, Typography } from "@mui/material";
import QrModal from "../PoDetail/QrModal";
import { WarehouseResult } from "@/app/api/warehouse";
import NotificationIcon from '@mui/icons-material/NotificationImportant';
import { useSession } from "next-auth/react";

type Props = {
  po: PoResult[];
  warehouse: WarehouseResult[];
};
type SearchQuery = Partial<Omit<PoResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const PoSearch: React.FC<Props> = ({ po, warehouse }) => {
  const [filteredPo, setFilteredPo] = useState<PoResult[]>(po);
  const { t } = useTranslation("purchaseOrder");
  const router = useRouter();

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(() => {
    var searchCriteria: Criterion<SearchParamNames>[] = [
      { label: t("Code"), paramName: "code", type: "text" },
      { label: t("Status"), paramName: "status", type: "select", options: ["PENDING", "RECEIVING", "COMPLETED"] },
      { label: t("Escalated"), paramName: "escalated", type: "select", options: [t("Escalated"), t("NotEscalated")] },
    ];
    return searchCriteria;
  }, [t, po]);


  const onDetailClick = useCallback(
    (po: PoResult) => {
      router.push(`/po/edit?id=${po.id}`);
    },
    [router]
  );

  const onDeleteClick = useCallback((po: PoResult) => {}, [router]);

  const columns = useMemo<Column<PoResult>[]>(
    () => [
      {
        name: "id",
        label: t("Details"),
        onClick: onDetailClick,
        buttonIcon: <EditNote />,
      },
      {
        name: "code",
        label: t("Code"),
      },
      {
        name: "orderDate",
        label: t("OrderDate"),
      },
      {
        name: "supplier",
        label: t("Supplier"),
      },
      {
        name: "status",
        label: t("Status"),
      },
      {
        name: "escalated",
        label: t("Escalated"),
        renderCell: (params) => {
          return params.escalated ? <NotificationIcon color="warning"/> : undefined
        }
      },
      // {
      //   name: "name",
      //   label: t("Name"),
      // },
      //   {
      //     name: "action",
      //     label: t(""),
      //     buttonIcon: <GridDeleteIcon />,
      //     onClick: onDeleteClick,
      //   },
    ],
    [filteredPo]
  );

  const onReset = useCallback(() => {
    setFilteredPo(po);
  }, [po]);

  const [isOpenScanner, setOpenScanner] = useState(false);
  const onOpenScanner = useCallback(() => {
    setOpenScanner(true);
  }, []);

  const onCloseScanner = useCallback(() => {
    setOpenScanner(false);
  }, []);

  return (
    <>
      <Grid container>
        <Grid item xs={8}>
          <Typography variant="h4" marginInlineEnd={2}>
            {t("Purchase Order")}
          </Typography>
        </Grid>
          <Grid
            item
            xs={4}
            display="flex"
            justifyContent="end"
            alignItems="end"
          >
            <QrModal
              open={isOpenScanner}
              onClose={onCloseScanner}
              warehouse={warehouse}
            />
            <Button onClick={onOpenScanner}>bind</Button>
          </Grid>
      </Grid>
        <>
          <SearchBox
            criteria={searchCriteria}
            onSearch={(query) => {
              setFilteredPo(
                po.filter((p) => {
                  return (
                    p.code.toLowerCase().includes(query.code.toLowerCase()) &&
                    (query.status === "All" || p.status === query.status) &&
                    (query.escalated === "All" || p.escalated === (query.escalated === t("Escalated")))
                  )
                })
              );
            }}
            onReset={onReset}
          />
          <SearchResults<PoResult> items={filteredPo} columns={columns} />
        </>

    </>
  );
};
export default PoSearch;
