"use client";
import {
  Html5QrcodeResult,
  Html5QrcodeScanner,
  QrcodeErrorCallback,
  QrcodeSuccessCallback,
} from "html5-qrcode";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import SearchResults, { Column } from "../SearchResults";
import EditNote from "@mui/icons-material/EditNote";
import { QcItemResult } from "@/app/api/settings/qcItem";
import { usePathname, useRouter } from "next/navigation";
import QrCodeScanner from "../QrCodeScanner";
import { Button } from "@mui/material";
import { Delete } from "@mui/icons-material";
import { deleteDialog, successDialog } from "../Swal/CustomAlerts";
import { deleteQcItem } from "@/app/api/settings/qcItem/actions";

interface Props {
  qcItems: QcItemResult[];
}

type SearchQuery = Partial<Omit<QcItemResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const QcItemSearch: React.FC<Props> = ({ qcItems }) => {
  const { t } = useTranslation("qcItem");
  const router = useRouter();
  const pathname = usePathname();

  // If qcItem searching is done on the server-side, then no need for this.
  const [filteredQcItems, setFilteredQcItems] = useState(qcItems);

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      { label: t("Code"), paramName: "code", type: "text" },
      { label: t("Name"), paramName: "name", type: "text" },
    ],
    [t],
  );

  const onReset = useCallback(() => {
    setFilteredQcItems(qcItems);
  }, [qcItems]);

  const onQcItemClick = useCallback(
    (qcItem: QcItemResult) => {
      router.push(`${pathname}/edit?id=${qcItem.id}`);
    },
    [router],
  );

  const handleDelete = useCallback((qcItem: QcItemResult) => {
    deleteDialog(async () => {
      qcItems = await deleteQcItem(qcItem.id);
      setFilteredQcItems(qcItems);

      await successDialog(t("Delete Success"), t);
    }, t);
  }, []);

  const columnWidthSx = (width = "10%") => {
    return { width: width, whiteSpace: "nowrap" };
  };

  const columns = useMemo<Column<QcItemResult>[]>(
    () => [
      {
        name: "id",
        label: t("Details"),
        sx: columnWidthSx("150px"),
        onClick: onQcItemClick,
        buttonIcon: <EditNote />,
      },
      { name: "code", label: t("Code"), sx: columnWidthSx() },
      { name: "name", label: t("Name"), sx: columnWidthSx() },
      { name: "description", label: t("Description") },
      {
        name: "id",
        label: t("Delete"),
        onClick: handleDelete,
        buttonIcon: <Delete />,
        buttonColor: "error",
      },
    ],
    [t, onQcItemClick],
  );

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

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

  // const handleScanSuccess = useCallback((result: string) => {
  //   console.log(result)
  // }, [])

  return (
    <>
      {/* <QrCodeScanner isOpen={isOpenScanner} onClose={onCloseScanner} onScanSuccess={handleScanSuccess} />
      <Button onClick={onOpenScanner}>abc</Button> */}
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilteredQcItems(
            qcItems.filter(
              (qi) =>
                qi.code.toLowerCase().includes(query.code.toLowerCase()) &&
                qi.name.toLowerCase().includes(query.name.toLowerCase()),
            ),
          );
        }}
        onReset={onReset}
      />
      <SearchResults<QcItemResult> items={filteredQcItems} columns={columns} />
    </>
  );
};

export default QcItemSearch;
