import React, { useState, useEffect, useMemo } from "react";
import { Grid, Card, Typography, TextField, Button, Box, MenuItem, FormControlLabel, Checkbox ,
  Dialog,
  DialogActions, DialogContent, DialogTitle, CardContent,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow, Paper
} from "@mui/material";
import SaveAltIcon from "@mui/icons-material/SaveAlt";
import CloseIcon from "@mui/icons-material/Close";
import { useFormik } from "formik";
import * as yup from "yup";
import { useStyles } from "../../../theme/appStyles";
import axios from "axios";
import { useParams, useNavigate,useLocation  } from "react-router-dom";
import { useNotifier } from "../../../Core/Notifier";
import CircularProgress from "@mui/material/CircularProgress";
import CancelIcon from '@mui/icons-material/Cancel';
import DescriptionIcon from '@mui/icons-material/Description';
import { FaTrash } from "react-icons/fa";
import { FaEdit, FaUndo } from "react-icons/fa";
import IconButton from '@mui/material/IconButton';
import AddIcon from "@mui/icons-material/Add";
import {
  IEmailTemplate,
} from "../../../Api/Interface/api.interface";
import {
  useGetEmailTemplateQuery,
} from "../../../Api/attoDeskApi";

interface Driver {
  id: number;
  driverFirstName: string;
  driverLastName: string;
  driverEmail: string;
  driverUserRole: string;
  projectId?: number[];

}

const EditExpenseForm = () => {
  const { id } = useParams(); // Get the expense ID from the URL
  const navigate = useNavigate();
  const API_URL = process.env.REACT_APP_API_URL;
  const classes = useStyles();
  const [isHST, setIsHST] = useState(false);
  const [total, setTotal] = useState(0);
  const [hstAmount, setHstAmount] = useState(0);
  const { showErrorMessage, showMessage } = useNotifier();
  const [loading, setLoading] = useState(false); 
  const [expense, setExpense] = useState<any>(null); // State to store fetched expense data
  const [description, setDescription] = useState('');
  const [amount, setAmount] = useState(0);
  const [category, setCategory] = useState('');
  const [remarks, setRemarks] = useState('');
   const [team, setTeam] = useState<Driver[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const LARAVEL_API_URL = process.env.REACT_APP_LARAVEL_API;
  const [openModal, setOpenModal] = useState(false);
  const [fileUrl, setFileUrl] = useState<string | null>(null);
  const location = useLocation();
const projectId = location.state?.projectId;
 const [subCategories, setSubCategories] = useState<Category[]>([]);
    const [selectedSubCategoryId, setSelectedSubCategoryId] = useState<number | null>(null);
   const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [installments, setInstallments] = useState<Installment[]>([]);
    const [editIndex, setEditIndex] = useState(null);
    const [refreshTrigger, setRefreshTrigger] = useState(false);
    const [openModalView, setOpenModalView] = useState(false);

    const [beforeImages, setBeforeImages] = useState<string[]>([]);
    const [afterImages, setAfterImages] = useState<string[]>([]);
 const [installmentData, setInstallmentData] = useState({
   date: new Date().toLocaleDateString("en-CA", { timeZone: "America/Toronto" }),
    amount: "",
    paymentMode:"",
    description: "",
  });
  

  interface Category {
    id: number;
    category_name: string;
    mainCatId: number;
  }

   interface Installment  {
  date: string;
  amount: string;
  paymentMode: string;
  description: string;
};


const {
      data: emailTemplateData,
      isLoading: emailTemplateIsLoading,
      isError: emailTemplateError,
      refetch: emailTemplateRefetch,
    } = useGetEmailTemplateQuery({
      searchText: "",
      // id: "",
    });

const totalPaidAmount = installments.reduce(
  (sum, inst) => sum + Number(inst.amount),
  0
);

const totalDueAmount = Number(expense?.total ?? 0) - totalPaidAmount;


 const emailTemplateList: IEmailTemplate[] = useMemo(() => {
      if (emailTemplateData && Array.isArray(emailTemplateData.data)) {
        return emailTemplateData.data as IEmailTemplate[];
      }
      return [];
    }, [emailTemplateData]);

  const formik = useFormik({
    initialValues: {
      date: expense?.date || new Date().toISOString().split("T")[0],
      description: expense?.description || "",
      amount: expense?.amount || "",
      hst: expense?.hst || false,
      total: expense?.total || "",   
      installment: expense?.installment || "",
      installments: expense
        ?.installment_details ? JSON.parse(expense.installment_details)
      : [], 
      category: expense?.category || "",
      status: expense?.status || "",
      file: expense?.files || [], 
      before_images: expense?.before_images || [], 
      after_images: expense?.after_images || [],
      remarks: expense?.remarks || "",
      sendEmail: true,
    },
    validationSchema: yup.object({    
      date: yup.date().required("Date is required"),
      description: yup.string().required("Description is required"),
      amount: yup
        .number()
        .required("Amount is required")
        .positive("Amount must be positive"),
      category: yup.string().required("Category is required"),
    }),
    onSubmit: async (values) => {
      //console.log("Formik Values on Submit:", values); 
      setLoading(true);
      try {
        const formData = new FormData();
        formData.append("date", values.date);
        formData.append("description", values.description);
        formData.append("amount", values.amount);
        formData.append("hst", isHST ? hstAmount.toString() : "0"); 
        formData.append("total", total.toString());
        formData.append("category", values.category);
        formData.append("status", values.status);
        formData.append("installment", values.installment.toString());
        formData.append("remarks", values.remarks || ""); // Ensure it's an empty string if not provided
        formData.append("sendEmail", values.sendEmail ? "1" : "0");

        if (values.file && Array.isArray(values.file)) {
          values.file.forEach((file: File) => {
            formData.append("files[]", file);
          });
        }


        if (values.before_images && Array.isArray(values.before_images)) {
          values.before_images.forEach((before_images: File) => {
            formData.append("before_images[]", before_images); // Append each file individually
          });
        }
        
        
        if (values.after_images && Array.isArray(values.after_images)) {
          values.after_images.forEach((after_images: File) => {
            formData.append("after_images[]", after_images); // Append each file individually
          });
        }
        
           if (values.installment === 1 && installments.length > 0) {
      formData.append("installmentDetails", JSON.stringify(installments));
    }

        const response = await axios.post(`${API_URL}/expense/${id}`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        });
 
  
        if (values.sendEmail) {

          const managers = team;
         const existingFiles = expense?.files ? JSON.parse(expense.files) : [];
  const newFiles = values.file || [];

  const invoiceFiles = [...existingFiles, ...newFiles];
// console.log("Combined invoiceFiles:", invoiceFiles);

  
           
          for (const manager of managers) {
            const emailData = prepareEmailData(response.data.expense, manager, invoiceFiles); // invoiceFiles is assumed to be selected
            if (emailData) {
              await axios.post(`${API_URL}/send-email`, emailData, {
                headers: {
                  'Content-Type': 'multipart/form-data',
                   Authorization: `Bearer ${localStorage.getItem("token") || ""}`,
                },
              });
            }
          }
        }

        showMessage("Expense updated successfully!");
        navigate(`/expense/list/${projectId}`); // Redirect after update
      } catch (error) {
        showErrorMessage("An error occurred while updating the expense.");
      } finally {
        setLoading(false);
      }
    },
  });

 
  

  const fetchExpenseAndCategories = async () => {
  setLoading(true);
  try {
    // Fetch categories
    const categoriesResponse = await axios.get(`${API_URL}/view-expense-category/${projectId}`);
    const fetchedCategories = categoriesResponse.data;
    setCategories(fetchedCategories);

    // Fetch expense details
    const expenseResponse = await axios.get(`${API_URL}/expense/${id}`);
    const fetchedExpense = expenseResponse.data;

    setExpense(fetchedExpense);
    setDescription(fetchedExpense.description);
    setAmount(fetchedExpense.amount);
    setTotal(fetchedExpense.total);
    setIsHST(fetchedExpense.hst > 0);
    setHstAmount(fetchedExpense.hst);
    setCategory(fetchedExpense.category);
    setRemarks(fetchedExpense.remarks);

    const parsedFiles = fetchedExpense.file ? JSON.parse(fetchedExpense.file) : [];
    const parsedBeforeFiles = fetchedExpense.before_images ? JSON.parse(fetchedExpense.before_images) : [];
    const parsedAfterFiles = fetchedExpense.after_images ? JSON.parse(fetchedExpense.after_images) : [];
    const parsedInstallments = fetchedExpense?.installment_details
      ? JSON.parse(fetchedExpense.installment_details)
      : [];

    setInstallments(parsedInstallments);

    // Set Formik values
    formik.setValues({
      date: fetchedExpense.date,
      description: fetchedExpense.description,
      amount: fetchedExpense.amount,
      hst: fetchedExpense.hst > 0,
      total: fetchedExpense.total,
      category: fetchedExpense.category,
      installment: fetchedExpense.installment,
      status: fetchedExpense.status,
      installments: parsedInstallments,
      file: Array.isArray(parsedFiles) ? parsedFiles : [],
      before_images: Array.isArray(parsedBeforeFiles) ? parsedBeforeFiles : [],
      after_images: Array.isArray(parsedAfterFiles) ? parsedAfterFiles : [],
      remarks: fetchedExpense.remarks,
      sendEmail: true,
    });
  } catch (error) {
    showErrorMessage("Failed to fetch expense or categories data.");
  } finally {
    setLoading(false);
  }
};

const fetchTeam = async () => {
  try {
    const response = await axios.get(`${API_URL}/view-team`);
    const team: Driver[] = response.data.data;
    const managers = team.filter(driver => {
      const ids = typeof driver.projectId === "string" ? JSON.parse(driver.projectId) : driver.projectId;
      return driver.driverUserRole === "manager" && Array.isArray(ids) && ids.includes(parseInt(projectId || "0"));
    });
    setTeam(managers);
  } catch (error) {
    console.error("Failed to load team members", error);
  }
};

// Then inside useEffect
useEffect(() => {
  if (id) {
    fetchExpenseAndCategories();
    fetchTeam();
  }
}, [id]);
  
// async
 function prepareEmailData(expenseDetails: any, manager: Driver, invoiceFiles: File[] = []) {
  const ExpenseTemplate = emailTemplateList.find(item => item.template_name === 'Expense');

  if (!ExpenseTemplate) return null;

  const message = convertPlainTextToHTML(ExpenseTemplate.message)
    .replace('[customer_name]', `${manager.driverFirstName } ${manager.driverLastName}`)
    .replace('[category_name]', categoryMap[expenseDetails.category] || "Unknown" )
    .replace('[payment_amount]',  Number(expenseDetails.total).toFixed(2));

  const formData = new FormData();
  formData.append("to", manager.driverEmail);
  formData.append("subject", ExpenseTemplate.subject);
  formData.append("message", message);

  // Attach each invoice file
  invoiceFiles.forEach((file, index) => {
 formData.append("attachments[]", file);
  });
// async function urlToFile(url: string): Promise<File> {
//     const response = await fetch(url, { mode: 'cors' });
//     const blob = await response.blob();
//     const filename = url.split('/').pop() || 'attachment.jpg';
//     return new File([blob], filename, { type: blob.type });
//   }

//   // Convert URLs to Files and append
//   for (const fileUrl of invoiceFiles) {
//     try {
//       const fullUrl = `${LARAVEL_API_URL}/${fileUrl}`;
//       const file = await urlToFile(fullUrl);
//       formData.append("attachments[]", file);
//     } catch (error) {
//       console.error("Failed to fetch and convert file:", fileUrl, error);
//       // Optionally skip or handle error
//     }
//   }



  return formData;
}



 const convertPlainTextToHTML= (text: string) => {
    return text
      .replace(/\n/g, '<br>') // Replace line breaks with <br>
      .replace(/ {2,}/g, match => '&nbsp;'.repeat(match.length)); // Replace multiple spaces with &nbsp;
  }
 

    const categoryMap = useMemo(
      () =>
        categories.reduce((map, category) => {
          map[category.id] = category.category_name;
          return map;
        }, {} as Record<number, string>),
      [categories]
    );

 const handleAmountChange = (
     event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
   ) => {
     const inputValue = event.target.value; // Raw input value
     const amount = inputValue ? parseFloat(inputValue) : 0; // Default to 0 if empty
   
     formik.setFieldValue("amount", inputValue); // Update formik directly with raw value for better UX
   
     if (isHST) {
       const hstAmount = amount * 0.13; // Calculate HST
       const updatedTotal = amount + hstAmount; // Calculate total
       setHstAmount(hstAmount);
       setTotal(parseFloat(updatedTotal.toFixed(2)));
       formik.setFieldValue("total", updatedTotal.toFixed(2)); // Update total
     } else {
       setHstAmount(0); // Reset HST
       setTotal(amount); // Total equals amount
       formik.setFieldValue("total", amount.toFixed(2)); // Update total
     }
   };
   
   const handleHSTToggle = (event: React.ChangeEvent<HTMLInputElement>) => {
     const checked = event.target.checked;
     setIsHST(checked);
   
     // Parse the current values from Formik (default to 0 if empty)
     const currentAmount = parseFloat(formik.values.amount || "0");
     const currentTotal = parseFloat(formik.values.total || "0");
   
     if (checked) {
       // HST is checked
       if (currentTotal > 0 && currentAmount === 0) {
         // Case 2: User entered total (which includes HST), calculate base amount and HST
         const baseAmount = parseFloat((currentTotal / 1.13).toFixed(2)); // Calculate and round base amount
         const calculatedHST = parseFloat((currentTotal - baseAmount).toFixed(2)); // Calculate and r
  
         setHstAmount(calculatedHST); // Set the calculated HST
         setTotal(parseFloat(currentTotal.toFixed(2)));// Keep total as entered
         console.log(parseFloat(currentTotal.toFixed(2)))
         formik.setFieldValue("amount", baseAmount.toFixed(2)); // Update the amount in the form
       } else if (currentAmount > 0) {
      
         // Case 1: User entered amount, calculate HST and total from amount
         const calculatedHST = parseFloat((currentAmount * 0.13).toFixed(2)); // Calculate and round HST
         const updatedTotal = parseFloat((currentAmount + calculatedHST).toFixed(2)); // Calculate and round total
   
         setHstAmount(calculatedHST);
         setTotal(updatedTotal);
      
         formik.setFieldValue("total", updatedTotal.toFixed(2)); // Update total based on amount
       }
     } else {
       // HST is unchecked
       if (currentTotal > 0) {
         // If total is entered, recalculate the base amount from total (remove HST)
         const baseAmount = currentTotal / 1.13; // Calculate the base amount before HST
   
         setHstAmount(0); // Reset HST to 0
         const roundedBaseAmount = parseFloat(baseAmount.toFixed(2)); // Round base amount to 2 decimal places
         setTotal(roundedBaseAmount); // Set total back to the base amount (without HST)
      
         formik.setFieldValue("total", roundedBaseAmount.toFixed(2)); // Update total in the form
         formik.setFieldValue("amount", roundedBaseAmount.toFixed(2)); // Ensure amount matches the recalculated base amount
       } else if (currentAmount > 0) {
         // If only amount is entered, reset HST to 0 and set total to the amount
         setHstAmount(0); // Reset HST to 0
         setTotal(currentAmount); // Set total to amount
         formik.setFieldValue("total", currentAmount.toFixed(2)); // Set total in the form
       
       }
     }
   };
   
   
   
   
   const handleTotalChange = (
     event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
   ) => {
     const inputValue = event.target.value; // Raw input value
     const total = inputValue ? parseFloat(inputValue) : 0; // Default to 0 if empty
   
     formik.setFieldValue("total", inputValue); // Update Formik directly with raw value
   
     if (isHST) {
       // When HST is checked, calculate base amount and HST
       const baseAmount = total / 1.13; // Calculate the base amount before HST
       const hstAmount = total - baseAmount; // Calculate HST
       setHstAmount(hstAmount);
       setTotal(total); // Keep total as entered
       formik.setFieldValue("amount", baseAmount.toFixed(2)); // Update amount
     } else {
       // When HST is unchecked, total equals the amount (no HST)
       setHstAmount(0); // Reset HST
       setTotal(total); // Total equals input total
       //formik.setFieldValue("amount", total.toFixed(2)); // Update amount
       formik.setFieldValue("amount", 0); // Update amount
 
     }
   };

   
  const handleOpenModal = (file: string): void => {
    //const url = `${LARAVEL_API_URL}/${file}`;
    setFileUrl(file);
    setOpenModal(true);
   
  };

  const handleCloseModal = () => {
    setOpenModal(false);
    setFileUrl(null);
  };


  const handleAddInstallment = async () => {
  if (installmentData.date && installmentData.amount) {
    let updatedInstallments = [];

    if (editIndex !== null) {
      updatedInstallments = [...installments];
      updatedInstallments[editIndex] = installmentData;
    } else {
      updatedInstallments = [...installments, installmentData];
    }

    try {
      await axios.post(`${API_URL}/expense-installment/${id}`, {
        installmentDetails: JSON.stringify(updatedInstallments),
      }, {
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      });

      showMessage("Installment details saved successfully!");
     fetchExpenseAndCategories();

      // Update local state after API success
      //setInstallments(updatedInstallments);
      setInstallments([]);
      setInstallmentData({ date: new Date().toLocaleDateString("en-CA", { timeZone: "America/Toronto" }), amount: "", paymentMode:"", description: "" });
      setEditIndex(null);
      setModalOpen(false);

    } catch (error) {
      console.error("Error updating installment details", error);
      showErrorMessage("Failed to update installments.");
    }
  }
};


  const handleEditClick = (index: any) => {
  setInstallmentData(installments[index]);
  setEditIndex(index);
  setModalOpen(true);
};

const handleDeleteClick = (index: any ) => {
  const updated = installments.filter((_, i) => i !== index);
  setInstallments(updated);
   axios.post(`${API_URL}/expense-installment/${expense.id}`, {
      installmentDetails: JSON.stringify(updated),
    }, {
      headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
    })
    .then(() => {
      showMessage("Installment reversal successful!");
 fetchExpenseAndCategories();
    })
    .catch(() => {
      showErrorMessage("Failed to reverse installment.");
    });
  }

  const handleViewImages = (beforeImagesData: string[], afterImagesData: string[]) => {

  setBeforeImages(beforeImagesData || []);
  setAfterImages(afterImagesData || []);
  setOpenModalView(true);
};


  // if (loading)
  //     return (
  //       <Box
  //         display="flex"
  //         justifyContent="center"
  //         alignItems="center"
  //         height="10vh"
  //       >
  //         <CircularProgress />
  //       </Box>
  //     );
  


  return (
    <><div>
      <Grid container spacing={3}>
        <Grid item xs={12} md={3}>
          <Card>
            <Grid container justifyContent="space-between" sx={{ borderBottom: 2, padding: 2 }}>
              <Grid item xs={12} pt={2} alignContent={"center"}>
                <Typography className={classes.cardTitle}>Installment Expense</Typography>
              </Grid>
            </Grid>
          </Card>
        </Grid>

        <Grid item xs={12} md={9}>
          <form onSubmit={formik.handleSubmit}>
            <Grid container>
              <Grid item xs={12}>
                <Card>
                  <Grid container spacing={3} sx={{ padding: 3 }}>


   <Grid item xs={12} md={6}>
          {/* Date */}
          <Box display="flex" gap={1} mb={2}>
            <Typography variant="subtitle1">Date:</Typography>
            <Typography variant="body2" color="text.secondary">
              {formik.values.date || "-"}
            </Typography>
          </Box>

          {/* Description */}
          <Box display="flex" gap={1} mb={2}>
            <Typography variant="subtitle1">Description:</Typography>
            <Typography variant="body2" color="text.secondary">
              {formik.values.description || "-"}
            </Typography>
          </Box>

          {/* Category */}
          <Box display="flex" gap={1} mb={2}>
            <Typography variant="subtitle1">Category:</Typography>
            <Typography variant="body2" color="text.secondary">
            {categories.find((cat) => cat.id === Number(formik.values.category))?.category_name || "-"}

            </Typography>
          </Box>
         {/* remarks */}
         {formik.values.remarks  && 
          <Box display="flex" gap={1} mb={2}>
            <Typography variant="subtitle1">Remarks:</Typography>
            <Typography variant="body2" color="text.secondary">
              {formik.values.remarks || "-"}
            </Typography>
          </Box>
}
        </Grid>

        {/* Right side */}
        <Grid item xs={12} md={6}>
          {/* Total */}
          <Box display="flex" gap={1} mb={2}>
            <Typography variant="subtitle1">Total Amount:</Typography>
            <Typography variant="body2" color="text.secondary">
              {total || 0}
            </Typography>
          </Box>

          {/* Paid */}
          <Box display="flex" gap={1} mb={2}>
            <Typography variant="subtitle1">Paid Amount:</Typography>
            <Typography variant="body2" color="text.secondary">
              {totalPaidAmount.toFixed(2) || 0}
            </Typography>
          </Box>
        </Grid>
                   


                  
                    {/* {selectedCategoryId && subCategories.length > 0 && (
                      <Grid item xs={12} sm={5}>
                        <Typography variant="subtitle1">Sub Category</Typography>
                        <TextField
                          select
                          fullWidth
                          size="small"
                          className={classes.textField}
                          value={selectedSubCategoryId || ""}
                          onChange={(e) => setSelectedSubCategoryId(Number(e.target.value))}
                          InputLabelProps={{ shrink: true }}
                        >
                          <MenuItem value="" disabled>
                            Select a subcategory
                          </MenuItem>
                          {subCategories.map((sub) => (
                            <MenuItem key={sub.id} value={sub.id}>
                              {sub.category_name}
                            </MenuItem>
                          ))}
                        </TextField>
                      </Grid>
                    )} */}


                

                   {formik.values.installment == 1 && (
                      <>
                       <Grid container spacing={4}  >
                           <Grid item xs={12} sm={12} md={12}>
                           <Card className={classes.card}>


                       <Grid item lg={12} md={12} sm={12} xs={12}>
                                          <Card sx={{ padding: 3 }}>
                        <Box
      display="flex"
      justifyContent="space-between"
      alignItems="center"
      mb={2}
    >
      <Typography variant="h5">Installment Details</Typography>
      <Button
        variant="contained"
        className={classes.addButton}
        onClick={() => setModalOpen(true)}
        startIcon={<AddIcon />}
      >
        Pay
      </Button>
    </Box>
                                             
                            <TableContainer>
                          <Table size="small" className={classes.table}>
                            <TableHead className={classes.tableHeaderRow}>
                              <TableRow>
                                <TableCell className={classes.tablheader}>Date</TableCell>
                                <TableCell className={classes.tablheader}>Amount</TableCell>
                                <TableCell className={classes.tablheader}>Due Amount</TableCell> 
                                <TableCell className={classes.tablheader}>Mode</TableCell>
                                <TableCell className={classes.tablheader}>Description</TableCell>
                                 <TableCell className={classes.tablheader} align="right">Actions</TableCell>
                              </TableRow>
                            </TableHead>
                            <TableBody>
                              {installments.length > 0 ? (  
                              installments.map((item, index) =>   {
                                   const paidAmount = installments
          .slice(0, index + 1)
          .reduce((sum, inst) => sum + Number(inst.amount), 0);

        // Calculate due amount
        const dueAmount = Number(expense.total) - paidAmount;

        // Check if fully paid
        const isFullyPaid = dueAmount <= 0;
                                return(
                              
                                <TableRow key={index}>
                                  <TableCell className={classes.tablCell}>{item.date}</TableCell>
                                  <TableCell className={classes.tablCell}>{item.amount}</TableCell>
                                  <TableCell className={classes.tablCell}>{dueAmount}</TableCell>
                                   <TableCell className={classes.tablCell}>{item.paymentMode || "-"}</TableCell>
                                  <TableCell className={classes.tablCell}>{item.description || "-"}</TableCell>
                               <TableCell scope="row" className={classes.tablCell}>
                                         <Grid
                                           container
                                           spacing={1}
                                           sx={{ display: "flex", justifyContent: "flex-end" }}
                                         >
                     {/* <Grid item>
                         <IconButton
                                                    color="primary"
                                                onClick={() => handleEditClick(index)}
                                                  >
                                                    <FaEdit  style={{ fontSize: 18 }}/>
                                                  </IconButton>
                     
                                                                              </Grid> */}
                                                                              <Grid item>
                                                                                 <IconButton
                              color="primary"
                              onClick={() => handleDeleteClick(index)}
                            >
                              <FaUndo style={{ fontSize: 16 }} />
                            </IconButton>
                                                   
        </Grid>
          </Grid>
        </TableCell>
                                </TableRow>
                             );
      })
    
     ) : (
    <TableRow>
      <TableCell colSpan={6} align="center">
        No data available
      </TableCell>
    </TableRow>
  )}
                            </TableBody>
                          </Table>
                          </TableContainer>
                          
                                                </Card>
                                                          </Grid>
                                                          </Card>
                                                          </Grid>
                        </Grid>
                      </>
                    )} 

<Grid container spacing={2} ml={1} justifyContent="center">
      {[ // array of your 5 cards
      
        { title: 'Total Amount', value: total, prefix: '$', suffix: '' },
        { title: 'Paid Amount', value: totalPaidAmount.toFixed(2), prefix: '$', suffix: '' },
        { title: 'Due Amount', value: totalDueAmount.toFixed(2), prefix: '$', suffix: '' },
      ].map((item, index) => (

        <Grid item xs={12} sm={6} md={4} key={index}>
          <Card elevation={3}>


            <CardContent>
              <Grid container direction="column" alignItems="center">
                <Typography variant="h5" mt={2}>{item.title}</Typography>
                <Typography
                  variant="h3"
                  sx={{ marginTop: 2, fontWeight: "bold", color: "#4CAF50" }}
                >
                  {item.prefix}{item.value}{item.suffix}
                </Typography>
              </Grid>
            </CardContent>
          </Card>
        </Grid>
      ))}
    </Grid>


             <Grid container spacing={4} mt={2} ml={1}>
  <Grid item xs={12} sm={12} md={12}>
    {(formik.values.file?.length > 0 ||
      formik.values.before_images?.length > 0 ||
      formik.values.after_images?.length > 0) && (
      <Card className={classes.card}>
        <Grid item lg={12} md={12} sm={12} xs={12}>
          <Box
            display="flex"
            justifyContent="space-between"
            alignItems="center"
            mt={2}
          >
            <Typography variant="h5">Uploads</Typography>
          </Box>

          <TableContainer component={Paper} sx={{ mt: 2 }}>
            <Table className={classes.table}>
              <TableHead className={classes.tableHeaderRow}>
                <TableRow>
                  <TableCell
                    className={classes.tablheader}
                    sx={{ fontWeight: "bold", width: "30%" }}
                  >
                    Title
                  </TableCell>
                  <TableCell
                    className={classes.tablheader}
                    sx={{ fontWeight: "bold" }}
                  >
                    Files
                  </TableCell>
                </TableRow>
              </TableHead>

              <TableBody>
                {/* Uploaded Invoice */}
                {formik.values.file?.length > 0 && (
                  <TableRow >
                    <TableCell className={classes.tablCell}>
                      <Typography variant="subtitle1">
                         Invoice
                      </Typography>
                    </TableCell>
                    <TableCell className={classes.tablCell}>
                      <ul style={{ paddingLeft: 0, margin: 0 }}>
                        {formik.values.file.map((file: File, index: number) => {
                          const fileUrl =
                            file instanceof File
                              ? URL.createObjectURL(file)
                              : `${LARAVEL_API_URL}/${file}`;
                          return (
                            <li
                              key={index}
                              style={{
                                display: "inline-flex",
                                alignItems: "center",
                                // marginRight: 15,
                                listStyle: "none",
                              }}
                            >
                              <Button
                                variant="text"
                                size="small"
                                onClick={() => handleOpenModal(fileUrl)}
                                sx={{
                                  minWidth: "auto",
                                  padding: 0,
                                  marginRight: 1,
                                }}
                              >
                                <DescriptionIcon style={{ fontSize: 20 }} />
                              </Button>
                              {/* <span>{`Invoice ${index + 1}`}</span> */}
                            </li>
                          );
                        })}
                      </ul>
                    </TableCell>
                  </TableRow>
                )}

                {/* Before Images */}
                {formik.values.before_images?.length > 0 && (
                  <TableRow>
                    <TableCell className={classes.tablCell}>
                      <Typography variant="subtitle1">
                        Before  & After Images
                      </Typography>
                    </TableCell>
                    <TableCell className={classes.tablCell}>
                      <ul style={{ paddingLeft: 0, margin: 0 }}>





                            <Grid item>


                              {(
                                (Array.isArray(expense.before_images) && expense.before_images.length > 0) ||
                                (Array.isArray(expense.after_images) && expense.after_images.length > 0) ||
                                (expense.before_images && typeof expense.before_images === 'string' && JSON.parse(expense.before_images).length > 0) ||
                                (expense.after_images && typeof expense.after_images === 'string' && JSON.parse(expense.after_images).length > 0)
                              ) && (
                                  <Button
                                    variant="text"
                                    size="small"
                                     sx={{
                                    minWidth: "auto",
                                    padding: 0,
                                    marginRight: 1,
                                  }}
                                    onClick={() => {
                                      // Ensure before_images is properly parsed and wrapped in an array if necessary
                                      let beforeImages = Array.isArray(expense.before_images)
                                        ? expense.before_images
                                        : expense.before_images
                                          ? JSON.parse(expense.before_images) // Parse if it's a stringified array
                                          : []; // Default to empty array if undefined or not valid

                                      let afterImages = Array.isArray(expense.after_images)
                                        ? expense.after_images
                                        : expense.after_images
                                          ? JSON.parse(expense.after_images) // Parse if it's a stringified array
                                          : []; // D



                                      //console.log("After Images:", afterImages);  // Log the parsed before images array
                                      // Handle the images by calling handleViewImages
                                      handleViewImages(beforeImages, afterImages);
                                    } }

                                  >
                                     <DescriptionIcon style={{ fontSize: 20 }} />
                                  </Button>
                                )}



                            </Grid>





                        {/* {formik.values.before_images.map(
                          (before_images: File, index: number) => {
                            const fileUrl =
                              before_images instanceof File
                                ? URL.createObjectURL(before_images)
                                : `${LARAVEL_API_URL}/${before_images}`;
                            return (
                              <li
                                key={index}
                                style={{
                                  display: "inline-flex",
                                  alignItems: "center",
                                  marginRight: 15,
                                  listStyle: "none",
                                }}
                              >
                                <Button
                                  variant="text"
                                  size="small"
                                  onClick={() => handleOpenModal(fileUrl)}
                                  sx={{
                                    minWidth: "auto",
                                    padding: 0,
                                    marginRight: 1,
                                  }}
                                >
                                  <DescriptionIcon style={{ fontSize: 20 }} />
                                </Button>
                            <span>{`BeforeImage ${index + 1}`}</span> 
                              </li>
                            );
                          }
                        )} */}
                      </ul>
                    </TableCell>
                  </TableRow>
                )}

                {/* After Images */}
                {/* {formik.values.after_images?.length > 0 && (
                  <TableRow className={classes.tableRowHover}>
                    <TableCell className={classes.tablCell}>
                      <Typography variant="subtitle1">
                        After Images
                      </Typography>
                    </TableCell>
                    <TableCell className={classes.tablCell}>
                      <ul style={{ paddingLeft: 0, margin: 0 }}>
                        {formik.values.after_images.map(
                          (after_images: File, index: number) => {
                            const fileUrl =
                              after_images instanceof File
                                ? URL.createObjectURL(after_images)
                                : `${LARAVEL_API_URL}/${after_images}`;
                            return (
                              <li
                                key={index}
                                style={{
                                  display: "inline-flex",
                                  alignItems: "center",
                                  marginRight: 15,
                                  listStyle: "none",
                                }}
                              >
                                <Button
                                  variant="text"
                                  size="small"
                                  onClick={() => handleOpenModal(fileUrl)}
                                  sx={{
                                    minWidth: "auto",
                                    padding: 0,
                                    marginRight: 1,
                                  }}
                                >
                                  <DescriptionIcon style={{ fontSize: 20 }} />
                                </Button>
                                 <span>{`AfterImage ${index + 1}`}</span> 
                              </li>
                            );
                          }
                        )}
                      </ul>
                    </TableCell>
                  </TableRow>
                )} */}
              </TableBody>
            </Table>
          </TableContainer>
        </Grid>
      </Card>
    )}
  </Grid>
</Grid>

                  

 {/* <Grid item xs={12} sm={7}>
                         
                      <FormControlLabel
  control={
    <Checkbox
      name="sendEmail"
      color="primary"
      checked={formik.values.sendEmail}
      onChange={formik.handleChange}
    />
  }
  label="Send Email Notification"
/>

</Grid> */}

                  </Grid>
                </Card>
              </Grid>

              {/* Submit and Cancel Buttons */}
              <Grid item xs={12} pt={3}>
                <Card>
                  <Grid container spacing={3} sx={{ padding: 3 }}>
                    <Grid item xs={12} sx={{ display: "flex", justifyContent: "flex-end" }}>
                      <Button
                        variant="outlined"
                        className={classes.addButton}
                        startIcon={<CloseIcon />}
                        // onClick={() => formik.resetForm()}
                        onClick={() => navigate(`/expense/list/${projectId}`)}
                      >
                        Cancel
                      </Button>
                      <Box m={0.5}></Box>
                      {/* <Button
                        variant="contained"
                        className={classes.addButton}
                        startIcon={<SaveAltIcon />}
                        type="submit"
                        disabled={loading}
                      >
                        {loading ? <CircularProgress size={24} /> : "Submit"}
                      </Button> */}
                    </Grid>
                  </Grid>
                </Card>
              </Grid>
            </Grid>
          </form>
        </Grid>
      </Grid>
    </div><Dialog open={modalOpen} onClose={() => setModalOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>Add Installment</DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            margin="dense"
            label="Date"
            type="date"
            InputLabelProps={{ shrink: true }}
            value={installmentData.date}
            onChange={(e) => setInstallmentData({ ...installmentData, date: e.target.value })} />
          <TextField
            fullWidth
            margin="dense"
            label="Amount"
            type="number"
            value={installmentData.amount}
            onChange={(e) => {
    const val = e.target.value;
    const enteredAmount = parseFloat(val);
    if (isNaN(enteredAmount) || enteredAmount < 0) {
      setInstallmentData({ ...installmentData, amount: val });
      return;
    }

   let existingInstallments: Installment[] = [];

try {
  if (expense) {
    if (typeof expense.installment_details === 'string') {
      existingInstallments = JSON.parse(expense.installment_details) as Installment[];
    } else if (Array.isArray(expense.installment_details)) {
      existingInstallments = expense.installment_details;
    } else {
      existingInstallments = [];
    }
  }
} catch {
  existingInstallments = [];
}


    // Calculate sum of other installments, excluding the one being edited
    const sumOtherInstallments = existingInstallments.reduce(
      (acc: number, inst: Installment, idx: number) => {
        if (editIndex !== null && idx === editIndex) return acc; // exclude current edited
        return acc + parseFloat(inst.amount?.toString() || "0");
      }, 0
    );

    const totalAmount = parseFloat(expense?.total?.toString() || "0");
    const remaining = totalAmount - sumOtherInstallments;

    if (enteredAmount > remaining) {
      // alert(`Amount cannot exceed remaining balance $${remaining.toFixed(2)}`);
          showErrorMessage(`Amount cannot exceed remaining balance $${remaining.toFixed(2)}`);
      return;
    }

    setInstallmentData({ ...installmentData, amount: val });

  }}/>
          <TextField
      select
      fullWidth
      margin="dense"
      label="Payment Mode"
      value={installmentData.paymentMode || ""}
      onChange={(e) => setInstallmentData({ ...installmentData, paymentMode: e.target.value })}
    >
     <MenuItem value="">Select option</MenuItem>
              <MenuItem value="Cash">Cash</MenuItem>
              <MenuItem value="Credit">Credit</MenuItem>
              <MenuItem value="Debit">Debit</MenuItem>
              <MenuItem value="E-Transfer">E-Transfer</MenuItem>
              <MenuItem value="Online banking">Online banking</MenuItem>
              <MenuItem value="Pre authorization">Pre authorization</MenuItem>
              <MenuItem value="Bank deposit">Bank deposit</MenuItem>
    </TextField>
          <TextField
            fullWidth
            margin="dense"
            label="Description"
            value={installmentData.description}
             multiline
             rows={4}
            onChange={(e) => setInstallmentData({ ...installmentData, description: e.target.value })} />
        </DialogContent>
     <DialogActions sx={{ paddingRight: "24px", p: 3, py: 3, gap: 2 }}>
          
                  <Grid container spacing={3}>
                   <Grid
                                      item
                                      lg={12}
                                      md={12}
                                      sm={12}
                                      xs={12}
                                      sx={{ display: "flex", justifyContent: "flex-end" }}
                                    >
          <Button   className={classes.addButton}  variant="outlined"   startIcon={<CloseIcon />} onClick={() => setModalOpen(false)}>Cancel</Button>
            <Box m={0.5}></Box>
          <Button  className={classes.addButton} variant="contained"    startIcon={<SaveAltIcon />} onClick={handleAddInstallment}>
            Save
          </Button>
          </Grid>
          </Grid>
         
        </DialogActions>
      </Dialog>
      
      
      
      
          <Dialog open={openModal} onClose={handleCloseModal} fullWidth maxWidth="md">
                              <DialogTitle>View File</DialogTitle>
                              <DialogContent>
                                {fileUrl?.endsWith('.pdf') ? (
                                  <iframe
                                    src={fileUrl || ''}
                                    style={{
                                      width: '100%',
                                      height: '500px',
                                    }}
                                    title="PDF Viewer" />
                                ) : (
                                  <img
                                    src={fileUrl || ''}
                                    alt="File Content"
                                    style={{
                                      width: '100%',
                                      height: '500px',
                                      objectFit: 'contain', // Ensures the image fits within the available space
                                    }} />
                                )}
                              </DialogContent>
                              <DialogActions>
                                <Button onClick={handleCloseModal} color="primary">Close</Button>
                              </DialogActions>
                            </Dialog>
      
      
      
      <Dialog open={openModalView} onClose={() => setOpenModalView(false)} maxWidth="lg" fullWidth>
        <DialogTitle >
          View Images
          
          <IconButton
            edge="end"
            color="inherit"
            onClick={() => setOpenModalView(false)}
            aria-label="close"
            sx={{ position: 'absolute', right: 20, top: 8 }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
      
        <DialogContent>
        <Box display="flex" flexDirection={{ xs: 'column', md: 'row' }} gap={2}>
            {/* Left side for Before Images */}
            <Box flex={1} marginRight={{ md: 2 }}>
              <h3>Before Images</h3>
              {beforeImages.length > 0 ? (
                <Box display="flex" flexDirection="column" gap={2}>
                  {beforeImages.map((before_image, index) => {
                      const imageUrl = `${LARAVEL_API_URL}/${before_image}`;
                      //console.log(`Image URL: ${imageUrl}`);  // Log the image URL
                      return (
                        <Box key={index} padding={1} borderRadius={4}>
                    
      
      {imageUrl.endsWith('.pdf') ? (
                <iframe
                src={imageUrl || ''} 
                  style={{
                    width: '100%',
                    height: '500px',
                  }}
                  title="PDF Viewer"
                />
              ) : (
                <img
                 src={imageUrl  || ''}
                  alt="File Content"
                  style={{
                    width: '100%',
                    height: 'auto', // Adjust height dynamically based on image aspect ratio
                    maxHeight: '500px',
                    objectFit: 'contain', // Ensures the image fits within the available space
                  }}
                />
              )}
      
                      </Box>
                      );
      })}
                </Box>
              ) : (
                <p>No before images available.</p>
              )}
            </Box>
      
            {/* Right side for After Images */}
            <Box flex={1} marginLeft={{ md: 2 }}>
              <h3>After Images</h3>
              {afterImages.length > 0 ? (
                <Box display="flex" flexDirection="column" gap={2}>
                  {afterImages.map((after_image, index) => {
                      const imageUrl = `${LARAVEL_API_URL}/${after_image}`;
                      //console.log(`Image After URL: ${imageUrl}`);  // Log the image URL
                      return (
                        <Box key={index} padding={1} borderRadius={4}>
                   
      {imageUrl.endsWith('.pdf') ? (
                <iframe
                src={imageUrl || ''} 
                  style={{
                    width: '100%',
                    height: '500px',
                  }}
                  title="PDF Viewer"
                />
              ) : (
                <img
                 src={imageUrl  || ''}
                  alt="File Content"
                  style={{
                    width: '100%',
                    height: 'auto', // Adjust height dynamically based on content
                    maxHeight: '500px', 
                    objectFit: 'contain', // Ensures the image fits within the available space
                  }}
                />
              )}
      
                      </Box>
                      );
      })}
                </Box>
              ) : (
                <p>No after images available.</p>
              )}
            </Box>
          </Box>
        </DialogContent>
      </Dialog>
      
      
      
      
      
      </>
  );
};

export default EditExpenseForm;
