import React, { useCallback, useState } from "react";
import {
  Modal,
  Box,
  Typography,
  Button,
  SxProps,
  CardContent,
  CardActions,
  Card,
} from "@mui/material";
import { useTranslation } from "react-i18next";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import { Check, Close } from "@mui/icons-material";
import { ProjectResult } from "@/app/api/projects";
import {
  CreateNewExpense,
  PostExpenseData,
  saveProjectExpense,
} from "@/app/api/projectExpenses/actions";
import ExpenseTable from "./ExpenseTable";
import dayjs from "dayjs";
import { INPUT_DATE_FORMAT } from "@/app/utils/formatUtil";
import { submitDialog, successDialog } from "../Swal/CustomAlerts";
import { useRouter } from 'next/navigation';
import { ProjectExpensesResultFormatted } from "@/app/api/projectExpenses";

interface Props {
  isOpen: boolean;
  onClose: () => void;
  projects: ProjectResult[];
}

const modalSx: SxProps = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  width: { xs: "calc(100% - 2rem)", sm: "90%" },
  maxHeight: "90%",
  maxWidth: 1400,
  bgcolor: "background.paper",
};



type postData = {
  data: (PostExpenseData & { _error: any })[];
} 

const CreateExpenseModal: React.FC<Props> = ({ isOpen, onClose, projects }) => {
  const { t } = useTranslation();
  const formProps = useForm<postData>();
  const router = useRouter();

  const onSubmit = useCallback<SubmitHandler<postData>>((data) => {
    const _data = data.data;
    // console.log(_data.some(data => data._error))
    if(_data.some(data => data._error)){
      return
    }
    try {
      const postData: PostExpenseData[] = _data.map((item) => {
        return {
          expenseNo: item.expenseNo,
          issueDate: item.issueDate ? dayjs(item.issueDate).format(INPUT_DATE_FORMAT) : null,
          amount: item.amount,
          projectId: projects.find((p) => p.code === item.projectCode)!.id,
          projectCode: item.projectCode,
          remarks:
            item.remarks && item.remarks.length > 0 ? item.remarks : undefined,
        };
      });
      // console.log(postData);
      submitDialog(async () => {
        const response = await saveProjectExpense(postData)
        console.log(response)
        if (response) {
            onClose()
            successDialog(t("Submit Success"), t).then(() => {
                window.location.reload()
            })
        }
    }, t)
      
    } catch (error) {
      console.log(error);
    }
  }, []);

  return (
    <FormProvider {...formProps}>
      <Modal open={isOpen} onClose={onClose}>
        <Card sx={modalSx}>
          <CardContent
            component="form"
            onSubmit={formProps.handleSubmit(onSubmit)}
          >
            <Typography variant="overline" display="block" marginBlockEnd={1}>
              {t("Invoice Creation")}
            </Typography>
            <Box
              sx={{
                display: "flex",
                justifyContent: "center",
                marginBlock: 2,
              }}
            >
              <ExpenseTable projects={projects} />
            </Box>
            <CardActions sx={{ justifyContent: "flex-end" }}>
              <Button
                variant="outlined"
                startIcon={<Close />}
                onClick={onClose}
              >
                {t("Cancel")}
              </Button>
              <Button variant="contained" startIcon={<Check />} type="submit">
                {t("Save")}
              </Button>
            </CardActions>
          </CardContent>
        </Card>
      </Modal>
    </FormProvider>
  );
};

export default CreateExpenseModal;
