"use client";

import Check from "@mui/icons-material/Check";
import Close from "@mui/icons-material/Close";
import Button from "@mui/material/Button";
import Stack from "@mui/material/Stack";
import { useRouter } from "next/navigation";
import React, { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import ClaimFormInfo from "./ClaimFormInfo";
import { ProjectCombo } from "@/app/api/claims";
import { Typography } from "@mui/material";
import { FormProvider, SubmitErrorHandler, SubmitHandler, useForm } from "react-hook-form";
import { ClaimInputFormByStaff, saveClaim } from "@/app/api/claims/actions";
import { DoneAll } from "@mui/icons-material";
import { expenseTypeCombo } from "@/app/utils/comboUtil";
import { convertDateToString } from "@/app/utils/formatUtil";
import { errorDialog, submitDialog, successDialog, warningDialog } from "../Swal/CustomAlerts";

export interface Props {
    projectCombo: ProjectCombo[]
}

const ClaimDetail: React.FC<Props> = ({ projectCombo }) => {
    const { t } = useTranslation("common");
    const [serverError, setServerError] = useState("");
    const router = useRouter();

    const formProps = useForm<ClaimInputFormByStaff>({
        defaultValues: {
            id: null,
            expenseType: expenseTypeCombo[0],
            addClaimDetails: []
        },
    });

    const handleCancel = () => {
        router.back();
    };

    const onSubmit = useCallback<SubmitHandler<ClaimInputFormByStaff>>(
        async (data, event) => {
            try {
                if (data.isGridEditing) {
                    warningDialog(t("Please save all the rows before submitting"), t)
                    return false
                }

                let haveError = false
                if (data.addClaimDetails.length === 0 || data.addClaimDetails.filter(row => String(row.description).trim().length === 0 || String(row.amount).trim().length === 0 || row.project === null || row.project === undefined || ((row.oldSupportingDocument === null || row.oldSupportingDocument === undefined) && (row.newSupportingDocument === null || row.newSupportingDocument === undefined))).length > 0) {
                    haveError = true
                    formProps.setError("addClaimDetails", { message: "Claim details include empty fields", type: "required" })
                }

                if (data.addClaimDetails.length > 0 && data.addClaimDetails.filter(row => row.invoiceDate.getTime() > new Date().getTime()).length > 0) {
                    haveError = true
                    formProps.setError("addClaimDetails", { message: "Claim details include invalid invoice date", type: "invalid_date" })
                }

                if (data.addClaimDetails.length > 0 && data.addClaimDetails.filter(row => row.project === null || row.project === undefined).length > 0) {
                    haveError = true
                    formProps.setError("addClaimDetails", { message: "Claim details include empty project", type: "invalid_project" })
                }
                
                if (data.addClaimDetails.length > 0 && data.addClaimDetails.filter(row => row.amount <= 0).length > 0) {
                    haveError = true
                    formProps.setError("addClaimDetails", { message: "Claim details include invalid amount", type: "invalid_amount" })
                }

                if (haveError) {
                    return false
                }

                const buttonName = (event?.nativeEvent as any).submitter.name
                const formData = new FormData()
                formData.append("expenseType", data.expenseType)
                data.addClaimDetails.forEach((claimDetail) => {
                    console.log(claimDetail)
                    formData.append("addClaimDetailIds", JSON.stringify(claimDetail.id))
                    formData.append("addClaimDetailInvoiceDates", convertDateToString(claimDetail.invoiceDate, "YYYY-MM-DD"))
                    formData.append("addClaimDetailProjectIds", JSON.stringify(claimDetail.project))
                    formData.append("addClaimDetailDescriptions", claimDetail.description)
                    formData.append("addClaimDetailAmounts", JSON.stringify(claimDetail.amount))
                    formData.append("addClaimDetailNewSupportingDocuments", claimDetail.newSupportingDocument)
                    formData.append("addClaimDetailOldSupportingDocumentIds", JSON.stringify(claimDetail?.oldSupportingDocument?.id ?? -1))
                })
                // for (let i = 0; i < data.addClaimDetails.length; i++) {
                //     const updatedData = {
                //         id: data.addClaimDetails[i].id,
                //         // project: data.addClaimDetails[i].project,
                //         invoiceDate: convertDateToString(data.addClaimDetails[i].invoiceDate, "YYYY-MM-DD"),
                //         description: data.addClaimDetails[i].description,
                //         amount:data.addClaimDetails[i].amount,
                //         // oldSupportingDocument: data.addClaimDetails[i].oldSupportingDocument,
                //     }
                //     formData.append("addClaimDetails", JSON.stringify(updatedData))
                //     formData.append("addClaimDetailsFiles", data.addClaimDetails[i].newSupportingDocument)
                //     formData.append("testFiles", data.addClaimDetails[i].newSupportingDocument)
                // }
                if (buttonName === "submit") {
                    formData.append("status", "Waiting for Approval")
                } else if (buttonName === "save") {
                    formData.append("status", "Not Submitted")
                }
                formData.append("id", "-1")

                setServerError("");

                submitDialog(async () => {
                    const response = await saveClaim(formData);

                    if (response.message === "Success") {
                        successDialog(t("Submit Success"), t).then(() => {
                            router.replace("/staffReimbursement");
                        })
                    }
                }, t)
            } catch (e) {
                setServerError(t("An error has occurred. Please try again later."));
            }
        },
        [router, t],
    );

    const onSubmitError = useCallback<SubmitErrorHandler<ClaimInputFormByStaff>>(
        (errors) => {
            // Set the tab so that the focus will go there
            console.log(errors)
        },
        [],
    );

    return (
        <FormProvider {...formProps}>
            <Stack spacing={2} component={"form"} onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}>
                <ClaimFormInfo projectCombo={projectCombo} />
                {serverError && (
                    <Typography variant="body2" color="error" alignSelf="flex-end">
                        {serverError}
                    </Typography>
                )}
                <Stack direction="row" justifyContent="flex-end" gap={1}>
                    <Button variant="text" startIcon={<Close />} onClick={handleCancel}>
                        {t("Cancel")}
                    </Button>
                    <Button variant="outlined" name="save" startIcon={<Check />} type="submit" disabled={Boolean(formProps.watch("isGridEditing"))}>
                        {t("Save")}
                    </Button>
                    <Button variant="contained" name="submit" startIcon={<DoneAll />} type="submit" disabled={Boolean(formProps.watch("isGridEditing"))}>
                        {t("Submit")}
                    </Button>
                </Stack>
            </Stack>
        </FormProvider>
    );
};

export default ClaimDetail;
