"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, useEffect } 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";
import { getSession } from "next-auth/react"
import { BASE_API_URL } from "@/config/api";

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 [accessToken, setAccessToken] = useState('');

    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()
    }, [])

    // useEffect(() => {
    //   const fetchData = async () => {
    //     try {
    //       const session = await getSession();
          
    //       if (session?.accessToken) {
    //         const accessToken = session.accessToken;
    //         // Use the access token as needed
    //         setAccessToken(accessToken)
    //         console.log(accessToken);
    //       } else {
    //         throw new Error('Access token not found in the session.');
    //       }
    //     } catch (error) {
    //       console.error(error);
    //     }
    //   };
  
    //   fetchData();
    // }, []);


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

  
  const handlePrintout = async () => {
    const formData = formProps.getValues()
    const projectId = searchParams.get("id")
    // console.log(formData, projectId)
    const tempData = {
      ...formData, 
      id: projectId
    }
      try {
        // Make an API request to generate the JasperReport
        
        const response = await fetch(`https://tsms-uat.2fi-solutions.com/back-api/invoices/pdf`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${accessToken}`,
            Accept: "application/json"
          },
          
          body: JSON.stringify(tempData),
        });
    
        // Check if the request was successful
        if (response.ok) {
          // Extract the filename from the response headers
          const contentDisposition = response.headers.get("Content-Disposition");
          // response.headers.forEach(e => console.log(e))
          const fileName = contentDisposition
            ? contentDisposition.split('filename=')[1]
            : 'invoice.pdf';
    
          // Convert the response data to a Blob object
          const blob = await response.blob();
    
          // Create a temporary URL for the Blob object
          const url = URL.createObjectURL(blob);
    
          // Create a link element to trigger the file download
          const link = document.createElement('a');
          link.href = url;
          link.download = fileName.replace(/"/g, '');
          link.click();
    
          // Clean up the temporary URL
          URL.revokeObjectURL(url);
        } else {
          throw new Error('Failed to generate the JasperReport.');
        }
      } catch (error) {
        console.error(error);
        // Handle any errors that occurred during the process
      }
  }

  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;