"use client"
import { SearchJoResult, SearchJoResultRequest, fetchJos } from "@/app/api/jo/actions";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Criterion } from "../SearchBox";
import SearchResults, { Column, defaultPagingController } from "../SearchResults/SearchResults";
import { EditNote } from "@mui/icons-material";
import { decimalFormatter } from "@/app/utils/formatUtil";
import { uniqBy, upperFirst } from "lodash";
import SearchBox from "../SearchBox/SearchBox";

interface Props {
    defaultInputs: SearchJoResultRequest
}

type SearchQuery = Partial<Omit<SearchJoResult, "id">>;

type SearchParamNames = keyof SearchQuery;

const JoSearch: React.FC<Props> = ({ defaultInputs }) => {
    const { t } = useTranslation("jo");
    const [filteredJos, setFilteredJos] = useState<SearchJoResult[]>([]);
    const [inputs, setInputs] = useState(defaultInputs);
    const [pagingController, setPagingController] = useState(
        defaultPagingController
    )
    const [totalCount, setTotalCount] = useState(0)

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

    const columns = useMemo<Column<SearchJoResult>[]>(
        () => [
            {
                name: "id",
                label: t("Details"),
                onClick: (record) => onDetailClick(record),
                buttonIcon: <EditNote />,
            },
            {
                name: "code",
                label: t("Code")
            },
            {
                name: "name",
                label: t("Name"),
            },
            {
                name: "reqQty",
                label: t("Req. Qty"),
                align: "right",
                headerAlign: "right",
                renderCell: (row) => {
                    return decimalFormatter.format(row.reqQty)
                }
            },
            {
                name: "uom",
                label: t("UoM"),
                align: "left",
                headerAlign: "left",
                renderCell: (row) => {
                    return t(row.uom)
                }
            },
            {
                name: "status",
                label: t("Status"),
                renderCell: (row) => {
                    return t(upperFirst(row.status))
                }
            }
        ], []
    )

    const refetchData = useCallback(async (
        query: Record<SearchParamNames, string> | SearchJoResultRequest,
        actionType: "reset" | "search" | "paging",
    ) => {
        const params: SearchJoResultRequest = {
            code: query.code,
            name: query.name,
            pageNum: pagingController.pageNum - 1,
            pageSize: pagingController.pageSize,
        }
        const response = await fetchJos(params)

        if (response) {
            setTotalCount(response.total);
            switch (actionType) {
                case "reset":
                case "search":
                    setFilteredJos(() => response.records);
                    break;
                case "paging":
                    setFilteredJos((fs) =>
                        uniqBy([...fs, ...response.records], "id"),
                    );
                    break;
            }
        }
    }, [pagingController, setPagingController])

    useEffect(() => {
        refetchData(inputs, "paging");
    }, [pagingController]);

    const onDetailClick = useCallback((record: SearchJoResult) => {

    }, [])

    const onSearch = useCallback((query: Record<SearchParamNames, string>) => {
        setInputs(() => ({
            code: query.code,
            name: query.name
        }))
        refetchData(query, "search");
    }, [])

    const onReset = useCallback(() => {
        refetchData(defaultInputs, "paging");
    }, [])

    return <>
        <SearchBox
            criteria={searchCriteria}
            onSearch={onSearch}
            onReset={onReset}
        />
        <SearchResults<SearchJoResult>
            items={filteredJos}
            columns={columns}
            setPagingController={setPagingController}
            pagingController={pagingController}
            totalCount={totalCount}
        // isAutoPaging={false}
        />
    </>
}

export default JoSearch;