"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 { CreateCompanyInputs, EditCompanyInputs, saveCompany } from "@/app/api/companys/actions";
import { useRouter } from "next/navigation";
import React, { useCallback, useDebugValue, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
    FieldErrors,
    FormProvider,
    SubmitErrorHandler,
    SubmitHandler,
    useForm,
  } from "react-hook-form";
import CompanyDetails from "./CompanyDetails";
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'
import dayjs from "dayjs";
import { convertTimeArrayToString } from "@/app/utils/formatUtil";

interface Props {
    isEdit: Boolean;
    company?: EditCompanyInputs;
    companyCodes: string[];
}

const CreateCompany: React.FC<Props> = ({
    isEdit,
    company,
    companyCodes,
}) => {
    const [serverError, setServerError] = useState("");
    const { t } = useTranslation();
    const router = useRouter();

    console.log(companyCodes)

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

    const onSubmit = useCallback<SubmitHandler<CreateCompanyInputs>>(
        async (data) => {
          try {
            let haveError = false
            if (companyCodes.includes(data.companyCode.toLowerCase().trim())) {
                haveError = true
                formProps.setError("companyCode", { message: t("Duplicated Code."), type: "required" })
            }
            console.log(data);
            if (haveError) {
                return
            }
            console.log("passed")
            setServerError("");
            // console.log(JSON.stringify(data));
            await saveCompany(data)
            router.replace("/settings/company");
          } catch (e) {
            setServerError(t("An error has occurred. Please try again later."));
          }
        },
        [router, t],
    );

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

    const formProps = useForm<CreateCompanyInputs>({
        defaultValues: {
            id: company?.id,
            companyCode: company?.companyCode,
            companyName: company?.name,
            brNo: company?.brNo,
            contactName: company?.contactName,
            phone: company?.phone,
            otHourTo: "",
            otHourFrom:  "",
            normalHourTo: "",
            normalHourFrom: "",
            currency: company?.currency,
            address: company?.address,
            district: company?.district,
            email: company?.email,
        },
    });
    
    const errors = formProps.formState.errors;

    return(
        <FormProvider {...formProps}>
            <Stack
                spacing={2}
                component="form"
                onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
            >
                {
                <LocalizationProvider dateAdapter={AdapterDayjs}>
                    <CompanyDetails 
                    content={
                        {
                            normalHourFrom: company?.normalHourFrom as number[],
                            normalHourTo: company?.normalHourTo as number[],
                            otHourFrom: company?.otHourFrom as number[],
                            otHourTo: company?.otHourTo as number[]
                        }
                    }
                    />
                </LocalizationProvider>
                }

            <Stack direction="row" justifyContent="flex-end" gap={1}>
                <Button
                    variant="outlined"
                    startIcon={<Close />}
                    onClick={handleCancel}
                >
                    {t("Cancel")}
                </Button>
                <Button variant="contained" startIcon={<Check />} type="submit">
                    {t("Confirm")}
                </Button>
                </Stack>
            </Stack>    
        </FormProvider>
    )
}

export default CreateCompany;