"use client";

import SearchBox, { Criterion } from "../SearchBox";
import { useCallback, useMemo, useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import SearchResults, { Column } from "../SearchResults/index";
import EditNote from "@mui/icons-material/EditNote";
import DeleteIcon from "@mui/icons-material/Delete";
import { useRouter } from "next/navigation";
import { deleteDialog, successDialog } from "../Swal/CustomAlerts";
import { PrinterResult } from "@/app/api/settings/printer";
import { deletePrinter } from "@/app/api/settings/printer/actions";
import PrinterSearchLoading from "./PrinterSearchLoading";

interface Props {
  printers: PrinterResult[];
}

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

const PrinterSearch: React.FC<Props> = ({ printers }) => {
  const { t } = useTranslation("common");
  const [filteredPrinters, setFilteredPrinters] = useState(printers);
  const [pagingController, setPagingController] = useState({
    pageNum: 1,
    pageSize: 10,
  });
  const router = useRouter();
  const [isSearching, setIsSearching] = useState(false);

  useEffect(() => {
    console.log("Printers prop changed:", printers);
    setFilteredPrinters(printers);
  }, [printers]);

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      {
        label: t("Name"),
        paramName: "name",
        type: "text",
      },
      {
        label: "IP",
        paramName: "ip",
        type: "text",
      },
      {
        label: t("Type"),
        paramName: "type",
        type: "text",
      },
      {
        label: t("Brand"),
        paramName: "brand",
        type: "text" },
    ],
    [t],
  );

  const onPrinterClick = useCallback(
    (printer: PrinterResult) => {
      console.log(printer);
      router.push(`/settings/printer/edit?id=${printer.id}`);
    },
    [router],
  );

  const onDeleteClick = useCallback((printer: PrinterResult) => {
    deleteDialog(async () => {
      try {
        console.log("Deleting printer with id:", printer.id);
        const result = await deletePrinter(printer.id);
        console.log("Delete result:", result);
        
        setFilteredPrinters(prev => prev.filter(p => p.id !== printer.id));
        
        router.refresh();
        
        setTimeout(() => {
          successDialog(t("Delete Success") || "刪除成功", t);
        }, 100);
      } catch (error) {
        console.error("Failed to delete printer:", error);
        const errorMessage = error instanceof Error ? error.message : (t("Delete Failed") || "刪除失敗");
        alert(errorMessage);
        router.refresh();
      }
    }, t);
  }, [t, router]);

  const columns = useMemo<Column<PrinterResult>[]>(
    () => [
      {
        name: "action",
        label: t("Edit"),
        onClick: onPrinterClick,
        buttonIcon: <EditNote />,
        sx: { width: "10%", minWidth: "80px" },
      },
      { 
        name: "name", 
        label: t("Name"),
        align: "left",
        headerAlign: "left",
        sx: { width: "20%", minWidth: "120px" },
      },
      { 
        name: "description", 
        label: t("Description"),
        align: "left",
        headerAlign: "left",
        sx: { width: "20%", minWidth: "140px" },
      },
      { 
        name: "ip", 
        label: "IP",
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: "100px" },
      },
      { 
        name: "port", 
        label: "Port",
        align: "left",
        headerAlign: "left",
        sx: { width: "10%", minWidth: "80px" },
      },
      { 
        name: "type", 
        label: t("Type"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: "100px" },
      },
            { 
        name: "brand", 
        label: t("Brand"),
        align: "left",
        headerAlign: "left",
        sx: { width: "12%", minWidth: "90px" },
      },
      { 
        name: "dpi", 
        label: "DPI",
        align: "left",
        headerAlign: "left",
        sx: { width: "10%", minWidth: "80px" },
      },
      {
        name: "action",
        label: t("Delete"),
        onClick: onDeleteClick,
        buttonIcon: <DeleteIcon />,
        color: "error",
        sx: { width: "10%", minWidth: "80px" },
      },
    ],
    [t, onPrinterClick, onDeleteClick],
  );

  console.log("PrinterSearch render - filteredPrinters:", filteredPrinters);
  console.log("PrinterSearch render - printers prop:", printers);

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onReset={() => {
          setFilteredPrinters(printers);
          setPagingController({ pageNum: 1, pageSize: pagingController.pageSize });
        }}
        onSearch={async (query) => {
          setIsSearching(true);
          try {
            let results: PrinterResult[] = printers;

            if (query.name && query.name.trim()) {
              results = results.filter((printer) =>
                printer.name?.toLowerCase().includes(query.name?.toLowerCase() || "")
              );
            }

            if (query.ip && query.ip.trim()) {
              results = results.filter((printer) =>
                printer.ip?.toLowerCase().includes(query.ip?.toLowerCase() || "")
              );
            }

            if (query.type && query.type.trim()) {
              results = results.filter((printer) =>
                printer.type?.toLowerCase().includes(query.type?.toLowerCase() || "")
              );
            }
            if (query.brand && query.brand.trim()) {
              results = results.filter((printer) =>
                printer.brand?.toLowerCase().includes(query.brand?.toLowerCase() || "")
              );
            }

            setFilteredPrinters(results);
            setPagingController({ pageNum: 1, pageSize: pagingController.pageSize });
          } catch (error) {
            console.error("Error searching printers:", error);
            setFilteredPrinters(printers);
          } finally {
            setIsSearching(false);
          }
        }}
      />
      <SearchResults<PrinterResult>
        items={filteredPrinters}
        columns={columns}
        pagingController={pagingController}
        setPagingController={setPagingController}
      />
    </>
  );
};

export default PrinterSearch;