import React, { useState, useEffect, useMemo } from "react";
import { Grid, Card, Typography, TextField, Button, Box, MenuItem, FormControlLabel, 
  Checkbox,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions, } 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 { useNotifier } from "../../../Core/Notifier";
import CircularProgress from "@mui/material/CircularProgress";
import { CiBoxList } from "react-icons/ci";
import CancelIcon from '@mui/icons-material/Cancel';
import { useNavigate, useParams, useLocation } from 'react-router-dom';
import AddIcon from "@mui/icons-material/Add";
import IconButton from '@mui/material/IconButton';
import DeleteOutlineSharpIcon from "@mui/icons-material/DeleteOutlineSharp";
import EditSharpIcon from "@mui/icons-material/EditSharp";
import { FaTrash } from "react-icons/fa";
import { FaEdit } from "react-icons/fa";
import {
  IEmailTemplate,
} from "../../../Api/Interface/api.interface";
import {
  useGetEmailTemplateQuery,
} from "../../../Api/attoDeskApi";

const ExpenseForm = () => {
  const API_URL = process.env.REACT_APP_API_URL;
  const { projectId } = useParams();
  const location = useLocation();
  const defaultCategoryId = location.state?.defaultCategoryId || null;
  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 [expenseCategories, setExpenseCategories] = useState<ExpenseCategory[]>([]); // Type expenseCategories as an array of ExpenseCatego
  const navigate = useNavigate();
  const [subCategories, setSubCategories] = useState<ExpenseCategory[]>([]);
  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 [installmentData, setInstallmentData] = useState({
     date: new Date().toLocaleDateString("en-CA", { timeZone: "America/Toronto" }),
    amount: "",
    description: "",
  });
  const [team, setTeam] = useState<Driver[]>([]);
  const [categories, setCategories] = useState<Category[]>([]); 

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

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

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


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

}

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


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

     

  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const response = await axios.get(`${API_URL}/view-expense-category/${projectId}`); // Replace with your endpoint
        setExpenseCategories(response.data || []); // Update state with categories

      } catch (error) {
        showErrorMessage("Failed to fetch categories");
        console.error("Error fetching categories:", error);
      }
    };

       const fetchTeam = async () => {
          try {
            const response = await axios.get(`${API_URL}/view-team`);
            // setTeam(response.data.data);
            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); 
           // console.log(response.data.data);
          } catch (error) {
            console.error("Failed to load team members", error);
          }
        };
       
    fetchTeam();
    fetchCategories();
  }, []);

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

  const formik = useFormik({
    initialValues: {
      // date: new Date().toISOString().split("T")[0],
      date: new Date().toLocaleDateString('en-CA', { timeZone: 'America/Toronto' }),
      description: "",
      amount: "",
      hst: false,
      total: "",      
      category: defaultCategoryId || "",
      subCategory: "",
      type: "Other",
      installment:0,
      sendEmail: true,
      status: "Unpaid",
      file: [] as File[],
      beforeImages: [] as File[],
      afterImages: [] as File[],
      remarks:"",
    },
    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) => {
      setLoading(true);
      try {
        // Prepare the form data to be sent
        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("subCategory", values.subCategory || "");
        formData.append("type", values.type || "");
        formData.append("installment", values.installment.toString());
        formData.append("sendEmail", values.sendEmail ? "1" : "0");


        formData.append("status", values.status);
        formData.append("remarks", values.remarks);



        if (values.file && values.file.length > 0) {
          values.file.forEach((file) => {
            formData.append("files[]", file); // Use `files[]` or appropriate field name
          });
        }

        if (values.beforeImages && values.beforeImages.length > 0) {
          values.beforeImages.forEach((beforeImages) => {
            formData.append("beforeImages[]", beforeImages); // Use `files[]` or appropriate field name
          });
        }

        if (values.afterImages && values.afterImages.length > 0) {
          values.afterImages.forEach((afterImages) => {
            formData.append("afterImages[]", afterImages); // Use `files[]` or appropriate field name
          });
        }

           if (values.installment === 1 && installments.length > 0) {
      formData.append("installmentDetails", JSON.stringify(installments));
    }
        // Send the data to the Laravel backend using axios
        const response = await axios.post(`${API_URL}/save-expenses/${projectId}`, formData, {
         
          headers: {
            "Content-Type": "multipart/form-data",
          },
        });

if (values.sendEmail) {

 
  const managers = team;
    const invoiceFiles = values.file || [];
  for (const manager of managers) {
    const emailData = prepareEmailData(response.data, manager, invoiceFiles); // invoiceFiles is assumed to be selected
     if (!emailData) continue; // skip sending if no email or template

  try {
    await axios.post(`${API_URL}/send-email`, emailData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: `Bearer ${localStorage.getItem("token") || ""}`,
      },
    });
  } catch (err) {
    console.error(`Failed to send email to ${manager.driverEmail}:`, err);
  
  }
}
}

      //  console.log("Response:", response.data);
        showMessage("Expense saved successfully!");
        formik.resetForm();
        setTotal(0); 
        setIsHST(false); 
        setInstallments([]);
        setSelectedCategoryId(null); 
        setSelectedSubCategoryId(null)
      } catch (error) {
        console.error("Error saving expense:", error);
        showErrorMessage("An error occurred while saving the expense.");
            
      }finally {
        setLoading(false); // Reset loading state after the submission completes
      }
    },
  });

function prepareEmailData(expenseDetails: any, manager: Driver, invoiceFiles: File[] = []) {
    if (!manager.driverEmail) {
    console.warn(`Skipping email for ${manager.driverFirstName} ${manager.driverLastName} (no email)`);
    return null; // return nothing if no email
  }
  
  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);
  });

  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 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 handleAddInstallment = () => {
  if (installmentData.date && installmentData.amount) {
    if (editIndex !== null) {
      // Update existing row
      const updated = [...installments];
      updated[editIndex] = installmentData;
      setInstallments(updated);
    } else {
      // Add new row
      setInstallments([...installments, installmentData]);
    }

    // Reset state
    setInstallmentData({ date: "", amount: "", description: "" });
    setEditIndex(null);
    setModalOpen(false);
  }
};

  

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

const handleDeleteClick = (index: any ) => {
  const updated = installments.filter((_, i) => i !== index);
  setInstallments(updated);
};

  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}>
                  Create 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 }}>
                    {/* Date Field */}
                    <Grid item xs={12} sm={7}>
                      <Typography variant="subtitle1">Date</Typography>
                      <TextField
                        type="date"
                        size="small"
                        value={formik.values.date}
                        onChange={formik.handleChange}
                        name="date"
                        fullWidth />
                    </Grid>

                    {/* Description Field */}
                    <Grid item xs={12} sm={7}>
                      <Typography variant="subtitle1">Description</Typography>
                      <TextField
                        placeholder="Enter description"
                        size="small"
                        {...formik.getFieldProps("description")}
                        error={formik.touched.description && Boolean(formik.errors.description)}
                        helperText={formik.touched.description && formik.errors.description}
                        multiline
                        rows={4}
                        fullWidth />
                    </Grid>

                    {/* Amount Field */}
                    <Grid item xs={12} sm={7}>
                      <Typography variant="subtitle1">Amount</Typography>
                      <TextField
                        placeholder="Enter amount"
                        size="small"
                        type="number"
                        value={formik.values.amount}
                        error={formik.touched.amount && Boolean(formik.errors.amount)}
                        helperText={formik.touched.amount && formik.errors.amount}
                        onChange={(event) => handleAmountChange(event)}
                        fullWidth />
                    </Grid>

                    {/* HST Checkbox */}
                    <Grid item xs={12} sm={7}>
                      <Typography variant="subtitle1">Include HST(13%)?</Typography>
                      <Grid container alignItems="center">
                        <Grid item>
                          <FormControlLabel
                            control={<Checkbox
                              checked={isHST}
                              onChange={handleHSTToggle}
                              color="primary" />}
                            label="Yes" />
                        </Grid>
                        {isHST && (
                          <Grid item sx={{ marginLeft: 2 }}>
                            <Typography variant="body2">
                              HST = ${hstAmount.toFixed(2)}
                            </Typography>
                          </Grid>
                        )}
                      </Grid>
                    </Grid>


                    {/* Total Field */}
                    <Grid item xs={12} sm={7}>
                      <Typography variant="subtitle1">Total</Typography>
                      <TextField
                        size="small"
                        type="number"
                        value={total === 0 ? "" : total} // Hide the '0' when total is 0
                        onChange={(event) => handleTotalChange(event)} // Add this handler
                        InputProps={{
                          readOnly: false, // Allow the user to edit total
                        }}
                        fullWidth />
                    </Grid>

                    {/* Category Dropdown */}
                    <Grid item xs={12} sm={7}>
                      <Typography variant="subtitle1">Category</Typography>
                      <TextField
                        select
                        size="small"
                        value={formik.values.category} 
                        onChange={(e) => {
                          const selectedId = Number(e.target.value);
                          formik.setFieldValue("category", selectedId);
                          setSelectedCategoryId(selectedId);

                          // Filter subcategories
                          const filteredSubs = expenseCategories.filter(
                            (cat) => cat.mainCatId === selectedId
                          );
                          setSubCategories(filteredSubs);
                          setSelectedSubCategoryId(null); // reset subcategory selection
                        } }

                        error={formik.touched.category && Boolean(formik.errors.category)}
                        // helperText={formik.touched.category && formik.errors.category}
                         helperText={
    formik.touched.category && typeof formik.errors.category === "string"
      ? formik.errors.category
      : undefined
  }
                        fullWidth
                      >
                        {expenseCategories.filter((category) => category.mainCatId === null).map((category, index) => (
                          <MenuItem key={index} value={category.id}>
                            {category.category_name}
                          </MenuItem>
                        ))}
                      </TextField>
                    </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));
                                formik.setFieldValue("subCategory", 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>
                    )}
<Grid item xs={12} sm={7}>
  <Typography variant="subtitle1">Type</Typography>
  <TextField
    select
    fullWidth
    size="small"
    className={classes.textField}
    value={formik.values.type || "Other"} // Default: Other
    onChange={(e) => formik.setFieldValue("type", e.target.value)}
    InputLabelProps={{ shrink: true }}
  >
    <MenuItem value="Labour">Labour</MenuItem>
    <MenuItem value="Material">Material</MenuItem>
     <MenuItem value="Material + Labour">Material + Labour</MenuItem>
    <MenuItem value="Other">Other</MenuItem>
  </TextField>
</Grid>


                    
                    <Grid container spacing={2} mt={2} ml={2} mb={2}>
                      <Grid item xs={12} sm={4}>
                        <Typography variant="subtitle1">Installment</Typography>
                        <FormControlLabel
                          control={<Checkbox
                            checked={formik.values.installment === 1} // Check if installment is true (1)
                            onChange={(e) => formik.setFieldValue("installment", e.target.checked ? 1 : 0)} // Set 1 for checked, 0 for unchecked
                            color="primary" />}
                          label="Is Installment?" />
                      </Grid>

                      <Grid item xs={12} sm={3}>
                        <Typography variant="subtitle1">Status</Typography>
                        <FormControlLabel
                          control={<Checkbox
                            checked={formik.values.status === "Paid"} // Check if status is "Paid"
                            onChange={(e) => formik.setFieldValue("status", e.target.checked ? "Paid" : "Unpaid")} // Update Formik value based on checkbox state
                            color="primary" />}
                          label="Paid" />
                      </Grid>
                    </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 }}>
              <Typography variant="subtitle2">Installment Details</Typography>
                 <TableContainer>
              <Table size="small" className={classes.table}>
                <TableHead className={classes.tableHeaderRow}>
                  <TableRow>
                    <TableCell className={classes.tablheader}> <strong>Date</strong></TableCell>
                    <TableCell className={classes.tablheader}> <strong>Amount</strong></TableCell>
                    <TableCell className={classes.tablheader}> <strong>Description</strong></TableCell>
                      <TableCell className={classes.tablheader} align="right">Actions</TableCell>
                
                  </TableRow>
                </TableHead>
                <TableBody>
                  {installments.map((item, index) => (
                    <TableRow key={index} className={classes.tableRowHover}>
                      <TableCell className={classes.tablCell}>{item.date}</TableCell>
                      <TableCell className={classes.tablCell}>{item.amount}</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)}
                            >
                              <FaTrash style={{ fontSize: 16 }} />
                            </IconButton>
                                                   
        </Grid>
          </Grid>
        </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
</TableContainer>
   <Grid
                      item
                      lg={12}
                      md={12}
                      sm={12}
                      xs={12}
                      py={2}
                      sx={{
                        display: "flex",
                        justifyContent: "flex-end",
                      }}
                       
                    >
                     <Button
                              variant="contained"
                              className={classes.addButton}
                               onClick={() => setModalOpen(true)}
                               startIcon={<AddIcon />}
                            >
                             Installment
                            </Button>
                    </Grid>

              </Card>
            </Grid>

            </Card>
            </Grid>
            </Grid>
            
          </>
        )} */}


                    <Grid container spacing={2} mt={1} ml={2} mb={2}>
                      {/* File Upload Field */}
                      <Grid item xs={12} sm={4}>
                        <Typography variant="subtitle1">Upload Invoice</Typography>
                        <input
                          type="file"
                          multiple
                          onChange={(event) => {
                            const newFiles = event.currentTarget.files ? Array.from(event.currentTarget.files) : [];
                            const allFiles = [...formik.values.file, ...newFiles]; // Merge the new files with the already selected files
                            formik.setFieldValue("file", allFiles); // Update Formik's file field
                          } }

                          style={{ display: "none" }}
                          id="file-upload" /><Box>
                          <label htmlFor="file-upload">
                            <Button variant="outlined" component="span">
                              Choose Files
                            </Button>
                          </label>
                          {formik.values.file && formik.values.file.length > 0 && (
                            <Box sx={{ mt: 1 }}>
                              <Typography variant="body2" color="textSecondary">
                                Selected Invoice:
                              </Typography>
                              <ul>
                                {formik.values.file.map((file, index) => (
                                  <li key={index}>
                                    {file.name}
                                    {/* Remove file button */}
                                    <Button
                                      size="small"
                                      color="secondary"
                                      onClick={() => {
                                        // Remove the selected file
                                        const updatedFiles = formik.values.file.filter((_, i) => i !== index);
                                        formik.setFieldValue("file", updatedFiles); // Update Formik's file field
                                      } }
                                    >
                                      <CancelIcon sx={{ color: 'red', backgroundColor: '#f8d7da', borderRadius: '50%' }} />
                                    </Button>
                                  </li>
                                ))}
                              </ul>
                            </Box>
                          )}
                        </Box>
                      </Grid>




                      {/* Before Section */}
                      <Grid item xs={12} sm={4}>
                        <Typography variant="subtitle1">Before Image</Typography>
                        <input
                          type="file"
                          multiple
                          onChange={(event) => {
                            // Collect selected files for the "Before" section
                            const newFiles = event.currentTarget.files ? Array.from(event.currentTarget.files) : [];
                            const allFiles = [...formik.values.beforeImages, ...newFiles]; // Merge new files with already selected files
                            formik.setFieldValue("beforeImages", allFiles); // Update Formik's field for Before images
                          } }
                          style={{ display: "none" }}
                          id="before-image-upload" />
                        <Box>
                          <label htmlFor="before-image-upload">
                            <Button variant="outlined" component="span">
                              Choose Files
                            </Button>
                          </label>
                          {formik.values.beforeImages && formik.values.beforeImages.length > 0 && (
                            <Box sx={{ mt: 1 }}>
                              <Typography variant="body2" color="textSecondary">
                                Selected Before Images:
                              </Typography>
                              <ul>
                                {formik.values.beforeImages.map((file, index) => (
                                  <li key={index}>
                                    {file.name}
                                    {/* Remove button for Before images */}
                                    <Button
                                      size="small"
                                      color="secondary"
                                      onClick={() => {
                                        const updatedFiles = formik.values.beforeImages.filter((_, i) => i !== index);
                                        formik.setFieldValue("beforeImages", updatedFiles); // Update Formik's field for Before images
                                      } }
                                    >
                                      <CancelIcon
                                        sx={{
                                          color: "red",
                                          backgroundColor: "#f8d7da",
                                          borderRadius: "50%",
                                        }} />
                                    </Button>
                                  </li>
                                ))}
                              </ul>
                            </Box>
                          )}
                        </Box>
                      </Grid>

                      {/* After Section */}
                      <Grid item xs={12} sm={4}>
                        <Typography variant="subtitle1">After Image</Typography>
                        <input
                          type="file"
                          multiple
                          onChange={(event) => {
                            // Collect selected files for the "After" section
                            const newFiles = event.currentTarget.files ? Array.from(event.currentTarget.files) : [];
                            const allFiles = [...formik.values.afterImages, ...newFiles]; // Merge new files with already selected files
                            formik.setFieldValue("afterImages", allFiles); // Update Formik's field for After images
                          } }
                          style={{ display: "none" }}
                          id="after-image-upload" />
                        <Box>
                          <label htmlFor="after-image-upload">
                            <Button variant="outlined" component="span">
                              Choose Files
                            </Button>
                          </label>
                          {formik.values.afterImages && formik.values.afterImages.length > 0 && (
                            <Box sx={{ mt: 1 }}>
                              <Typography variant="body2" color="textSecondary">
                                Selected After Images:
                              </Typography>
                              <ul>
                                {formik.values.afterImages.map((file, index) => (
                                  <li key={index}>
                                    {file.name}
                                    {/* Remove button for After images */}
                                    <Button
                                      size="small"
                                      color="secondary"
                                      onClick={() => {
                                        const updatedFiles = formik.values.afterImages.filter((_, i) => i !== index);
                                        formik.setFieldValue("afterImages", updatedFiles); // Update Formik's field for After images
                                      } }
                                    >
                                      <CancelIcon
                                        sx={{
                                          color: "red",
                                          backgroundColor: "#f8d7da",
                                          borderRadius: "50%",
                                        }} />
                                    </Button>
                                  </li>
                                ))}
                              </ul>
                            </Box>
                          )}
                        </Box>
                      </Grid>

                    </Grid>

                    <Grid item xs={12} sm={7}>
                      <Typography variant="subtitle1">Remarks</Typography>
                      <TextField
                        placeholder="Enter remarks"
                        size="small"
                        {...formik.getFieldProps("remarks")}
                        multiline
                        rows={4}
                        fullWidth />
                    </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={() => 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"} {/* Show loader when submitting */}
                      </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) => setInstallmentData({ ...installmentData, amount: e.target.value })}
          />
          <TextField
            fullWidth
            margin="dense"
            label="Description"
            rows={4} 
            multiline
            value={installmentData.description}
            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></>

  );
};

export default ExpenseForm;
