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, useFormContext } from 'react-hook-form';
import { Check, Close } from "@mui/icons-material";
import InvoiceTable from './InvoiceTable';
import { ProjectResult } from '@/app/api/projects';
import { createInvoices, InvoiceType, NewInvoice, PostInvoiceData } from '@/app/api/invoices/actions';
import dayjs from 'dayjs';
import { INPUT_DATE_FORMAT } from '@/app/utils/formatUtil';
import { invoiceList } from '@/app/api/invoices';
import { submitDialog, successDialog } from '../Swal/CustomAlerts';
import { useRouter } from 'next/navigation';

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

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',
};

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

  const onSubmit = useCallback<SubmitHandler<InvoiceType>>(
    async ( data ) => {
      const _data = data.data
      // console.log(_data)
      if(_data.some(data => data._error !== undefined)){
        // console.log(data)
        return
      }
      // const postData: PostInvoiceData = _data.map(item => ({
      const postData: any = _data.map(item => ({
        invoiceNo: item.invoiceNo || '',
        // projectId: projects.find(p => p.code === item.projectCode)!.id,
        projectCode: item.projectCode || '',
        issuedAmount: item.issuedAmount || 0,
        issuedDate: dayjs(item.issuedDate).format(INPUT_DATE_FORMAT),
        receiptDate: item.receiptDate ? dayjs(item.receiptDate).format(INPUT_DATE_FORMAT) : null,
        receivedAmount: item.receivedAmount  || null,
      }))
      // console.log(postData)
      submitDialog(async () => {
        const response = await createInvoices(postData)
        // console.log(response)
        if (response === "OK") {
            onClose()
            successDialog(t("Submit Success"), t).then(() => {
                // router.replace("/invoice");
            })
        }
    }, t)
      
    }
  , [])

  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,
                }}
              >
                <InvoiceTable projects={projects} invoices={invoices}/>
              </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 CreateInvoiceModal;