"use client";

import React, { useCallback, 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 { Subsidiary } from "@/app/api/subsidiary";
import { deleteSubsidiary } from "@/app/api/subsidiary/actions";

interface Props {
    subsidiaries: Subsidiary[];
}

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

const SubsidiarySearch: React.FC<Props> = ({ subsidiaries }) => {
    const { t } = useTranslation();
    const router = useRouter()
    const searchParams = useSearchParams()

    const [filteredSubsidiaries, setFilteredSubsidiaries] = useState(subsidiaries);
    const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
        () => [
            { label: t("Subsidiary Code"), paramName: "code", type: "text" },
            { label: t("Subsidiary Name"), paramName: "name", type: "text" },
        ],
        [t],
    );
    const onReset = useCallback(() => {
        setFilteredSubsidiaries(subsidiaries);
    }, [subsidiaries]);

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

    const onDeleteClick = useCallback((subsidiary: Subsidiary) => {

        deleteDialog(async() => {
            await deleteSubsidiary(subsidiary.id)

            successDialog(t("Delete Success"), t)

            setFilteredSubsidiaries((prev) => prev.filter((obj) => obj.id !== subsidiary.id))
        }, t)
    }, []);

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

    return (
        <>
            <SearchBox
                criteria={searchCriteria}
                onSearch={(query) => {
                    setFilteredSubsidiaries(
                        subsidiaries.filter(
                            (subsidiary) =>
                            subsidiary.code.toLowerCase().includes(query.code.toLowerCase()) &&
                            subsidiary.name.toLowerCase().includes(query.name.toLowerCase()),
                        ),
                    );
                }}
                onReset={onReset}
            />
            <SearchResults items={filteredSubsidiaries} columns={columns} />
        </>
    );
};

export default SubsidiarySearch;