"use client";

import { Customer } from "@/app/api/customer";
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 DeleteIcon from '@mui/icons-material/Delete';
import { useRouter, useSearchParams } from "next/navigation";
import { deleteDialog, successDialog } from "../Swal/CustomAlerts";
import { deleteCustomer } from "@/app/api/customer/actions";
import { MAINTAIN_CLIENT } from "@/middleware";

interface Props {
    customers: Customer[];
    abilities: String[];
}

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

const CustomerSearch: React.FC<Props> = ({ customers, abilities }) => {
    const { t } = useTranslation();
    const router = useRouter()
    const searchParams = useSearchParams()
    const maintainClient = abilities.includes(MAINTAIN_CLIENT)

    const [filteredCustomers, setFilteredCustomers] = useState(customers);
    useEffect(() => {
        setFilteredCustomers(customers)
    }, [customers])
    const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
        () => [
            { label: t("Customer Code"), paramName: "code", type: "text" },
            { label: t("Customer Name"), paramName: "name", type: "text" },
        ],
        [t],
    );
    const onReset = useCallback(() => {
        setFilteredCustomers(customers);
    }, [customers]);

    const onTaskClick = useCallback((customer: Customer) => {
        const params = new URLSearchParams(searchParams.toString())
        params.set("id", customer.id.toString())
        router.push(`/settings/customer/edit?${params.toString()}`);
    }, []);

    const onDeleteClick = useCallback((customer: Customer) => {

        deleteDialog(async() => {
            await deleteCustomer(customer.id)

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

    const columns = useMemo<Column<Customer>[]>(
        () => [
            {
                name: "id",
                label: t("Details"),
                onClick: onTaskClick,
                buttonIcon: <EditNote />,
                isHidden: !maintainClient
            },
            { name: "code", label: t("Customer Code") },
            { name: "name", label: t("Customer Name") },
            {
                name: "id",
                label: t("Delete"),
                onClick: onDeleteClick,
                buttonIcon: <DeleteIcon />,
                color: "error",
                isHidden: !maintainClient
            },
        ],
        [onTaskClick, t],
    );

    return (
        <>
            <SearchBox
                criteria={searchCriteria}
                onSearch={(query) => {
                    setFilteredCustomers(
                        customers.filter(
                            (customer) =>
                            customer.code.toLowerCase().includes(query.code.toLowerCase()) &&
                            customer.name.toLowerCase().includes(query.name.toLowerCase()),
                        ),
                    );
                }}
                onReset={onReset}
            />
            <SearchResults items={filteredCustomers} columns={columns} />
        </>
    );
};

export default CustomerSearch;