"use client"

import { M18ImportTestingForm, testM18ImportPo, M18ImportPoForm, testM18ImportPq, testM18ImportMasterData, testM18ImportDo } from "@/app/api/settings/m18ImportTesting/actions";
import { Card, CardContent, Grid, Stack, Typography } from "@mui/material";
import React, { BaseSyntheticEvent, FormEvent, useCallback, useState } from "react";
import { FormProvider, SubmitErrorHandler, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import M18ImportPo from "./M18ImportPo";
import M18ImportPq from "./M18ImportPq";
import { dateTimeStringToDayjs } from "@/app/utils/formatUtil";
import M18ImportMasterData from "./M18ImportMasterData";
import M18ImportDo from "./M18ImportDo";

interface Props {

}

const M18ImportTesting: React.FC<Props> = ({

}) => {

    const { t } = useTranslation()
    const [isLoading, setIsLoading] = useState(false)
    const [loadingType, setLoadingType] = useState<String | null>(null)
    const formProps = useForm<M18ImportTestingForm>()

    const onSubmit = useCallback(async (data: M18ImportTestingForm, event?: BaseSyntheticEvent) => {
        console.log(isLoading)

        if (isLoading) {
            return;
        }

        const buttonId = (event?.nativeEvent as SubmitEvent).submitter?.id
        console.log(data)
        console.log(buttonId)

        switch (buttonId) {
            case "m18ImportMasterData":
                const mdDateFrom = data.masterData.modifiedDateFrom
                const mdDateTo = data.masterData.modifiedDateTo
                if (!(!mdDateFrom || dateTimeStringToDayjs(mdDateFrom).isValid())) {
                    formProps.setError("masterData.modifiedDateFrom", { message: "Invalid DateTime Format" })
                }

                if (!(!mdDateTo || dateTimeStringToDayjs(mdDateTo).isValid())) {
                    formProps.setError("masterData.modifiedDateTo", { message: "Invalid DateTime Format" })
                }

                if (formProps.formState.errors.masterData) {
                    return;
                }

                setIsLoading(() => true)
                setLoadingType(() => "Master Data")
                const mdResponse = await testM18ImportMasterData(data.masterData)
                console.log(mdResponse)
                if (mdResponse) {
                    setIsLoading(() => false)
                }
                break;
            case "m18ImportPo":
                const poDateFrom = data.po.modifiedDateFrom
                const poDateTo = data.po.modifiedDateTo
                if (!(poDateFrom && dateTimeStringToDayjs(poDateFrom).isValid())) {
                    formProps.setError("po.modifiedDateFrom", { message: "Invalid DateTime Format" })
                }

                if (!(poDateTo && dateTimeStringToDayjs(poDateTo).isValid())) {
                    formProps.setError("po.modifiedDateTo", { message: "Invalid DateTime Format" })
                }

                if (formProps.formState.errors.po) {
                    return;
                }

                setIsLoading(() => true)
                setLoadingType(() => "Purchase Order")
                const poResponse = await testM18ImportPo(data.po)
                console.log(poResponse)
                if (poResponse) {
                    setIsLoading(() => false)
                }
                break;
            case "m18ImportDo":
                const doDateFrom = data.do.modifiedDateFrom
                const doDateTo = data.do.modifiedDateTo
                if (!(doDateFrom && dateTimeStringToDayjs(doDateFrom).isValid())) {
                    formProps.setError("do.modifiedDateFrom", { message: "Invalid DateTime Format" })
                }

                if (!(doDateTo && dateTimeStringToDayjs(doDateTo).isValid())) {
                    formProps.setError("do.modifiedDateTo", { message: "Invalid DateTime Format" })
                }

                if (formProps.formState.errors.do) {
                    return;
                }

                setIsLoading(() => true)
                setLoadingType(() => "Delivery Order")
                const doResponse = await testM18ImportDo(data.po)
                console.log(doResponse)
                if (doResponse) {
                    setIsLoading(() => false)
                }
                break;
            case "m18ImportPq":
                const pqDateFrom = data.pq.modifiedDateFrom
                const pqDateTo = data.pq.modifiedDateTo
                if (!(pqDateFrom || dateTimeStringToDayjs(pqDateFrom).isValid())) {
                    formProps.setError("pq.modifiedDateFrom", { message: "Invalid DateTime Format" })
                }

                if (!(pqDateTo || dateTimeStringToDayjs(pqDateTo).isValid())) {
                    formProps.setError("pq.modifiedDateTo", { message: "Invalid DateTime Format" })
                }

                if (formProps.formState.errors.pq) {
                    return;
                }

                setIsLoading(() => true)
                setLoadingType(() => "Purchase Quotation")
                const pqResponse = await testM18ImportPq(data.pq)
                console.log(pqResponse)
                if (pqResponse) {
                    setIsLoading(() => false)
                }
                break;
            default:
                break;
        }
    }, [])

    // const onSubmitError = useCallback<SubmitErrorHandler<M18ImportTestingForm>>(
    //     (errors) => {
    //         console.log(errors)
    //     },
    //     [],
    // );

    return (
        <Card>
            <CardContent sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
                <Typography variant="overline">{t("Status: ")}{isLoading ? t(`Importing ${loadingType}...`) : t("Ready to import")}</Typography>
                <FormProvider {...formProps}>
                    <Stack
                        spacing={2}
                        component={"form"}
                        onSubmit={formProps.handleSubmit(onSubmit)}
                    >
                        <Grid container columnGap={2} rowGap={2}>
                            <Grid item xs={12}>
                                <M18ImportMasterData />
                            </Grid>
                            <Grid item xs={12}>
                                <M18ImportPo />
                            </Grid>
                            <Grid item xs={12}>
                                <M18ImportDo />
                            </Grid>
                            <Grid item xs={12}>
                                <M18ImportPq />
                            </Grid>
                        </Grid>
                    </Stack>
                </FormProvider>
            </CardContent>
        </Card>
    )
}

export default M18ImportTesting;