"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, integerFormatter } from "@/app/utils/formatUtil";
import { orderBy, uniqBy, upperFirst } from "lodash";
import SearchBox from "../SearchBox/SearchBox";
import { useRouter } from "next/navigation";
import { FormProvider, SubmitErrorHandler, SubmitHandler, useForm } from "react-hook-form";
import { JoDetail } from "@/app/api/jo";
import { Button, Stack } from "@mui/material";
import { BomCombo } from "@/app/api/bom";
import JoCreateFormModal from "./JoCreateFormModal";
import AddIcon from '@mui/icons-material/Add';

interface Props {
    defaultInputs: SearchJoResultRequest,
    bomCombo: BomCombo[]
}

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

type SearchParamNames = keyof SearchQuery;

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

    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 integerFormatter.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(() => orderBy(response.records, ["id"], ["desc"]));
                    break;
                case "paging":
                    setFilteredJos((fs) =>
                        orderBy(uniqBy([...fs, ...response.records], "id"), ["id"], ["desc"]),
                    );
                    break;
            }
        }
    }, [pagingController, setPagingController])

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

    const onDetailClick = useCallback((record: SearchJoResult) => {
        router.push(`/jo/edit?id=${record.id}`)
    }, [])

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

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

    // Manual Create Jo Related

    const onOpenCreateJoModal = useCallback(() => {
        setIsCreateJoModalOpen(() => true)
    }, [])

    const onCloseCreateJoModal = useCallback(() => {
        setIsCreateJoModalOpen(() => false)
    }, [])

    return <>
        <Stack
            direction="row"
            justifyContent="flex-end"
            spacing={2}
            sx={{ mt: 2 }}
        >
            <Button
                variant="outlined"
                startIcon={<AddIcon />}
                onClick={onOpenCreateJoModal}
            >
                {t("Create Job Order")}
            </Button>
        </Stack>
        <SearchBox
            criteria={searchCriteria}
            onSearch={onSearch}
            onReset={onReset}
        />
        <SearchResults<SearchJoResult>
            items={filteredJos}
            columns={columns}
            setPagingController={setPagingController}
            pagingController={pagingController}
            totalCount={totalCount}
        // isAutoPaging={false}
        />
        <JoCreateFormModal
            open={isCreateJoModalOpen}
            bomCombo={bomCombo}
            onClose={onCloseCreateJoModal}
            onSearch={searchDataByPage}
        />
    </>
}

export default JoSearch;