"use client";

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

interface Props {
    subsidiaries: Subsidiary[];
    abilities: String[];
}

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

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

    const [filteredSubsidiaries, setFilteredSubsidiaries] = useState(subsidiaries);
    useEffect(() => {
        setFilteredSubsidiaries(subsidiaries)
    }, [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.push(`/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 />,
                isHidden: !maintainSubsidiary,
            },
            { name: "code", label: t("Subsidiary Code") },
            { name: "name", label: t("Subsidiary Name") },
            {
                name: "id",
                label: t("Delete"),
                onClick: onDeleteClick,
                buttonIcon: <DeleteIcon />,
                color: "error",
                isHidden: !maintainSubsidiary,
            },
        ],
        [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;