"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 Print from '@mui/icons-material/Print';
// import { CreateInvoiceInputs, saveInvoice } from "@/app/api/companys/actions";
import { useRouter } from "next/navigation";
import React, { useCallback, useState, useLayoutEffect } from "react";
import { useTranslation } from "react-i18next";
import {
    FieldErrors,
    FormProvider,
    SubmitErrorHandler,
    SubmitHandler,
    useForm,
  } from "react-hook-form";
import { useSearchParams } from 'next/navigation'
import { InvoiceResult } from "@/app/api/invoices";
import { InvoiceInformation, fetchInvoiceInfoById, fetchProjectInvoiceById } from "@/app/api/invoices/actions";
import InvoiceDetails from "./InvoiceDetails";
import ProjectDetails from "./ProjectDetails";
import ProjectTotalFee from "./ProjectTotalFee";
import { timestampToDateString } from "@/app/utils/formatUtil";
import dayjs from "dayjs";

const CreateInvoice: React.FC = ({
}) => {
    const { t } = useTranslation();
    const searchParams = useSearchParams()
    const router = useRouter()
    
    const [projectDetail, setProjectDetail] = useState<InvoiceResult>()
    const [invoiceDetail, setInvoiceDetail] = useState<InvoiceInformation>()
    const [serverError, setServerError] = useState("");

    // const { getValues } = useForm();

    const fetchProjectDetails = async () =>{
      const projectId = searchParams.get("id")
      try{
        if (projectId !== null && parseInt(projectId) > 0) {
          const projectDetail = await fetchProjectInvoiceById(parseInt(projectId))
          // console.log(projectDetail)
          const updatedPrijectDetail = projectDetail.map(detail => {
              return { ...detail, paymentMilestoneDate: timestampToDateString(detail.paymentMilestoneDate) }; // Update the age of person with id 2
          });
          setProjectDetail(updatedPrijectDetail[0])
        }
      } catch (error){
        console.log(error)
        setServerError(t("An error has occurred. Please try again later."));
      } 
    }

    const fetchInvoiceDetails = async () =>{
      const projectId = searchParams.get("id")
      try{
        if (projectId !== null && parseInt(projectId) > 0) {
          const invoiceInfo = await fetchInvoiceInfoById(parseInt(projectId))
          console.log(invoiceInfo)
          const updatedInvoiceInfo = invoiceInfo.map(info => {
            return { ...info, 
              invoiceDate: dayjs.unix(parseFloat(info.invoiceDate)/1000).format('YYYY/MM/DD'),
              dueDate: dayjs.unix(parseFloat(info.dueDate)/1000).format('YYYY/MM/DD') 
            }; 
        });
          setInvoiceDetail(updatedInvoiceInfo[0])
        }
      } catch (error){
        console.log(error)
        setServerError(t("An error has occurred. Please try again later."));
      } 
    }

    useLayoutEffect(() => {
      fetchProjectDetails()
      fetchInvoiceDetails()
    }, [])

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

  const handlePrintout = () => {
    // const formData = getValues();
    console.log("Printing in Progress")
  }

  const onSubmit = useCallback<SubmitHandler<InvoiceResult>>(
    async (data) => {
      try {
        console.log(data);
        setServerError("");
        // console.log(JSON.stringify(data));
        // await saveCompany(data)
        // router.replace("/invoices");
      } catch (e) {
        setServerError(t("An error has occurred. Please try again later."));
      }
    },
    [router, t],
  );

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

  const formProps = useForm<InvoiceResult>({
      defaultValues: {
      },
  });

  const errors = formProps.formState.errors;

  return(
      <FormProvider {...formProps}>
          <Stack
              spacing={2}
              component="form"
              onSubmit={formProps.handleSubmit(onSubmit, onSubmitError)}
          >
          {
            projectDetail && <ProjectDetails projectDetails={projectDetail}/>
          }
          {
            invoiceDetail && <InvoiceDetails invoiceinfo={invoiceDetail}/>
          }
          {
            <ProjectTotalFee />
          }
          <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>
              <Button 
                variant="contained" 
                color="secondary"
                startIcon={<Print />} 
                onClick={handlePrintout}
              >
                  {t("Generate Print Out")}
              </Button>
          </Stack>
          </Stack>    
      </FormProvider>
  )
}

export default CreateInvoice;