"use client"

import { ImportTestingForm, testImportPo } from "@/app/api/settings/importTesting/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 ImportPo from "./ImportPo";
import { ImportPoForm } from "@/app/api/settings/importTesting/actions";

interface Props {

}

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

}) => {

    const { t } = useTranslation()
    const [isLoading, setIsLoading] = useState(false)
    const formProps = useForm<ImportTestingForm>()

    const onSubmit = useCallback(async (data: ImportTestingForm, event?: BaseSyntheticEvent) => {
        const buttonId = (event?.nativeEvent as SubmitEvent).submitter?.id
        console.log(data.po)
        switch (buttonId) {
            case "importPo":
                setIsLoading(() => true)
                const response = await testImportPo(data.po)
                console.log(response)
                if (response) {
                    setIsLoading(() => false)
                }
                break;
            default:
                break;
        }
    }, [])

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

    return (
        <Card>
            <CardContent sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
                <Typography variant="overline">{t("Status: ")}{isLoading ? t("Importing...") : t("Ready to import")}</Typography>
                <FormProvider {...formProps}>
                    <Stack
                        spacing={2}
                        component={"form"}
                        onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
                    >
                        <Grid container>
                            <ImportPo />
                        </Grid>
                    </Stack>
                </FormProvider>
            </CardContent>
        </Card>
    )
}

export default ImportTesting;