"use client"
import { JoDetail } from "@/app/api/jo"
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import useUploadContext from "../UploadProvider/useUploadContext";
import { FormProvider, SubmitErrorHandler, SubmitHandler, useForm } from "react-hook-form";
import { useCallback, useState } from "react";
import { Button, Stack, Typography } from "@mui/material";
import StartIcon from "@mui/icons-material/Start";
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import { releaseJo } from "@/app/api/jo/actions";
import InfoCard from "./InfoCard";
import PickTable from "./PickTable";

type Props = {
    id?: number;
    defaultValues: Partial<JoDetail> | undefined;
}

const JoSave: React.FC<Props> = ({
    defaultValues,
    id,
}) => {
    const { t } = useTranslation("jo")
    const router = useRouter();
    const { setIsUploading } = useUploadContext();
    const [serverError, setServerError] = useState("");

    const formProps = useForm<JoDetail>({
        defaultValues: defaultValues
    })

    const handleBack = useCallback(() => {
        router.replace(`/jo`)
    }, [])

    const handleRelease = useCallback(async () => {
        try {
            setIsUploading(true)
            if (id) {
                console.log(id)
                const response = await releaseJo({ id: id })
                console.log(response.entity.status)
                if (response) {
                    formProps.setValue("status", response.entity.status)
                    console.log(formProps.watch("status"))
                }
            }

        } catch (e) {
            // backend error
            setServerError(t("An error has occurred. Please try again later."));
            console.log(e);
        } finally {
            setIsUploading(false)
        }
    }, [])

    const onSubmit = useCallback<SubmitHandler<JoDetail>>(async (data, event) => {
        console.log(data)
    }, [t])

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

    return <>
        <FormProvider {...formProps}>
            <Stack
                spacing={2}
                component="form"
                onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
            >
                {serverError && (
                    <Typography variant="body2" color="error" alignSelf="flex-end">
                        {serverError}
                    </Typography>
                )}
                {
                    formProps.watch("status").toLowerCase() === "planning" && (
                        <Stack direction="row" justifyContent="flex-start" gap={1}>
                            <Button
                                variant="outlined"
                                startIcon={<StartIcon />}
                                onClick={handleRelease}
                            >
                                {t("Release")}
                            </Button>
                        </Stack>
                    )}
                <InfoCard />
                <PickTable />
                <Stack direction="row" justifyContent="flex-end" gap={1}>
                    <Button
                        variant="outlined"
                        startIcon={<ArrowBackIcon />}
                        onClick={handleBack}
                    >
                        {t("Back")}
                    </Button>
                </Stack>
            </Stack>
        </FormProvider>
    </>
}

export default JoSave;