"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 {
    FieldErrors,
    FormProvider,
    SubmitErrorHandler,
    SubmitHandler,
    useForm,
} from "react-hook-form";
import { Tab, Tabs, TabsProps, Typography } from "@mui/material";
import TimesheetMailDetails from "./TimesheetMailDetails";
import { Error } from "@mui/icons-material";
import { MailSave, saveMail, testEveryone, test7th, test15th, testEmail } from "@/app/api/mail/actions";
import SettingDetails from "./SettingDetails";
import { errorDialog, submitDialog, successDialog } from "../Swal/CustomAlerts";

export interface Props {
    defaultInputs?: MailSave,
}

const hasErrorsInTab = (
    tabIndex: number,
    errors: FieldErrors<MailSave>,
) => {
    switch (tabIndex) {
        case 0:
            return (
                errors.settings
            );
        case 1:
            return (
                errors.template
            );
        default:
            false;
    }
};

const MailSetting: React.FC<Props> = ({
    defaultInputs,
}) => {
    const [serverError, setServerError] = useState("");
    const { t } = useTranslation();
    const router = useRouter();
    const [tabIndex, setTabIndex] = useState(0);
    const [test, setTest] = useState(false)

    const handleTabChange = useCallback<NonNullable<TabsProps["onChange"]>>(
        (_e, newValue) => {
            setTabIndex(newValue);
        },
        [],
    );

    const formProps = useForm<MailSave>({
        defaultValues: defaultInputs
    });

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

    const onSubmit = useCallback<SubmitHandler<MailSave>>(
        async (data) => {
            try {
                console.log(data);

                let haveError = false
                // if (data.name.length === 0) {
                //     haveError = true
                //     formProps.setError("name", { message: "Name is empty", type: "required" })
                // }

                if (haveError) {
                    return false
                }


                setServerError("");

                submitDialog(async () => {
                        const response = await saveMail(data);

                        console.log(response)
                        if (response !== null) {
                            if (test) {
                                let msg = ""
                                try {
                                    // msg = "testEveryone"
                                    // await testEveryone()
                                    // msg = "test7th"
                                    // await test7th()
                                    // msg = "test15th"
                                    // await test15th()
                                    msg = "testEmail"
                                    await testEmail()
                                } catch (error) {
                                    console.log(error)
                                    console.log(msg)
                                }
                            }

                            successDialog(t("Save Success"), t)
                        } else {
                            errorDialog(t("Save Fail"), t).then(() => {
                                // formProps.setError("code", { message: response.message, type: "custom" })
                                // setTabIndex(0)
                                return false
                            })
                        }
                    }, t)
            } catch (e) {
                console.log(e)
                setServerError(t("An error has occurred. Please try again later."));
            }
        },
        [router, t, test],
    );

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

    const errors = formProps.formState.errors;

    return (
        <FormProvider {...formProps}>
            <Stack
                spacing={2}
                component="form"
                onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
            >
                {serverError && (
                    <Typography variant="body2" color="error" alignSelf="flex-end">
                        {serverError}
                    </Typography>
                )}
                <Tabs
                    value={tabIndex}
                    onChange={handleTabChange}
                    variant="scrollable"
                >
                    <Tab
                        label={t("Setting")}
                        sx={{ marginInlineEnd: hasErrorsInTab(1, errors) && !hasErrorsInTab(1, errors) ? 1 : undefined }}
                        icon={
                            hasErrorsInTab(0, errors) ? (
                                <Error sx={{ marginInlineEnd: 1 }} color="error" />
                            ) : undefined
                        }
                        iconPosition="end"
                    />
                    <Tab
                        label={t("Timesheet Template")}
                        icon={
                            hasErrorsInTab(1, errors) ? (
                                <Error sx={{ marginInlineEnd: 1 }} color="error" />
                            ) : undefined
                        }
                        iconPosition="end"
                    />
                </Tabs>
                <SettingDetails isActive={tabIndex === 0}/>
                <TimesheetMailDetails isActive={tabIndex === 1} />

                <Stack direction="row" justifyContent="flex-end" gap={1}>
                    <Button
                        variant="outlined"
                        startIcon={<Close />}
                        onClick={handleCancel}
                    >
                        {t("Cancel")}
                    </Button>
                    <Button variant="contained" startIcon={<Check />} onClick={() => setTest(true)} type="submit">
                        {t("send to everyone")}
                    </Button>
                    <Button variant="contained" startIcon={<Check />} onClick={() => setTest(false)} type="submit">
                        {t("Save")}
                    </Button>
                </Stack>
            </Stack>
        </FormProvider>
    );
};

export default MailSetting;