"use client";

import type { DoDetail as DoDetailType } from "@/app/api/do/actions";
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 ArrowBackIcon from '@mui/icons-material/ArrowBack';
import StartIcon from "@mui/icons-material/Start";
import { releaseDo } from "@/app/api/do/actions";
import DoInfoCard from "./DoInfoCard";
import DoLineTable from "./DoLineTable";

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

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

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

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

    const handleRelease = useCallback(async () => {
        try {
            setIsUploading(true)
            if (id) {
                console.log(id)
                const response = await releaseDo({ 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)
        }
    }, [id, formProps, t, setIsUploading])

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

    const onSubmitError = useCallback<SubmitErrorHandler<DoDetailType>>((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() === "pending" && (
                        <Stack direction="row" justifyContent="flex-start" gap={1}>
                            <Button
                                variant="outlined"
                                startIcon={<StartIcon />}
                                onClick={handleRelease}
                            >
                                {t("Release")}
                            </Button>
                        </Stack>
                    )}
                <DoInfoCard />
                <DoLineTable />
                <Stack direction="row" justifyContent="flex-end" gap={1}>
                    <Button
                        variant="outlined"
                        startIcon={<ArrowBackIcon />}
                        onClick={handleBack}
                    >
                        {t("Back")}
                    </Button>
                </Stack>
            </Stack>
        </FormProvider>
    </>
}

export default DoDetail;