import React, { useEffect, useMemo, useRef, useState} from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableFooter,
  TableHead,
  TableRow,
  CircularProgress,
  Grid,
  Box,
  Button,
  Typography,
  TextField,
  MenuItem,
  InputAdornment,
  Card,
  Dialog, useTheme, useMediaQuery,
  DialogActions, DialogContent, DialogTitle, CardContent,Paper, Stack, Chip, Divider
} from "@mui/material";
import { FaMoneyBillWave, FaPlusCircle ,FaFileAlt, FaClipboardList , FaChartPie , FaCog , FaMoneyCheckAlt, FaLayerGroup , FaChartBar } from 'react-icons/fa'; // Example icons

import { useNotifier } from "../../../Core/Notifier";
import { useStyles } from "../../../theme/appStyles";
import { useNavigate, useParams, Link } from "react-router-dom";
import { CiSearch } from "react-icons/ci";
import DeleteOutlineSharpIcon from "@mui/icons-material/DeleteOutlineSharp";
import EditSharpIcon from "@mui/icons-material/EditSharp";
import PaymentIcon from '@mui/icons-material/Payment';
import Pagination from "../../../Components/Pagination";
import axios from "axios";
import Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';
import AttachFileIcon from '@mui/icons-material/AttachFile';
import DescriptionIcon from '@mui/icons-material/Description';
import { Pie } from 'react-chartjs-2';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import CancelIcon from '@mui/icons-material/Cancel';
import CommentIcon from '@mui/icons-material/Comment';
import { Tooltip as MuiTooltip } from '@mui/material';
import InfoIcon from '@mui/icons-material/Info';  
import VisibilitySharpIcon from "@mui/icons-material/VisibilitySharp";
import LoopIcon from '@mui/icons-material/Loop';           // Circular arrow, used for Before
import LoopOutlinedIcon from '@mui/icons-material/LoopOutlined'; // Outlined circular arrow, used for After
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';
import SaveAltIcon from "@mui/icons-material/SaveAlt";
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ExpandLessIcon from '@mui/icons-material/ExpandLess';
import Collapse from '@mui/material/Collapse';
import { FaTrash } from "react-icons/fa";
import { FaEdit, FaUndo } from "react-icons/fa";
import LinkIcon from "@mui/icons-material/Link";
import PrintIcon from "@mui/icons-material/Print";
import VisibilityIcon from "@mui/icons-material/Visibility";
import FileDownloadIcon from "@mui/icons-material/FileDownload";
import * as XLSX from "xlsx";
import ReactToPrint from "react-to-print";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import PictureAsPdfRoundedIcon from '@mui/icons-material/PictureAsPdfRounded';
import TableChartIcon from "@mui/icons-material/TableChart";
import GridOnIcon from "@mui/icons-material/GridOn";

ChartJS.register(ArcElement, Tooltip, Legend);

interface Expense {
  id: number;
  date: string;
  description: string;
  remarks: string;
  amount: number;
  hst: number;
  category: number;
  status: number;
  type: string;
  total: number;
  installment: number;
  installment_details: Installment[];
  file?: string;
  created_at: string;
  before_images?: string;
  after_images?: string;
  return_amount?: number;
return_date?: string;
return_reason?: string;
is_returned?: boolean;
}

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

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

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

interface Deposit {
  id: number;
  amount: string;
  user_id: number;
  created_at: string;
  date: string;
  is_approved: boolean; 
  remarks: string;
}

interface UserInfo {
  id: number;
  username: string;
  token: string;
  user_id: number;
}

interface Group {
  id: number;
  project_id: number;
  group_name: string;
  category_ids: number[];
}

interface IncomeSource {
  id: number;
  name: string;
  description: string;
  is_active: boolean;
  sort_order: number;
}

interface PropertyIncome {
  id: number;
  property_id: number;
  income_source_id: number;
  income_source?: IncomeSource;
  tenant_id?: number;
  booking_id?: string;
  owner_id?: number;
  amount: number;
  income_date: string;
  payment_method: string;
  reference_number?: string;
  description?: string;
  attachment?: string;
  status: "created" | "verified" | "cancelled";
  created_by: number;
  created_at: string;
}

const Index = () => {
  const classes = useStyles();
  const navigate = useNavigate();
  const { projectId } = useParams();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const [expenses, setExpenses] = useState<Expense[]>([]); 
  const [groups, setGroups] = useState<Group[]>([]); 
  const [categories, setCategories] = useState<Category[]>([]); 
  const [team, setTeam] = useState<Driver[]>([]); 
  const [deposit, setDeposit] = useState<Deposit[]>([]); 
  const { showErrorMessage, showMessage } = useNotifier();
  const API_URL = process.env.REACT_APP_API_URL;
  const [searchQuery, setSearchQuery] = useState(""); 
  const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(50);
const LARAVEL_API_URL = process.env.REACT_APP_LARAVEL_API;
const [openModal, setOpenModal] = useState(false);
const [openModalView, setOpenModalView] = useState(false);
const [fileUrl, setFileUrl] = useState<string | null>(null);
const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
const [tooltipOpen, setTooltipOpen] = React.useState<Record<number, boolean>>({});
const [showImages, setShowImages] = useState(false);
const [beforeImages, setBeforeImages] = useState<string[]>([]);
const [afterImages, setAfterImages] = useState<string[]>([]);
const isPdf = fileUrl?.endsWith('.pdf');
const [modalOpen, setModalOpen] = useState(false);
const [editIndex, setEditIndex] = useState(null);
  const [installments, setInstallments] = useState<Installment[]>([]);
const [installmentData, setInstallmentData] = useState({
     date: new Date().toLocaleDateString("en-CA", { timeZone: "America/Toronto" }),
    amount: "",
    paymentMode:"",
    description: "",
  });

const [selectedExpense, setSelectedExpense] = useState<Expense | null>(null);
const [expandedExpenseId, setExpandedExpenseId] = useState<number | null>(null);
const groupPrintRef = useRef<HTMLDivElement>(null);
const [selectedGroup, setSelectedGroup] = useState<any>(null);
const [openPrint, setOpenPrint] = useState(false);
const [returnModalOpen, setReturnModalOpen] = useState(false);
const [returnData, setReturnData] = useState({
  date: new Date().toLocaleDateString("en-CA", { timeZone: "America/Toronto" }),
  amount: "",
  reason: "",
});
const [incomeSources, setIncomeSources] = useState<IncomeSource[]>([]);


const [zoom, setZoom] = useState(1);

const handleZoomIn = () => setZoom((prev) => Math.min(prev + 0.2, 5)); // max 5x
const handleZoomOut = () => setZoom((prev) => Math.max(prev - 0.2, 0.2)); // min 0.2x
const handleResetZoom = () => setZoom(1);
const [incomes, setIncomes] = useState<PropertyIncome[]>([]);

const handleViewImages = (beforeImagesData: string[], afterImagesData: string[]) => {
 // console.log("Before Images Data:", beforeImagesData);  // This should now show the images
  setBeforeImages(beforeImagesData || []);
  setAfterImages(afterImagesData || []);
  setOpenModalView(true);
};


const fetchIncomeSources = async () => {
  try {
    const res = await axios.get(`${API_URL}/income-sources`, {
      headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
    });
    setIncomeSources(res.data);
  } catch (error) {
    console.error("Failed to load income sources", error);
  }
};

const handleTooltipOpen = (id: number) => {
  if (window.innerWidth > 768) {
    setTooltipOpen((prev) => ({ ...prev, [id]: true })); // Open tooltip on hover for desktop
  }
};

const handleTooltipClose = (id: number) => {
  if (window.innerWidth > 768) {
    setTooltipOpen((prev) => ({ ...prev, [id]: false })); // Close tooltip on hover leave for desktop
  }
};

// Handle touch on mobile
const handleMobileTooltipToggle = (id: number) => {
  if (window.innerWidth <= 768) {
    setTooltipOpen((prev) => ({
      ...prev,
      [id]: !prev[id], // Toggle the open state for the specific tooltip
    })); // Toggle open/close on tap for mobile
  }
};

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

  const filteredExpenses = expenses.filter(
    (expense) =>
      expense.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
    (categoryMap[expense.category] || "")
    .toLowerCase()
    .includes(searchQuery.toLowerCase())
);

// ---------------------------------------------------------------------
// NOTE ON THE CALCULATIONS BELOW
//
// `return_amount` is recorded against an expense's `total` (amount + hst
// combined) — see handleReturnClick / handleReturnExpense, which validate
// the return against `expense.total`. To keep the "Amount" and "HST"
// columns (and every other total derived from them) consistent with the
// grand total, a return is split proportionally between the amount and
// hst portions of that expense using `getReturnSplit` below, instead of
// being subtracted from a single field. A single `netTotal` helper is
// also used everywhere "total expense" is calculated (overall totals,
// group totals, category totals, category HST, paid/bank-balance totals)
// so all of these numbers reconcile with each other and with the
// itemized table.
// ---------------------------------------------------------------------

// Splits an expense's return_amount proportionally across its amount/hst
// portions, since return_amount is recorded against the combined total.
const getReturnSplit = (expense: Expense) => {
  const amt = Number(expense.amount) || 0;
  const hst = Number(expense.hst) || 0;
  const total = amt + hst;
  const returned = Number(expense.return_amount) || 0;

  if (total <= 0 || returned <= 0) {
    return { returnedAmountPortion: 0, returnedHstPortion: 0 };
  }

  const returnedAmountPortion = returned * (amt / total);
  const returnedHstPortion = returned * (hst / total);

  return { returnedAmountPortion, returnedHstPortion };
};

// Net total for a single expense = total minus whatever has been returned.
const netTotal = (expense: Expense) => {
  const total = Number(expense.total) || 0;
  const returned = Number(expense.return_amount) || 0;
  return total - returned;
};

const totalHst = filteredExpenses.filter(expense => expense.installment !== 1).reduce((sum, expense) =>  {
  const { returnedHstPortion } = getReturnSplit(expense);
  return sum + (Number(expense.hst) || 0) - returnedHstPortion;
}, 0);

const totalAmount = filteredExpenses.filter(expense => expense.installment !== 1).reduce((sum, expense) => {
  const { returnedAmountPortion } = getReturnSplit(expense);
  return sum + (Number(expense.amount) || 0) - returnedAmountPortion;
}, 0);

const totalAmountWithTax = filteredExpenses.filter(expense => expense.installment !== 1).reduce((sum, expense) => {
  return sum + netTotal(expense);
}, 0);



  const handleEditClick = (id: number) => {
 navigate(`/expense/${id}`, {
  state: { projectId },
});

  };

 const handleInstallmentEditClick = (expense: any, index: any) => {
  setSelectedExpense(expense);

  let installmentsArray = [];
  try {
    installmentsArray = expense.installment_details ? JSON.parse(expense.installment_details) : [];
  } catch {
    installmentsArray = [];
  }

  setInstallments(installmentsArray);

  if (installmentsArray.length > index) {
    setInstallmentData(installmentsArray[index]);
    setEditIndex(index);
    setModalOpen(true);
  } else {
    console.warn("Invalid installment index for selected expense");
  }
};

const handleInstallmentDeleteClick = (expense: any, index: any) => {
    if (window.confirm("Are you sure you want to reverse this installment?")) {
  setSelectedExpense(expense);

  let installmentsArray = [];
  try {
    installmentsArray = expense.installment_details ? JSON.parse(expense.installment_details) : [];
  } catch {
    installmentsArray = [];
  }

  const updated = installmentsArray.filter((_: any, i: any) => i !== index);

  setInstallments(updated);

  // Call backend immediately or after user confirms deletion
  axios.post(`${API_URL}/expense-installment/${expense.id}`, {
    installmentDetails: JSON.stringify(updated),
  }, {
    headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
  })
  .then(() => {
    showMessage("Installment reversal successful!");
    fetchExpenses();
  })
  .catch(() => {
    showErrorMessage("Failed to reverse installment.");
  });
}
};



  const handleDeleteClick = (id: number) => {
    // Delete expense logic
    axios.delete(`${API_URL}/delete-expense/${id}`).then(() => {
      setExpenses(expenses.filter((expense) => expense.id !== id));
      showMessage("Deleted successfully");
    }).catch((error) => {
     // console.error("Failed to delete expense", error);
      showErrorMessage("Failed to delete the template");
    });
  };

  
  const fetchExpenses = async () => {
      try {
       
        const response = await axios.get(`${API_URL}/view-expenses/${projectId}`);
        setExpenses(response.data); // Set the fetched data to state
   // console.log(response.data)
      if (selectedExpense) {
      const updatedExpense = response.data.find((exp: any) => exp.id === selectedExpense.id);
      if (updatedExpense) {
        setSelectedExpense(updatedExpense);
        // Also update installments based on the updated expense
        let updatedInstallments = [];
        try {
          updatedInstallments = updatedExpense.installment_details
            ? JSON.parse(updatedExpense.installment_details)
            : [];
        } catch {
          updatedInstallments = [];
        }
        setInstallments(updatedInstallments);
      }
    }
  } catch (error) {
    console.error("Failed to load expenses", error);
  }
};

const fetchGroups = async () => {
  try {
    const response = await axios.get(`${API_URL}/view-expense-group/${projectId}`);

    const groupsData = response.data.map((group: any) => ({
      ...group,
      category_ids:
        typeof group.category_ids === "string"
          ? JSON.parse(group.category_ids)
          : group.category_ids || []
    }));

    setGroups(groupsData);

  } catch (error) {
    console.error("Failed to load groups", error);
  }
};
    const fetchCategories = async () => {
      try {
        const response = await axios.get(`${API_URL}/view-expense-category/${projectId}`);
        setCategories(response.data);
        //console.log(response.data);
      } catch (error) {
        console.error("Failed to load 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);
      }
    };

    const fetchDeposit = async () => {
      try {
        const response = await axios.get(`${API_URL}/view-deposit/${projectId}`);
        setDeposit(response.data); // Set the fetched data to state
        // console.log(response.data);
      } catch (error) {
        console.error("Failed to load expenses", error);
      }
    };

    const fetchUserInfo = async () => {
      try {
          const response = await axios.post(
              `${API_URL}/user/userInfo`,
              {}, // No body required
              {
                  headers: {
                      'Content-Type': 'application/json',
                      Authorization: `Bearer ${localStorage.getItem('token') || ''}`, // Include token from localStorage
                  },
              }
          );
          setUserInfo(response.data.data); // Update your state with the response
        // console.log(response.data.data)
      } catch (error) {
          console.error('Error fetching user info', error);
      }
  };
  useEffect(() => {
  

    fetchExpenses();
    fetchCategories();
    fetchTeam();
    fetchDeposit();
    fetchUserInfo();
    fetchGroups();
    fetchIncomes();
    fetchIncomeSources();
  }, [API_URL, projectId]);

  
const incomeSourceMap = useMemo(
  () =>
    incomeSources.reduce((map, source) => {
      map[source.id] = source.name;
      return map;
    }, {} as Record<number, string>),
  [incomeSources]
);

const incomeBySource = useMemo(() => {
  const map: Record<string, number> = {};
  incomes
    .filter((i) => i.status !== "cancelled")
    .forEach((i) => {
      const name = incomeSourceMap[i.income_source_id] || "Unknown";
      map[name] = (map[name] || 0) + Number(i.amount);
    });
  return map;
}, [incomes, incomeSourceMap]);

 
  const handleChangePage = (event: unknown, newPage: number) => {
    setPage(newPage);
  };
  
  const generateYearlyData = (expenses: Expense[]) => {
    const yearlyData = Array(12).fill(0); // Array to store expenses for each month (12 months)
  
    expenses.forEach((expense) => {
      const expenseDate = new Date(expense.date);
      const month = expenseDate.getMonth(); // Get month (0-11)
      
      // Ensure expense.total is a number
      let totalExpense = netTotal(expense);
      
      if (typeof totalExpense === 'string') {
        totalExpense = parseFloat(totalExpense); // Convert string to number
      }
    
      // Check if totalExpense is a valid number
      if (!isNaN(totalExpense)) {
        yearlyData[month] += totalExpense; // Aggregate expense by month
      } else {
        console.error("Invalid total expense:", expense.total); // Log invalid total
      }
    });
  
    // Ensure that no NaN values are in yearlyData
    const validYearlyData = yearlyData.map((value) => (isNaN(value) ? 0 :  parseFloat(value.toFixed(2)))); // Replace NaN with 0
  
//    console.log(validYearlyData); // Check the data
    return validYearlyData;
  };
  
  
  const generateCategoryData = (expenses: Expense[], categories: Category[]) => {
    const categoryTotals: Record<string, number> = {};

    // Map category ID to category name
    const categoryMap = categories.reduce((acc, category) => {
      acc[category.id] = category.category_name;
      return acc;
    }, {} as Record<number, string>);

    expenses.forEach((expense) => {
      let totalExpense = netTotal(expense);

      // Ensure totalExpense is a number
      if (typeof totalExpense === 'string') {
        totalExpense = parseFloat(totalExpense); // Convert string to number
      }

      // Get the category name using the category ID
      const categoryName = categoryMap[expense.category];

      if (categoryName) {
        //console.log(`Processing Category: ${categoryName}, Total Expense: ${totalExpense}`);

        // Check if totalExpense is a valid number
        if (!isNaN(totalExpense)) {
          if (!categoryTotals[categoryName]) {
            categoryTotals[categoryName] = 0;
          }
          categoryTotals[categoryName] += totalExpense; // Aggregate by category name
        } else {
          console.error("Invalid category total:", expense.total);
        }
      } else {
        console.error("Invalid category ID:", expense.category);
      }
    });

    // Ensure that no NaN values are in categoryTotals
    const validCategoryTotals = Object.fromEntries(
      Object.entries(categoryTotals).map(([key, value]) => [key, isNaN(value) ? 0 :  parseFloat(value.toFixed(2))])
    );

    //console.log('Final Category Totals:', validCategoryTotals);
    return validCategoryTotals;
  };
  
  

  
  
  const categoryData = generateCategoryData(expenses, categories);
  const yearlyData = generateYearlyData(expenses);


const calculateGroupTotal = (group: any) => {
  return expenses
    .filter((expense) => group.category_ids.includes(Number(expense.category)))
    .reduce((sum, expense) => sum + netTotal(expense), 0);
};


  const handleAddProductClick = () => {
    navigate(`/expense/create/${projectId}`);
  };

  const handleAddCategoryClick = () => {
    navigate(`/expense-category/list/${projectId}`);
  };
    const handleAddGroupClick = () => {
    navigate(`/expense-group/list/${projectId}`);
  };
  
  const chartData = [
    { name: "Total HST", y: totalHst },
    { name: "Total Amount (Without hst)", y: totalAmount },
    // { name: "Total Amount (with hst)", y: totalAmountWithTax }
  ];
  
  // Highcharts options
  const chartOptions = {
    chart: {
      plotBackgroundColor: null,
      plotBorderWidth: null,
      plotShadow: false,
      type: "pie",
      height: 350,
      width: 250,
    },
    title: {
      text: " ",
      align: "left",
    },
    tooltip: {
      pointFormat: "{series.name}: <b>{point.percentage:.1f}%</b>",
    },
    accessibility: {
      point: {
        valueSuffix: "%",
      },
    },
    plotOptions: {
      pie: {
        allowPointSelect: true,
        cursor: "pointer",
        dataLabels: {
          enabled: false,
        },
        showInLegend: true,
        innerSize: "40%",
      },
    },
    legend: {
      layout: "horizontal",
      align: "center",
      verticalAlign: "top",
      symbolRadius: 0,
      itemStyle: {
        fontWeight: "normal",
      },
    },
    credits: {
      enabled: false,
    },
    series: [
      {
        name: 'Expenses',
        colorByPoint: true,
        data: chartData, // Data for the three totals
      },
    ],
  };

  const parseFiles = (file: string | undefined): string[] => {
    try {
      return file ? JSON.parse(file) : [];
    } catch (error) {
      return [];
    }
  };
  // Function to handle opening the modal
  const handleOpenModal = (file: string): void => {
    const url = `${LARAVEL_API_URL}/${file}`;
    setFileUrl(url);
    setOpenModal(true);
  };

  // Function to handle closing the modal
  const handleCloseModal = () => {
    setOpenModal(false);
    setFileUrl(null);
  };

    const handlePay = (expense: any) => {
   setSelectedExpense(expense);
    setModalOpen(true);
  };

  const handleCloseModalView = () => {
    setOpenModalView(false);
   // setFileUrl(null);
  };

  const handleDepositClick = (id: any) => {
    // console.log(`${id} Deposit Clicked`);
   // navigate("/deposit/create");
    navigate(`/deposit/create/${projectId}`, { state: { userId: id } });
  };

  const handleViewAllClick = (person: any) => {
  // navigate(`/deposit/list/${projectId}`, { state: { userId: person } });
  sessionStorage.setItem("personData", JSON.stringify(person));
  // window.open(`/deposit/list/${projectId}`, "_blank");
  navigate(`/deposit/list/${projectId}`);
};

  const handleViewPieChart = (categoryName: string) => {
  // navigate(`/deposit/list/${projectId}`, { state: { userId: person } });
  sessionStorage.setItem("categoryName", categoryName);
  window.open(`/project/report/${projectId}`, "_blank");
 // console.log(categoryName)
};


  const lineChartOptions = {
    chart: {
      type: 'line',
      height: 350,
      // width: 500,
    },
    title: {
      text: 'Yearly Expense Trend',
    },
    xAxis: {
      categories: [
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
      ],
    },
    yAxis: {
      title: {
        text: 'Expense Amount ($)',
      },
    },
    credits: {
      enabled: false, // Disable the watermark
    },
    series: [
      {
        name: 'Total Expense',
        data: yearlyData,
      },
    ],
    
  };
  
  // Bar Chart (Expense Category)
  const barChartOptions = {
    chart: {
      type: 'column',
      height: 350,
      // width: 500,
    },
    title: {
      text: 'Expense by Category',
    },
    xAxis: {
      categories: categories.map((category) => category.category_name), // Category names
    },
    yAxis: {
      title: {
        text: 'Expense Amount ($)',
      },
    },
    credits: {
      enabled: false, // Disable the watermark
    },
    series: [
      {
        name: 'Expense',
        data: categories.map((category) => categoryData[category.category_name] || 0), // Ensure the data is mapped correctly to the categories
      },
    ],
  };


 const calculateCategoryHST = (expenses: Expense[], categories: Category[]) => {
  const categoryHST: Record<string, number> = {};

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

  expenses.forEach((expense) => {
    const { returnedHstPortion } = getReturnSplit(expense);
    const hst = (Number(expense.hst) || 0) - returnedHstPortion; // Net of any returned HST
    const categoryName = categoryMap[expense.category];

    if (categoryName) {
      categoryHST[categoryName] = (categoryHST[categoryName] || 0) + hst;
    }
  });

  return categoryHST;
};

// Example Usage
const categoryHST = calculateCategoryHST(expenses, categories);
const totalBankBalance = deposit.filter((d) => d.is_approved).reduce((acc, curr) => acc + Number(curr.amount), 0);
const overallExpense = expenses.reduce((acc, expense) => acc + netTotal(expense), 0);
const paidExpense =  expenses
.filter(expense => String(expense.status) === 'Paid')  // Convert status to string
.reduce((total, expense) => total + netTotal(expense), 0); 


const allTypes = ["Other", "Labour", "Material", "Material + Labour"]; // All possible types
const typeColors: Record<string, string> = {
  Other: "#FF9800",
  Labour: "#4CAF50",
  Material: "#2196F3",
  "Material + Labour": "#9C27B0",
};

const calculatePieData = (categoryName: string) => {
  // Filter expenses for this category
  const filteredExpenses = expenses.filter(
    (expense) => categoryMap[expense.category] === categoryName
  );

  // Total per type, 0 if type not present
  const typeTotals = allTypes.map((type) =>
    filteredExpenses
      .filter((e) => (e.type || "Other") === type)
      .reduce((sum, e) => sum + netTotal(e), 0)
  );

  return {
    labels: allTypes,
    datasets: [
      {
        data: typeTotals,
        backgroundColor: allTypes.map((t) => typeColors[t]),
        hoverOffset: 4,
      },
    ],
  };
};

const calculateGroupPieData = (group: any) => {

  const filteredExpenses = expenses.filter((expense) =>
    group.category_ids.includes(Number(expense.category))
  );

  const typeTotals = allTypes.map((type) =>
    filteredExpenses
      .filter((e) => (e.type || "Other") === type)
      .reduce((sum, e) => sum + netTotal(e), 0)
  );

  return {
    labels: allTypes,
    datasets: [
      {
        data: typeTotals,
        backgroundColor: allTypes.map((t) => typeColors[t]),
        hoverOffset: 4,
      },
    ],
  };
};

// const calculatePieData = (categoryName: string) => {
//   const totalExpense = categoryData[categoryName] || 0;
//   const totalHST = categoryHST[categoryName] || 0;
//   const overallExpensePercentage = ((totalExpense / overallExpense) * 100).toFixed(2);

//   return {
//     labels: [`${categoryName} %`, `Overall Expense`],
//     datasets: [
//       {
//         data: [totalExpense, overallExpense], // Data for percentage and total expense
//         backgroundColor: ['#4CAF50', '#FF9800'], // Green for percentage, Orange for overall expense
//         hoverOffset: 4,
//       },
//     ],
//   };
// };


const handleApproveDeposit = (depositId: number) => {
  // API call to approve the deposit (you can use Axios or Fetch)
  axios
    .put(`${API_URL}/deposits/${depositId}/approve`,   { approved_by: userInfo?.user_id } )
    .then((response) => {
      showMessage("Approved successfully");
      // Update the state to reflect the change (this will re-render the UI)
      setDeposit((prevDeposits) =>
        prevDeposits.map((deposit) =>
          deposit.id === depositId ? { ...deposit, is_approved: true } : deposit
        )
      );
    })
    .catch((error) => {
      console.error('Error approving deposit:', error);
    });
};

const calculatePaidExpenses = () => {
  return expenses
    .filter(expense => String(expense.status) === 'Paid') // Ensure status is a string and matches "Paid"
    .reduce((total, expense) => {
      // Check if the amount is a string and parse it to a number if necessary
      const expenseTotal = typeof expense.total === 'string' ? parseFloat(expense.total) : expense.total;
      const returned = Number(expense.return_amount) || 0;
      return total + (isNaN(expenseTotal) ? 0 : expenseTotal) - returned;
    }, 0);
};


const formatCurrency = (amount: number) => {
  return amount.toFixed(2); // Format the number to two decimal places
};

  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/${selectedExpense?.id}`, {
        installmentDetails: JSON.stringify(updatedInstallments),
      }, {
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      });

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

      // 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 fetchIncomes = async () => {
  //  setLoading(true);
    try {
      const res = await axios.get(`${API_URL}/property-incomes/${projectId}`, {
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      });
      setIncomes(res.data);
    } catch { showErrorMessage("Failed to load income records."); }
    finally { 
      //setLoading(false);
     }
  };

 const totalIncome = useMemo(() =>
    incomes.filter(i => i.status !== "cancelled").reduce((s, i) => s + Number(i.amount), 0), [incomes]);

  const verifiedIncome = useMemo(() =>
    incomes.filter(i => i.status === "verified").reduce((s, i) => s + Number(i.amount), 0), [incomes]);

  const pendingIncome = useMemo(() =>
    incomes.filter(i => i.status === "created").reduce((s, i) => s + Number(i.amount), 0), [incomes]);


const handleToggleExpand = (id: number) => {
  setExpandedExpenseId(expandedExpenseId === id ? null : id);
};

const handleViewGroup = (group:any) => {
   navigate(`/expense/${projectId}/group/${group.id}`);

};

const exportGroupExcel = (group:any) => {

   const groupExpenses = filteredExpenses.filter((expense:any) =>
    group.category_ids.includes(Number(expense.category))
    // && expense.installment !== 1
  );

  

  const data = groupExpenses.map((e:any) => ({
    Date: e.date,
    Description: e.description,
    Category: categoryMap[e.category],
    Type: e.type,
    Amount: e.total
  }));

  const worksheet = XLSX.utils.json_to_sheet(data);
  const workbook = XLSX.utils.book_new();

  XLSX.utils.book_append_sheet(workbook, worksheet, group.group_name);

  XLSX.writeFile(workbook, `${group.group_name}_expenses.xlsx`);
};

const downloadGroupPDF = (group: any) => {

  const groupExpenses = expenses.filter(
    (e: any) =>
      group.category_ids.includes(Number(e.category)) 
    // && Number(e.installment) !== 1
  );

  // A4 portrait with mm units
  const doc = new jsPDF("p", "mm", "a4");

  const pageWidth = doc.internal.pageSize.getWidth();

  const groupTotal = groupExpenses.reduce(
    (sum: number, e: any) => sum + netTotal(e),
    0
  );

  // Header
  doc.setFontSize(16);
  doc.text("Expense Report", pageWidth / 2, 15, { align: "center" });

  doc.setFontSize(10);
  doc.text(`Group: ${group.group_name}`, 14, 25);
  doc.text(`Generated: ${new Date().toLocaleDateString()}`, 14, 31);
  doc.text(`Total Expense: $${groupTotal.toFixed(2)}`, 14, 37);

  const tableData = groupExpenses.map((e: any) => [
    e.date,
    e.description,
    categoryMap[e.category],
    e.type,
    `$${Number(e.total).toFixed(2)}`
  ]);

  autoTable(doc, {
    startY: 45,

    head: [["Date", "Description", "Category", "Type", "Amount"]],
    body: tableData,

    tableWidth: "auto",

    styles: {
      fontSize: 9,
      cellPadding: 2
    },

    headStyles: {
      fillColor: [52, 73, 94],
      textColor: 255,
      fontSize: 10
    },

    alternateRowStyles: {
      fillColor: [245, 245, 245]
    },

    columnStyles: {
      5: { halign: "right" }
    }
  });

  doc.save(`${group.group_name}_Expense_Report.pdf`);
};

const handlePrintGroup = (group:any) => {
  setSelectedGroup(group);
};

const handlePrint = () => {
  window.print();
};

// const printGroup = (group:any) => {

//   const groupExpenses = expenses.filter((expense:any) =>
//     group.category_ids.includes(Number(expense.category))
//   );

//   const printWindow = window.open("", "_blank");

//   if (!printWindow) return;

//   printWindow.document.write(`
//     <html>
//       <head>
//         <title>${group.group_name} Expenses</title>
//       </head>
//       <body>
//         <h2>${group.group_name} Expenses</h2>
//         <table border="1" cellspacing="0" cellpadding="5">
//           <tr>
//             <th>Date</th>
//             <th>Description</th>
//             <th>Category</th>
//             <th>Type</th>
//             <th>Amount</th>
//           </tr>
//           ${groupExpenses
//             .map(
//               (e:any) => `
//               <tr>
//                 <td>${e.date}</td>
//                 <td>${e.description}</td>
//                 <td>${categoryMap[e.category]}</td>
//                 <td>${e.type}</td>
//                 <td>$${Number(e.total).toFixed(2)}</td>
//               </tr>
//             `
//             )
//             .join("")}
//         </table>
//       </body>
//     </html>
//   `);

//   printWindow.document.close();
//   printWindow.print();
// };


const handleReturnClick = (expense: Expense) => {
  const remaining = Number(expense.total ?? 0) - Number(expense.return_amount ?? 0);

  if (remaining <= 0) {
    showErrorMessage("This expense has already been fully returned.");
    return;
  }

  setSelectedExpense(expense);
  setReturnData({
    date: new Date().toLocaleDateString("en-CA", { timeZone: "America/Toronto" }),
     amount: remaining.toFixed(2),
    reason: "",
  });
  setReturnModalOpen(true);
};


const handleReturnExpense = async () => {
  const amountNum = parseFloat(returnData.amount);
  const alreadyReturned = Number(selectedExpense?.return_amount ?? 0);
  const totalAmt = Number(selectedExpense?.total ?? 0);
  const remaining = totalAmt - alreadyReturned;

  if (!returnData.amount || isNaN(amountNum) || amountNum <= 0) {
    showErrorMessage("Please enter a valid return amount.");
    return;
  }

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

  try {
    await axios.post(`${API_URL}/expense-return/${selectedExpense?.id}`, {
      return_amount: amountNum,       // this return's amount only
      return_date: returnData.date,
      return_reason: returnData.reason,
    }, {
      headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
    });

    showMessage("Return recorded successfully!");
    fetchExpenses();
    setReturnModalOpen(false);
  } catch {
    showErrorMessage("Failed to record return.");
  }
};



  return (

    
    <>
    <Grid container spacing={2} sx={{ marginTop: 1 }}>
  {/* Card 1 */}
  <Grid item xs={12} sm={6} md={2.4}>
    <Card
      elevation={3}
      sx={{ cursor: "pointer", height: "100%" }}
      onClick={handleAddProductClick}
    >
      <CardContent>
        <Grid container direction="column" alignItems="center">
          <FaClipboardList size={40} color="#4CAF50" />
          <Typography variant="h6" mt={2} align="center">
            Add Expense
          </Typography>
        </Grid>
      </CardContent>
    </Card>
  </Grid>

  {/* Card 2 */}
  <Grid item xs={12} sm={6} md={2.4}>
    <Card
      elevation={3}
      sx={{ cursor: "pointer", height: "100%" }}
      onClick={handleAddCategoryClick}
    >
      <CardContent>
        <Grid container direction="column" alignItems="center">
          <FaMoneyCheckAlt size={40} color="#3f51b5" />
          <Typography variant="h6" mt={2} align="center">
            Manage Expense
          </Typography>
        </Grid>
      </CardContent>
    </Card>
  </Grid>

  {/* Card 3 */}
  <Grid item xs={12} sm={6} md={2.4}>
    <Card
      elevation={3}
      sx={{ cursor: "pointer", height: "100%" }}
      onClick={handleAddGroupClick}
    >
      <CardContent>
        <Grid container direction="column" alignItems="center">
          <FaLayerGroup size={40} color="#a82f2fd7" />
          <Typography variant="h6" mt={2} align="center">
            Manage Group
          </Typography>
        </Grid>
      </CardContent>
    </Card>
  </Grid>

  {/* Card 4 */}
  <Grid item xs={12} sm={6} md={2.4}>
    <Card
      elevation={3}
      sx={{ cursor: "pointer", height: "100%" }}
      onClick={() => navigate(`/income/${projectId}`)}
    >
      <CardContent>
        <Grid container direction="column" alignItems="center">
          <FaMoneyBillWave size={40} color="#2196F3" />
          <Typography variant="h6" mt={2} align="center">
            Income
          </Typography>
        </Grid>
      </CardContent>
    </Card>
  </Grid>

  {/* Card 5 */}
  <Grid item xs={12} sm={6} md={2.4}>
    <Card
      elevation={3}
      sx={{ cursor: "pointer", height: "100%" }}
      onClick={() => navigate(`/balance-sheet/${projectId}`)}
    >
      <CardContent>
        <Grid container direction="column" alignItems="center">
          <FaChartPie size={40} color="#795548" />
          <Typography variant="h6" mt={2} align="center">
            Balance Sheet
          </Typography>
        </Grid>
      </CardContent>
    </Card>
  </Grid>
</Grid>


    <Grid container spacing={4} justifyContent="center" sx={{ marginTop: 1 }}>
  {team .filter((person) => person.id !== userInfo?.user_id) // Exclude the logged-in user's data
    .map((person, index) => {
    const personDeposits = deposit.filter((d) => d.user_id === person.id); // Filter all deposits for the person

    const personTotalDeposit = personDeposits
      .filter((d) => d.is_approved) // Only include approved deposits for the total calculation
      .reduce((acc, curr) => acc + Number(curr.amount), 0);

    const unapprovedDeposits = personDeposits.filter((d) => !d.is_approved); // Filter out unapproved deposits

    // Only render the Card if there are unapproved deposits for this person
    if (unapprovedDeposits.length === 0) return null;

    return (
      <Grid item xs={12} sm={6} md={6} key={index}>
        <Card elevation={3} sx={{ height: '350px', display: 'flex', flexDirection: 'column' }}>
          <CardContent sx={{ flex: 1 }}>
            <Grid container alignItems="center" mt={1} justifyContent="center" spacing={2}>
              <Grid item>
                <Typography variant="body2" align="center" sx={{ fontWeight: 'bold', fontSize: '15px' }}>
                  {person.driverFirstName} {person.driverLastName}
                </Typography>
              </Grid>
            </Grid>

            {/* Section to approve deposits */}
            {unapprovedDeposits.length > 0 && (
              <Box mt={3}>
                <Typography variant="h6" align="center" sx={{ fontWeight: 'bold' }}>
                  Pending Approvals
                </Typography>
                <Box sx={{ maxHeight: '200px', overflowY: 'auto' }} className={classes.thinScrollbar}>
                  <Table className={classes.table}>
                    <TableHead className={classes.tableHeaderRow}>
                      <TableRow>
                        <TableCell className={classes.tablheader}>Date</TableCell>
                        <TableCell className={classes.tablheader}>Amount</TableCell>
                        <TableCell className={classes.tablheader}>Action</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {unapprovedDeposits.map((depositItem, idx) => (
                        <TableRow key={idx}>
                          <TableCell scope="row" className={classes.tablCell}>
                            {new Date(depositItem.created_at).toLocaleDateString()}
                          </TableCell>
                          <TableCell scope="row" className={classes.tablCell}>
                            ${depositItem.amount}

                            
                          </TableCell>
                          <TableCell scope="row" className={classes.tablCell}>
                            <Button
                              variant="contained"
                              color="primary"
                              size="small"
                              onClick={() => handleApproveDeposit(depositItem.id)}
                            >
                              Approve
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </Box>
              </Box>
            )}
          </CardContent>
        </Card>
      </Grid>
    );
  })}
</Grid>




  <Grid container spacing={4} justifyContent="center" sx={{ marginTop: 1 }}>

{groups.map((group)=>{

   const groupCategories = group.category_ids
      .map((id: number) => categoryMap[id])
      .filter(Boolean);

    const totalCategories = group.category_ids.length;

    const pieData = calculateGroupPieData(group);
    const groupTotal = calculateGroupTotal(group);

  const groupPercentage =
    overallExpense > 0
      ? ((groupTotal / overallExpense) * 100).toFixed(2)
      : "0.00";

      const maxRows = 3;
const chipsPerRow = isMobile ? 3 : 5; 
const maxVisibleChips = maxRows * chipsPerRow;
const visibleCategories = groupCategories.slice(0, maxVisibleChips);
const remainingCount = groupCategories.length - maxVisibleChips;

return(

<Grid item xs={12} sm={4} md={4} key={group.id}>

<Card elevation={3} sx={{ height:'530px', display:'flex', flexDirection:'column' }}>

<CardContent sx={{ flex:1, display:'flex', flexDirection:'column', position:'relative' }}>

{/* ACTION ICONS */}

<Box
  sx={{
    position: "absolute",
    top: 10,
    right: 10,
    display: "flex",
    alignItems: "center",
    background: "rgba(255,255,255,0.9)",
    backdropFilter: "blur(6px)",
    borderRadius: "20px",
    // boxShadow: "0 2px 8px rgba(0,0,0,0.15)",
    px: 0.5,
    py: 0.3
  }}
>
  <MuiTooltip title="View Details">
    <IconButton
      size="small"
      onClick={() => handleViewGroup(group)}
      sx={{
        color: "#1976d2",
        transition: "0.2s",
        "&:hover": {
          backgroundColor: "#e3f2fd",
          transform: "scale(1.1)"
        }
      }}
    >
      <VisibilityIcon fontSize="small" />
    </IconButton>
  </MuiTooltip>

  <MuiTooltip title="Export Excel">
    <IconButton
      size="small"
      onClick={() => exportGroupExcel(group)}
      sx={{
        color: "#2e7d32",
        transition: "0.2s",
        "&:hover": {
          backgroundColor: "#e8f5e9",
          transform: "scale(1.1)"
        }
      }}
    >
         <GridOnIcon  fontSize="small" />
    </IconButton>
  </MuiTooltip>

<MuiTooltip title="Download PDF">
  <IconButton
    size="small"
    onClick={() => downloadGroupPDF(group)}
    sx={{
      color: "#d32f2f",
      transition: "0.2s",
      "&:hover": {
        backgroundColor: "#fdecea",
        transform: "scale(1.1)"
      }
    }}
  >
    <PictureAsPdfRoundedIcon fontSize="small" />
  </IconButton>
</MuiTooltip>
</Box>

<Grid container direction="column" alignItems="center">

{/* GROUP NAME */}

<Box sx={{ position:'relative', width:'100%', mt:2 }}>

<Typography
variant="body2"
align="center"
sx={{ fontWeight:'bold', fontSize:'16px' }}
>
{group.group_name}
</Typography>

 <Typography
            variant="h3"
            align="center"
            sx={{ marginTop: 2, fontWeight: "bold", color: "#4CAF50" }}
          >
           ${groupTotal.toFixed(2)}
          </Typography>

             

                 {/* <Button
  size="small"
  variant="contained"
  color="secondary"
  // onClick={() => navigate(`/expenses/${projectId}`)}
   component={Link}
    to={`/expense/${projectId}/group/${group.id}`}
   // target="_blank" 
   sx={{
    position: 'absolute',
    top: 0,
    right: 0,
    minWidth: "40px",
    padding: "2px 8px",
    borderRadius: "6px",
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
  }}
>
  <VisibilitySharpIcon fontSize="small" />  
</Button> */}

       
</Box>


{/* PIE CHART */}

<Grid container direction="row" alignItems="center" spacing={2} sx={{ mt:2 }}>

<Grid item md={8} sx={{ display:'flex', justifyContent:'center' }}>

<Box sx={{ width:'150px', height:'150px' }}>
 

<Pie
data={pieData}
options={{
plugins:{
tooltip:{
callbacks:{
label:function(tooltipItem:any){

const value = tooltipItem.raw as number;

const total = (pieData.datasets[0].data as number[]).reduce(
  (a, b) => a + b,
  0
);

const percentage = ((value / total) * 100).toFixed(2);

return `$${value} (${percentage}%)`;
}
}
},
    legend: {
       
        display: true,
        labels: {
          color: '#000',
           boxWidth: 12,
        
        },
      },
}
}}
/>

</Box>

</Grid>


{/* GROUP TOTAL */}

<Grid item md={3} sx={{ display:'flex', justifyContent:'center', alignItems:'center' }}>

<Box sx={{ textAlign:'center' }}>

<Typography variant="body2">
Total {group.category_ids.length}
</Typography>

 <Typography variant="h3" sx={{ fontSize: '1.2rem'}}>

  {groupPercentage}%
</Typography>



           
            

</Box>

</Grid>

</Grid>


{/* CATEGORY LIST */}

<Box
sx={{
flex:1,
overflowY:'auto',
maxHeight:'200px',
width:'100%',
mt:2
}}
className={classes.thinScrollbar}
>

<Grid container direction="column" spacing={1}>

{pieData.labels.map((cat:any,index:number)=>{

const value = pieData.datasets[0].data[index];

return(

<Grid
item
key={cat}
container
justifyContent="space-between"
alignItems="center"
>

<Grid item xs={8}>

<Typography variant="body2">
{cat}
</Typography>

</Grid>

<Grid item xs={4} textAlign="right">

<Typography variant="body2">
${Number(value).toFixed(2)}
</Typography>

</Grid>

 <Grid item xs={12}>
    <Divider />
  </Grid>

</Grid>

)

})}

</Grid>



</Box>

{/* <Box sx={{ mt: 4 }}>
  <Stack direction="row" spacing={1} flexWrap="wrap">
    {groupCategories.map((name: string, index: number) => (
      <Chip
        key={index}
        label={name}
        color="primary"
        size="small"
        sx={{ mb: 0.5, fontWeight: 500, cursor: 'default' }}
        variant="outlined"
      />
    ))}
  </Stack>
</Box> */}
{/* FOOTER */}


<Box
  sx={{
    mt: "auto",
    pt: 4,
    pb: 1,
  }}
>
  {/* Show only first 12 categories (~3 rows) */}
<Box
  sx={{
    display: "flex",
    flexWrap: "wrap",
    gap: 0.5,
    //justifyContent: "center"
     maxHeight: "84px",       // ~3 rows at this chip size — tune if needed
    overflowY: "auto",
    justifyContent: isMobile ? "center" : "flex-start",
  }}
>
  {visibleCategories.map((name, index) => (
    <Chip
      key={index}
      label={name}
      color="primary"
      size="small"
      variant="outlined"
      sx={{
        fontWeight: 500,
        maxWidth: "120px",
        textOverflow: "ellipsis",
        overflow: "hidden",
        whiteSpace: "nowrap",
      }}
    />
  ))}

  {remainingCount > 0 && (
    <Button
      variant="text"
      size="small"
      onClick={() => navigate(`/expense/${projectId}/group/${group.id}`)}
      sx={{ minWidth: "auto", padding: "0 4px", textTransform: "none" }}
    >
      +{remainingCount} more
    </Button>
  )}
</Box>



</Box>

</Grid>

</CardContent>

</Card>

</Grid>

)

})}

</Grid>









    <Grid container spacing={4}  justifyContent="center" sx={{ marginTop: 3}}>
    <Grid item xs={12} sm={12} md={6} >
      <Card>
        <CardContent>
          <HighchartsReact highcharts={Highcharts} options={lineChartOptions} />
        </CardContent>
      </Card>
    </Grid>

    <Grid item xs={12} sm={12} md={6}>
      <Card>
        <CardContent>
          <HighchartsReact highcharts={Highcharts} options={barChartOptions} />
        </CardContent>
      </Card>
    </Grid>
  </Grid>

    <Grid container spacing={4} justifyContent="center" sx={{ marginTop: 1 }}>
  {/* Card 1 */}
  <Grid item xs={12} sm={4} md={3}>
    <Card elevation={3} >
      <CardContent>
        <Grid container direction="column" alignItems="center">
          {/* <FaClipboardList size={40} color="#4CAF50" /> */}
          <Typography variant="h5" mt={2}>
            Total Deposit
          </Typography>
          <Typography
            variant="h3"
            sx={{ marginTop: 2, fontWeight: "bold", color: "#4CAF50" }}
          >
        ${totalBankBalance.toFixed(2) || '0'}
          </Typography>
        </Grid>
      </CardContent>
    </Card>
  </Grid>

 {/* Total Income — verified only */}
<Grid item xs={12} sm={4} md={3}>
  <Card elevation={3}>
    <CardContent>
      <Grid container direction="column" alignItems="center">
        <Box display="flex" alignItems="center" gap={0.75} mt={2}>
          <Typography variant="h5">Total Income</Typography>
          <Box
            sx={{
              display: 'inline-flex',
              alignItems: 'center',
              backgroundColor: '#e8f5e9',
              border: '1px solid #66bb6a',
              borderRadius: '20px',
              padding: '1px 8px',
            }}
          >
            <Typography sx={{ fontSize: '0.65rem', fontWeight: 700, color: '#2e7d32' }}>
              Verified
            </Typography>
          </Box>
        </Box>
        <Typography
          variant="h3"
          sx={{ marginTop: 2, fontWeight: "bold", color: "#4CAF50" }}
        >
          ${verifiedIncome.toFixed(2) || '0'}
        </Typography>
      </Grid>
    </CardContent>
  </Card>
</Grid>

{/* Total Expense — paid only */}
<Grid item xs={12} sm={4} md={3}>
  <Card elevation={3}>
    <CardContent>
      <Grid container direction="column" alignItems="center">
        <Box display="flex" alignItems="center" gap={0.75} mt={2}>
          <Typography variant="h5">Total Expense</Typography>
          <Box
            sx={{
              display: 'inline-flex',
              alignItems: 'center',
              backgroundColor: '#e8f5e9',
              border: '1px solid #66bb6a',
              borderRadius: '20px',
              padding: '1px 8px',
            }}
          >
            <Typography sx={{ fontSize: '0.65rem', fontWeight: 700, color: '#2e7d32' }}>
              Paid
            </Typography>
          </Box>
        </Box>
        <Typography
          variant="h3"
          sx={{ marginTop: 2, fontWeight: "bold", color: "#4CAF50" }}
        >
          ${Number(calculatePaidExpenses()).toFixed(2) || '0.00'}
        </Typography>
      </Grid>
    </CardContent>
  </Card>
</Grid>

  

  <Grid item xs={12} sm={4} md={3}>
    <Card elevation={3} >
      <CardContent>
        <Grid container direction="column" alignItems="center">
          {/* <FaClipboardList size={40} color="#4CAF50" /> */}
          <Typography variant="h5" mt={2}>
            Bank Balance
          </Typography>
          <Typography
            variant="h3"
            sx={{ marginTop: 2, fontWeight: "bold", color: "#4CAF50" }}
          >
   {/* ${formatCurrency(totalBankBalance - calculatePaidExpenses())} */}
   ${formatCurrency(totalBankBalance + verifiedIncome - calculatePaidExpenses())}
          </Typography>
        </Grid>
      </CardContent>
    </Card>
  </Grid>



</Grid>


<Grid container spacing={4} justifyContent="center" sx={{ marginTop: 1 }}>
  {team.map((person, index) => {

    const personDeposits = deposit.filter(d => d.user_id === person.id ); 
    
    const personTotalDeposit = personDeposits.filter((d) => d.is_approved)
    .reduce((acc, curr) => acc + Number(curr.amount), 0);

    return (
      <Grid item xs={12} sm={6} md={6} key={index}>
        <Card elevation={3} sx={{ height: '350px', display: 'flex', flexDirection: 'column' }}>
          <CardContent sx={{ flex: 1 }}>
            <Grid container alignItems="center" mt={1} justifyContent="center" spacing={2}>
              <Grid item>
                <Typography variant="body2" align="center" sx={{ fontWeight: 'bold', fontSize: '15px' }}>
                  {person.driverFirstName} {person.driverLastName}
                </Typography>
              </Grid>
              <Grid item>
                <Typography variant="h4" align="center" sx={{ fontWeight: 'bold', color: "#4CAF50" }}>
                  ${personTotalDeposit.toFixed(2)}
                </Typography>
              </Grid>
            </Grid>
            <Box display="flex" justifyContent="center" gap={2} mt={2}>
              <Button
                size="small" 
                variant="contained"
                color="primary"
                onClick={() => handleDepositClick(person.id)}
              >
                Deposit
              </Button>
                <Button
    size="small"
    variant="contained"
    color="secondary"
    onClick={() => handleViewAllClick(person)}
    sx={{
    minWidth: "40px",       // Reduce minimum width
    padding: "6px 8px",     // Reduce padding
    borderRadius: "6px",    // Optional: rounded corners
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
  }}
    
  >
   <VisibilitySharpIcon fontSize="small"/>
  </Button>
            </Box>
            <Box
              mt={3}
              sx={{ maxHeight: '200px', overflowY: 'auto' }}
              className={classes.thinScrollbar}
            >
              <Table className={classes.table}>
                <TableHead className={classes.tableHeaderRow}>
                  <TableRow>
                    <TableCell className={classes.tablheader}>Date</TableCell>
                    <TableCell className={classes.tablheader}>Amount</TableCell>
                    <TableCell className={classes.tablheader}>Status</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {personDeposits.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={3} align="center" className={classes.tablCell}>
                        No Data Available
                      </TableCell>
                    </TableRow>
                  ) : (
                    personDeposits
                    .sort((a, b) => {
                      const dateA = new Date(a.date).getTime();
                      const dateB = new Date(b.date).getTime();
                  
                      // First sort by date (descending)
                      if (dateB !== dateA) {
                        return dateB - dateA;
                      }
                  
                      // If the dates are the same, sort by ID (ascending)
                      return b.id - a.id;
                    }).
                    map((depositItem, idx) => (
                      <TableRow key={idx}>
                        <TableCell scope="row" className={classes.tablCell}>
                          {new Date(depositItem.date).toLocaleDateString()}
                        </TableCell>
                        <TableCell scope="row" className={classes.tablCell}>
                          ${depositItem.amount}
                          {depositItem.remarks ? (
        <MuiTooltip
          title={depositItem.remarks}
          arrow
          open={tooltipOpen[depositItem.id] || false}
          onOpen={() => handleTooltipOpen(depositItem.id)}
          onClose={() => handleTooltipClose(depositItem.id)}
          disableInteractive
        >
          <InfoIcon
            sx={{
              color: '#2196F3',
              cursor: 'pointer',
              fontSize: '1.1rem',
              marginLeft: '8px',
              verticalAlign: 'middle',
            }} 
            onClick={()=>handleMobileTooltipToggle(depositItem.id)} // Mobile: tap to toggle
            onTouchStart={()=>handleMobileTooltipToggle(depositItem.id)}  
          />
        </MuiTooltip>
      ) : null}
                        </TableCell>
                        <TableCell scope="row" className={classes.tablCell}>
                          {depositItem.is_approved ? (
                            <CheckCircleIcon sx={{ color: 'green', backgroundColor: '#d4edda', borderRadius: '50%' }} />
                          ) : (
                            <CheckCircleIcon sx={{ color: 'red', backgroundColor: '#f8d7da', borderRadius: '50%' }} />
                          )}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </Box>
          </CardContent>
        </Card>
      </Grid>
    );
  })}
</Grid>



{Object.keys(incomeBySource).length > 0 && (() => {
  const sortedSources = Object.entries(incomeBySource).sort(([, a], [, b]) => b - a);

  // Pull from theme instead of hardcoding — falls back gracefully if not defined
  const palette = [
    theme.palette.primary.main,
    theme.palette.success.main,
    theme.palette.warning.main,
    theme.palette.secondary.main,
    theme.palette.info.main,
    theme.palette.error.main,
  ];

  return (
    <Grid container spacing={4} sx={{ marginTop: 2 }}>
      <Grid item xs={12}>
        <Card
          className={classes.card}
          sx={{
            borderRadius: 3,
            overflow: "hidden",
            boxShadow: theme.shadows[3],
          }}
        >
          {/* Header */}
          <Box
            sx={{
              background: `linear-gradient(135deg, ${theme.palette.primary.dark} 0%, ${theme.palette.primary.main} 60%, ${theme.palette.primary.light} 100%)`,
              px: 3,
              py: 2.5,
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              flexWrap: "wrap",
              gap: 1,
            }}
          >
            <Box>
              <Typography sx={{ color: theme.palette.primary.contrastText, fontWeight: 700, fontSize: "1.1rem" }}>
                Income by Source
              </Typography>
              <Typography sx={{ color: theme.palette.primary.contrastText, opacity: 0.8, fontSize: "0.8rem" }}>
                {sortedSources.length} active source{sortedSources.length !== 1 ? "s" : ""} · Total{" "}
                <b>${totalIncome.toFixed(2)}</b>
              </Typography>
            </Box>
          <Button
  size="small"
  component={Link}
  to={`/income/${projectId}`}
  sx={{
    backgroundColor: "rgba(255,255,255,0.18)",
    color: theme.palette.primary.contrastText,
    border: `1px solid rgba(255,255,255,0.4)`,
    borderRadius: "20px",
    px: 2,
    textTransform: "none",
    fontWeight: 600,
    "&:hover": {
      backgroundColor: "rgba(255,255,255,0.3)",
    },
  }}
>
  <VisibilitySharpIcon fontSize="small" sx={{ mr: 0.5 }} />
  View All
</Button>
          </Box>

          {/* Body */}
          <Box p={{ xs: 2, sm: 3 }}>
            <Grid container spacing={2}>
              {sortedSources.map(([sourceName, amount], index) => {
                const pct = totalIncome > 0 ? (amount / totalIncome) * 100 : 0;
                const color = palette[index % palette.length];
                const isTop = index === 0;

                return (
                  <Grid item xs={12} sm={6} md={4} key={sourceName}>
                    <Box
                      sx={{
                        position: "relative",
                        borderRadius: 2.5,
                        p: 2,
                        height: "100%",
                        backgroundColor: theme.palette.grey[50] ?? "#fafafa",
                        border: `1px solid ${theme.palette.divider}`,
                        borderLeft: `4px solid ${color}`,
                        transition: "all 0.2s ease",
                        "&:hover": {
                          backgroundColor: theme.palette.background.paper,
                          boxShadow: theme.shadows[4],
                          transform: "translateY(-2px)",
                        },
                      }}
                    >
                      {isTop && (
                        <Chip
                          label="Top Source"
                          size="small"
                          color="warning"
                          sx={{ position: "absolute", top: 10, right: 10, height: 20, fontSize: "0.62rem", fontWeight: 700 }}
                        />
                      )}

                      <Box display="flex" alignItems="center" gap={1.2} mb={1}>
                        <Box
                          sx={{
                            width: 34, height: 34, borderRadius: "50%",
                            backgroundColor: `${color}1A`,
                            color, display: "flex", alignItems: "center", justifyContent: "center",
                            fontWeight: 700, fontSize: "0.9rem", flexShrink: 0,
                          }}
                        >
                          {sourceName.charAt(0).toUpperCase()}
                        </Box>
                        <Typography variant="body2" sx={{ fontWeight: 600, color: theme.palette.text.primary, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                          {sourceName}
                        </Typography>
                      </Box>

                      <Typography variant="h5" sx={{ fontWeight: 800, color: theme.palette.text.primary, lineHeight: 1.1 }}>
                        ${amount.toFixed(2)}
                      </Typography>

                      <Box mt={1.2}>
                        <Box sx={{ height: 6, borderRadius: 3, backgroundColor: theme.palette.action.hover, overflow: "hidden" }}>
                          <Box sx={{ height: "100%", borderRadius: 3, backgroundColor: color, width: `${Math.min(pct, 100)}%`, transition: "width 0.5s ease" }} />
                        </Box>
                        <Typography variant="caption" sx={{ color: theme.palette.text.secondary, mt: 0.5, display: "block" }}>
                          {pct.toFixed(1)}% of total income
                        </Typography>
                      </Box>
                    </Box>
                  </Grid>
                );
              })}
            </Grid>
          </Box>
        </Card>
      </Grid>
    </Grid>
  );
})()}



    <Grid container spacing={4}  sx={{ marginTop: 2 }}>
    <Grid item xs={12} sm={12} md={12}>
    <Card className={classes.card}>



        <Grid
          container
          justifyContent={"space-between"}
          spacing={5}
          sx={{ borderBottom: 2, padding: 2 }}
          className={classes.titleGrid}
        >
          <Grid item lg={4} md={4} sm={4} xs={4} pt={2} alignContent={"center"}>
            <Typography className={classes.cardTitle}>Expense</Typography>
          </Grid>
          <Grid
            item
            lg={8}
            md={8}
            sm={8}
            xs={8}
            sx={{ display: "flex", justifyContent: "flex-end" }}
          >
            <Grid
              container
              spacing={1}
              justifyContent="flex-end"
              sx={{ display: "flex" }}
            >

              <Grid item>
                <TextField
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <CiSearch className={classes.searchWidgetIcon} />
                      </InputAdornment>
                    ),
                    classes: {
                      root: classes.formControlList,
                    },
                  }}
                  fullWidth
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Expense Name .."
                  sx={{ width: "100%" }}
                  size="small" />
              </Grid>

                          <Grid item>
                            <Button
                              variant="contained"
                              className={classes.addButton}
                              onClick={handleAddProductClick}
                            >
                              Add Expense
                            </Button>
           </Grid>
                           <Grid item> <Button
  size="small"
  variant="contained"
  color="secondary"
   className={classes.addButton}
  // onClick={() => navigate(`/expenses/${projectId}`)}
   component={Link}
    to={`/expenses/${projectId}`}   //  your target route
   // target="_blank" 
  sx={{
    minWidth: "40px",       // Reduce minimum width
    padding: "6px 8px",     // Reduce padding
    borderRadius: "6px",    // Optional: rounded corners
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
  }}
>
  <VisibilitySharpIcon fontSize="small" />  {/* Smaller icon */}
</Button>
          </Grid>    
                          </Grid>

 
          </Grid>
        </Grid>



        <Grid item lg={12} md={12} sm={12} xs={12}>
          <Card >
          <TableContainer
      sx={{
        maxHeight: 450, // Fixed height for the table
        overflowY: 'auto', // Enables vertical scrolling
      }}
      className={classes.thinScrollbar} 
      >
              <Table className={classes.table}>
                <TableHead className={classes.tableHeaderRow}>
                  <TableRow>
                    <TableCell className={classes.tablheader}> <strong>Date</strong></TableCell>
                    <TableCell className={classes.tablheader}> <strong>Details</strong></TableCell>
                    <TableCell className={classes.tablheader}><strong>Category</strong></TableCell>
                    <TableCell className={classes.tablheader}><strong>Type</strong></TableCell>
                    <TableCell className={classes.tablheader}> <strong>Amount</strong></TableCell>
                    <TableCell className={classes.tablheader}><strong>Hst</strong></TableCell>
                    <TableCell className={classes.tablheader}><strong>Total</strong></TableCell>
                    <TableCell className={classes.tablheader}><strong>Status</strong></TableCell>
                   
                    {/* <TableCell className={classes.tablheader}><strong>Invoice File</strong></TableCell> */}
                    <TableCell className={classes.tablheader} sx={{ textAlign: "right" }}>
                      <strong>Actions</strong>
                    </TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {filteredExpenses.length > 0 ? (
                 filteredExpenses
                 .sort((a, b) => {
                  const dateA = new Date(a.date).getTime();
                  const dateB = new Date(b.date).getTime();
              
                  // First sort by date (descending)
                  if (dateB !== dateA) {
                    return dateB - dateA;
                  }
              
                  // If the dates are the same, sort by ID (ascending)
                  return b.id - a.id;
                })
                .filter(expense => expense.installment !== 1)
                  .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                   .map((expense) => (
                      <TableRow key={expense.id}>
                        <TableCell scope="row" className={classes.tablCell}>{expense.date}</TableCell>
                        <TableCell scope="row" className={classes.tablCell}>
                        <Box display="flex" alignItems="center">
    {/* Details text */}
    <span>{expense.description}</span>
                            {expense.file && expense.file.length > 0 && (
      <Box display="flex" marginLeft={1}>
        {parseFiles(expense.file).map((file, index) => (
          <Button
            key={index}
            variant="text"
            className={classes.viewInvoiceButton}
            size="small"
            onClick={() => handleOpenModal(file)}
            sx={{
              minWidth: "auto",
              padding: 0,
              marginRight: 1, // Add space between icons
            }}
          >
            <DescriptionIcon style={{ fontSize: 16 }} />
          </Button>
        ))}
        
                              </Box>
                            )}
                           </Box>
                        </TableCell>



                        <TableCell scope="row" className={classes.tablCell}>
                         
                       <Link 
                           to={`/project/${projectId}/category/${expense.category}`}
                  style={{ textDecoration: 'none',color: 'inherit' }}
                > 
                         {categoryMap[expense.category] || "Unknown"}
                          
                  {/* <LinkIcon fontSize="small" style={{ verticalAlign: "middle" }} /> */}
                </Link>

</TableCell>
                        <TableCell scope="row" className={classes.tablCell}>{expense.type}</TableCell>
                        <TableCell scope="row" className={classes.tablCell}>{expense.amount}</TableCell>
                        <TableCell scope="row" className={classes.tablCell}>{expense.hst}</TableCell>
                        <TableCell scope="row" className={classes.tablCell}>{expense.total}</TableCell>
                        <TableCell scope="row" className={classes.tablCell}>
 <Box display="flex" flexDirection="row" alignItems="center" flexWrap="wrap" gap={0.5}>
    
    {/* Status Badge */}
   <Box
  sx={{
    display: 'inline-flex',
    alignItems: 'center',
    gap: 0.4,
    backgroundColor: String(expense.status) === 'Paid' ? '#e8f5e9' : '#fce4ec',
    border: `1px solid ${String(expense.status) === 'Paid' ? '#66bb6a' : '#f48fb1'}`,
    borderRadius: '20px',
    padding: '2px 8px',
    whiteSpace: 'nowrap',
  }}
>
  <Box
    sx={{
      width: 6,
      height: 6,
      borderRadius: '50%',
      backgroundColor: String(expense.status) === 'Paid' ? '#4CAF50' : '#e91e63',
      flexShrink: 0,
    }}
  />
  <Typography
    sx={{
      fontSize: '0.70rem',
      fontWeight: 600,
      color: String(expense.status) === 'Paid' ? '#2e7d32' : '#880e4f',
      lineHeight: 1,
    }}
  >
    {expense.status}
  </Typography>
</Box>
    {/* Return Badge - only shows if return exists */}
   {Number(expense.return_amount) > 0 && (
  <Box
    sx={{
      display: 'inline-flex',
      alignItems: 'center',
      gap: 0.4,
      backgroundColor: '#fff3e0',
      border: '1px solid #ff5722',
      borderRadius: '20px',
      padding: '2px 8px',
      whiteSpace: 'nowrap',
    }}
  >
    <FaUndo style={{ fontSize: 8, color: '#ff5722' }} />
    <Typography
      sx={{
        fontSize: '0.70rem',
        fontWeight: 700,
        color: '#ff5722',
        lineHeight: 1,
      }}
    >
      -${Number(expense.return_amount).toFixed(2)}
    </Typography>
  </Box>
)}
  </Box>
</TableCell>



                        <TableCell scope="row" className={classes.tablCell}>
  <Grid
                          container
                          spacing={1}
                          sx={{ display: "flex", justifyContent: "flex-end" }}
                        >
                   

<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: 8, 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>
<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="contained"
  className={classes.viewButtonList}
  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
      : []; 
    //console.log("After Images:", afterImages);  // Log the parsed before images array
    
    // Handle the images by calling handleViewImages
    handleViewImages(beforeImages, afterImages);
  }}
 
>
  <VisibilitySharpIcon className={classes.viewListIcon} />
</Button>
)}



                            </Grid>
                            <Grid item>
    <Button
      variant="contained"
      className={classes.editButtonList}
      onClick={() => handleEditClick(expense.id)}
      sx={{
        marginLeft: "auto", // Pushes the edit button to the right
      }}
    >
      <EditSharpIcon className={classes.editListIcon} style={{ fontSize: 20 }} />
    </Button>
    </Grid>

  <Grid item>
  {(() => {
    const isFullyReturned =
      Number(expense.return_amount ?? 0) >= Number(expense.total ?? 0);

    return (
      <MuiTooltip title={isFullyReturned ? "Fully returned" : "Return Item"}>
        <span>
          <Button
            variant="contained"
            disabled={isFullyReturned}
            onClick={() => handleReturnClick(expense)}
            sx={{
              minWidth: '32px',
              width: '32px',
              height: '32px',
              padding: 0,
              borderRadius: '6px',
              backgroundColor: isFullyReturned ? '#e0e0e0' : '#ff5722',
              boxShadow: 'none',
              '&:hover': {
                backgroundColor: isFullyReturned ? '#e0e0e0' : '#e64a19',
                boxShadow: 'none',
              },
              '&.Mui-disabled': {
                backgroundColor: '#e0e0e0',
              },
            }}
          >
            <FaUndo style={{ fontSize: 13, color: isFullyReturned ? '#9e9e9e' : '#fff' }} />
          </Button>
        </span>
      </MuiTooltip>
    );
  })()}
</Grid>
    </Grid>
    
  {/* </Box> */}
                            {/* <Grid item>
                              <Button
                                variant="contained"
                                className={classes.deleteButtonList}
                                onClick={() => handleDeleteClick(expense.id)}
                              >
                                <DeleteOutlineSharpIcon
                                  className={classes.deleteButtonList} />
                              </Button>
                            </Grid> */}
                          
                        </TableCell>
                      </TableRow>

                    ))
                  ) : (

                    <TableRow>

                      <TableCell colSpan={7} align="center">
                        No Data Available
                      </TableCell>

                    </TableRow>

                  )}




                  <TableRow>

                    <TableCell colSpan={4} align="right">
                      <strong>Total </strong>
                    </TableCell>

                    <TableCell>{totalAmount.toFixed(2)}</TableCell>
                    {/* <TableCell> */}
                    {/* <strong>Total HST:</strong> */}
                    {/* </TableCell> */}
                    <TableCell>{totalHst.toFixed(2)}</TableCell>
                    <TableCell colSpan={2}>
                      {/* <strong>Total Amount (With HST):</strong>  */}
                      {totalAmountWithTax.toFixed(2)}
                    </TableCell>
                  </TableRow>
                </TableBody>

              </Table>

              {/* Modal Dialog */}
            <Dialog open={openModal} onClose={handleCloseModal} fullWidth maxWidth="md">
              <DialogTitle>View File</DialogTitle>
              <DialogContent
                sx={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                 // overflow: 'auto', // allow scrolling when zoomed
                 overflow:'hidden'
                }}
              >
                {isPdf ? (
                  <iframe
                    src={fileUrl || ''}
                    style={{
                      width: `${100 * zoom}%`,
                      height: `${500 * zoom}px`,
                    }}
                    title="PDF Viewer"
                  />
                ) : (
                  <img
                    src={fileUrl || ''}
                    alt="File Content"
                    style={{
                      width: '100%',
                      maxWidth: '100%',
                      height: '500px',
                      objectFit: 'contain',
                      transform: `scale(${zoom})`,
                      transformOrigin: 'center',
                      transition: 'transform 0.2s ease',
                    }}
                  />
                )}
              </DialogContent>
              <DialogActions>
                 <Box display="flex" justifyContent="center" flexGrow={1} gap={1} width="100%">
                  <Button
                    variant="outlined"
                    size="small"
                    onClick={handleZoomOut}
                    sx={{ minWidth: '36px', fontSize:'16px' }}
                  >
                    -
                  </Button>
                  <Button
                    variant="outlined"
                    size="small"
                    onClick={handleResetZoom}
                    sx={{ minWidth: '60px' }}
                  >
                    Reset
                  </Button>
                  <Button
                    variant="outlined"
                    size="small"
                    onClick={handleZoomIn}
                    sx={{ minWidth: '36px',  fontSize:'16px' }}
                  >
                    +
                  </Button>
                </Box>
            
                <Button onClick={handleCloseModal} color="primary">Close</Button>
              </DialogActions>
            </Dialog>


              <Grid
                spacing={5}
                p={"18px"}
                py={4}
                justifyContent={"end"}
                container
                textAlign={"center"}
                alignContent={"center"}
                alignItems={"center"}
              >
                <Grid
                  sx={{
                    textAlign: "end",
                    justifyContent: "flex-end",
                    alignItems: "flex-end",
                  }}
                >

                  {/* <Pagination
                    count={Math.ceil(filteredExpenses.length / rowsPerPage)}
                    page={page}
                    rowsPerPage={rowsPerPage}
                    onPageChange={handleChangePage} /> */}


{/* View More Button */}
{filteredExpenses.length > rowsPerPage && (
  <Grid item sx={{ mt: 2 }}>
    <Button
      size="small"
      variant="outlined"
       color="secondary"
      className={classes.addButton}
      component={Link}
      to={`/expenses/${projectId}`}   // Target route
      target="_blank"
      sx={{
        minWidth: "40px",       
        padding: "6px 8px",     
        borderRadius: "6px",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <VisibilitySharpIcon fontSize="small" />  {/* Smaller icon */}
      <span style={{ marginLeft: 4 }}>View More</span>
    </Button>
  </Grid>
)}



                </Grid>

              </Grid>




            </TableContainer>
          


          </Card>
        </Grid>

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


  <Grid container spacing={4}  sx={{ marginTop: 2 }}>
    <Grid item xs={12} sm={12} md={12}>
    <Card className={classes.card}>



        <Grid
          container
          justifyContent={"space-between"}
          spacing={5}
          sx={{ borderBottom: 2, padding: 2 }}
          className={classes.titleGrid}
        >
          <Grid item lg={4} md={4} sm={4} xs={4} pt={2} alignContent={"center"}>
            <Typography className={classes.cardTitle}>Installment Expense</Typography>
          </Grid>
          <Grid
            item
            lg={8}
            md={8}
            sm={8}
            xs={8}
            sx={{ display: "flex", justifyContent: "flex-end" }}
          >
            <Grid
              container
              spacing={1}
              justifyContent="flex-end"
              sx={{ display: "flex" }}
            >

              <Grid item>
                <TextField
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <CiSearch className={classes.searchWidgetIcon} />
                      </InputAdornment>
                    ),
                    classes: {
                      root: classes.formControlList,
                    },
                  }}
                  fullWidth
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Expense Name .."
                  sx={{ width: "100%" }}
                  size="small" />
              </Grid>


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



        <Grid item lg={12} md={12} sm={12} xs={12}>
          <Card >
          <TableContainer
      sx={{
        maxHeight: 450, // Fixed height for the table
        overflowY: 'auto', // Enables vertical scrolling
      }}
      className={classes.thinScrollbar} 
      >
              <Table className={classes.table}>
                <TableHead className={classes.tableHeaderRow}>
                  <TableRow>
                    <TableCell className={classes.tablheader}> </TableCell>
                    <TableCell className={classes.tablheader}> <strong>Date</strong></TableCell>
                    <TableCell className={classes.tablheader}> <strong>Details</strong></TableCell>
                    <TableCell className={classes.tablheader}><strong>Category</strong></TableCell>
                    <TableCell className={classes.tablheader}> <strong>Amount</strong></TableCell>
                    <TableCell className={classes.tablheader}><strong>Hst</strong></TableCell>
                    <TableCell className={classes.tablheader}><strong>Total</strong></TableCell>
                    <TableCell className={classes.tablheader}><strong>Paid Amt</strong></TableCell>
                    <TableCell className={classes.tablheader}><strong>Due Amt</strong></TableCell>
                    <TableCell className={classes.tablheader}><strong>Status</strong></TableCell>
                   
                    {/* <TableCell className={classes.tablheader}><strong>Invoice File</strong></TableCell> */}
                    <TableCell className={classes.tablheader} sx={{ textAlign: "right" }}>
                      <strong>Actions</strong>
                    </TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {filteredExpenses.length > 0 ? (
                 filteredExpenses
                 .sort((a, b) => {
                  const dateA = new Date(a.date).getTime();
                  const dateB = new Date(b.date).getTime();
              
                  // First sort by date (descending)
                  if (dateB !== dateA) {
                    return dateB - dateA;
                  }
              
                  // If the dates are the same, sort by ID (ascending)
                  return b.id - a.id;
                })
                 .filter(expense => expense.installment == 1 )
                   .map((expense) => {

                        let installments = Array.isArray(expense.installment_details)
          ? expense.installment_details
          : expense.installment_details
          ? JSON.parse(expense.installment_details)
          : [];

        const paidAmount = installments.reduce(
          (sum :any, inst: any) => sum + Number(inst.amount),
          0
        );
             const dueAmount = Number(expense.total) - paidAmount;

        const isFullyPaid = dueAmount <= 0;
           const isExpanded = expandedExpenseId === expense.id;

                    return (
                      <><TableRow key={expense.id}>
                        <TableCell scope="row" className={classes.tablCell}>
                          <IconButton
                            size="small"
                            onClick={() => handleToggleExpand(expense.id)}
                          >
                            {isExpanded ? <ExpandLessIcon /> : <ExpandMoreIcon />}
                          </IconButton>
                        </TableCell>
                        <TableCell scope="row" className={classes.tablCell}>{expense.date}</TableCell>
                        <TableCell scope="row" className={classes.tablCell}>
                          <Box display="flex" alignItems="center">
                            {/* Details text */}
                          <span
      style={{ cursor: "pointer", textDecoration: "underline" }}
     onClick={() =>
    navigate(`/installmentExpense/${expense.id}`, {
      state: { projectId },
    })
  }
    >
      {expense.description}
    </span>
                            {expense.file && expense.file.length > 0 && (
                              <Box display="flex" marginLeft={1}>
                                {parseFiles(expense.file).map((file, index) => (
                                  <Button
                                    key={index}
                                    variant="text"
                                    className={classes.viewInvoiceButton}
                                    size="small"
                                    onClick={() => handleOpenModal(file)}
                                    sx={{
                                      minWidth: "auto",
                                      padding: 0,
                                      marginRight: 1, // Add space between icons
                                    }}
                                  >
                                    <DescriptionIcon style={{ fontSize: 16 }} />
                                  </Button>
                                ))}

                              </Box>
                            )}
                          </Box>
                        </TableCell>



                        <TableCell scope="row" className={classes.tablCell}>{categoryMap[expense.category] || "Unknown"}</TableCell>
                        <TableCell scope="row" className={classes.tablCell}>{expense.amount}</TableCell>
                        <TableCell scope="row" className={classes.tablCell}>{expense.hst}</TableCell>
                        <TableCell scope="row" className={classes.tablCell}>{expense.total}  </TableCell>
                        <TableCell className={classes.tablCell}>
                          {paidAmount.toFixed(2)}
                        </TableCell>
                        <TableCell className={classes.tablCell}>
                          {dueAmount.toFixed(2)}
                        </TableCell>
                        <TableCell scope="row" className={classes.tablCell}>
                          <Box display="flex" alignItems="center">
                            {/* <Box
      sx={{
        width: 10,
        height: 10,
        borderRadius: '50%',
        backgroundColor: String(expense.status) === 'Paid' ? 'green' : 'red', // Ensure expense.status is a string
        marginRight: 1, // Space between dot and text
      }}
    /> */}
                       {!isFullyPaid ? (
  <Button
    variant="contained"
    onClick={() => handlePay(expense)}
    style={{
      backgroundColor: '#007BFF',
      color: '#fff',
      borderRadius: '8px',
      padding: '2px 2px',
      // marginLeft: '8px',
      fontSize: '0.7rem',
      fontWeight: '500',
      cursor: 'pointer',
    }}
  >
    Pay
  </Button>

  
) : (
  <Typography
    variant="body2"
    color="textSecondary"
    sx={{
      backgroundColor: 'lightgreen',
      padding: '2px 8px',
      borderRadius: 2,
      display: 'inline-block',
    }}
  >
   Paid
  </Typography>
)}

                          </Box>
                        </TableCell>



                        <TableCell scope="row" className={classes.tablCell}>
                          <Grid
                            container
                            spacing={1}
                            sx={{ display: "flex", justifyContent: "flex-end" }}
                          >



                            <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="contained"
                                    className={classes.viewButtonList}
                                    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);
                                    } }

                                  >
                                    <VisibilitySharpIcon className={classes.viewListIcon} />
                                  </Button>
                                )}



                            </Grid>
                            <Grid item>
                              <Button
                                variant="contained"
                                className={classes.editButtonList}
                                onClick={() => handleEditClick(expense.id)}
                                sx={{
                                  marginLeft: "auto", // Pushes the edit button to the right
                                }}
                              >
                                <EditSharpIcon className={classes.editListIcon} style={{ fontSize: 20 }} />
                              </Button>
                            </Grid>
                            {/* <Grid item>
                              {!isFullyPaid && (
                                <Button
                                  variant="contained"
                                  className={classes.editButtonList}
                                  onClick={() => handlePay(expense)}
                                >
                                  <PaymentIcon className={classes.editListIcon} style={{ fontSize: 20 }} />
                                </Button>
                              )}
                            </Grid> */}
                          </Grid>

                          {/* </Box> */}

                        </TableCell>
                      </TableRow><TableRow>
                          <TableCell
                            style={{ paddingBottom: 0, paddingTop: 0 }}
                            colSpan={11} // Make it span all columns
                          >
                         <Collapse in={isExpanded} timeout="auto" unmountOnExit>
  <Box margin={2} display="flex" flexDirection="column" gap={2}>
    <Typography variant="subtitle1" gutterBottom>
      Installment Details
    </Typography>

    {installments.length === 0 && (
      <Typography color="textSecondary">No installments made yet.</Typography>
    )}

    {installments.map((inst: any, idx: any) => (
      <><Box
        key={idx}
        sx={{
          border: "1px solid #ddd",
          borderRadius: 2,
          padding: 2,
          backgroundColor: "#f9f9f9",
          boxShadow: "0 2px 5px rgba(0,0,0,0.05)",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          flexWrap: "wrap",
          gap: 2,
        }}
      >
        <Typography variant="body2" sx={{ minWidth: 100 }}>
          <strong>Date:</strong> {inst.date}
        </Typography>
        <Typography variant="body2" sx={{ minWidth: 80 }}>
          <strong>Amount:</strong> ${parseFloat(inst.amount).toFixed(2)}
        </Typography>
         <Typography variant="body2" sx={{ minWidth: 80 }}>
          <strong>Mode:</strong> {inst.paymentMode || "-"}
        </Typography>
        <Typography variant="body2" sx={{ flexGrow: 1, minWidth: 150 }}>
          <strong>Description:</strong> {inst.description || "-"}
        </Typography>
         
            {/* <Grid item>
            <IconButton color="primary" onClick={() => handleInstallmentEditClick(expense,idx)}>
             <FaEdit  style={{ fontSize: 18 }}/>
             </IconButton>
            </Grid> */}
             <Grid item>
            <IconButton color="primary" onClick={() => handleInstallmentDeleteClick(expense,idx)}>
             <FaUndo style={{ fontSize: 16 }} />
            </IconButton>
                                                   
        </Grid>
        
      </Box>
       
       </>
    ))}
  </Box>
</Collapse>

                          </TableCell>
                        </TableRow></>

)})
                  ) : (

                    <TableRow>

                      <TableCell colSpan={7} align="center">
                        No Data Available
                      </TableCell>

                    </TableRow>

                  )}




                  {/* <TableRow>

                    <TableCell colSpan={3} align="right">
                      <strong>Total </strong>
                    </TableCell>

                    <TableCell>{totalAmount.toFixed(2)}</TableCell>
                  
                    <TableCell>{totalHst.toFixed(2)}</TableCell>
                    <TableCell colSpan={2}>
                      {totalAmountWithTax.toFixed(2)}
                    </TableCell>
                  </TableRow> */}
                </TableBody>

              </Table>

           {/* <Dialog open={openModal} onClose={handleCloseModal} fullWidth maxWidth="md">
                <DialogTitle>View File</DialogTitle>
                <DialogContent>

                {isPdf ? (
          <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> */}


              <Grid
                spacing={5}
                p={"18px"}
                py={4}
                justifyContent={"end"}
                container
                textAlign={"center"}
                alignContent={"center"}
                alignItems={"center"}
              >
                <Grid
                  sx={{
                    textAlign: "end",
                    justifyContent: "flex-end",
                    alignItems: "flex-end",
                  }}
                >

                  <Pagination
                    count={Math.ceil(filteredExpenses.length / rowsPerPage)}
                    page={page}
                    rowsPerPage={rowsPerPage}
                    onPageChange={handleChangePage} />




                </Grid>

              </Grid>




            </TableContainer>
          


          </Card>
        </Grid>

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

      <Grid container spacing={4} justifyContent="center" sx={{ marginTop: 1 }}>
      {/* {Object.entries(categoryData).map(([categoryName, totalAmount]) => { */}
      {Object.entries(categoryData)
  .sort(([a], [b]) => a.localeCompare(b))  // Alphabetical sort
  .map(([categoryName, totalAmount]) => { 
       const pieData = calculatePieData(categoryName); 

       const categoryId = Object.entries(categoryMap).find(
  ([id, name]) => name === categoryName
)?.[0];

const categoryIdNumber = categoryId ? Number(categoryId) : null;
        return (
          <Grid item xs={12} sm={4} md={4} key={categoryName}>
            <Card elevation={3} sx={{ height: '510px', display: 'flex', flexDirection: 'column' }}>
              <CardContent sx={{ flex: 1, display: 'flex', flexDirection: 'column', position: 'relative' }}>
                <Grid container direction="column" alignItems="center" justifyContent="space-between">
                 
        
              <Box sx={{ position: 'relative', width: '100%', mt: 2 }}>
  <Typography
    variant="body2"
    align="center"
    sx={{ fontWeight: 'bold', fontSize: '15px' }}
  >
    {categoryName}
  </Typography>
   {/* <Link 
                           to={`/project/${projectId}/category/${categoryIdNumber}`}
                  style={{ textDecoration: 'none', marginLeft: "6px", color: 'inherit' }}
                > 
                  <LinkIcon fontSize="small" style={{ verticalAlign: "middle" }} />
                </Link> */}

                 <Button
  size="small"
  variant="contained"
  color="secondary"
  // onClick={() => navigate(`/expenses/${projectId}`)}
   component={Link}
    to={`/project/${projectId}/category/${categoryIdNumber}`}
   // target="_blank" 
   sx={{
    position: 'absolute',
    top: 0,
    right: 0,
    minWidth: "40px",
    padding: "2px 8px",
    borderRadius: "6px",
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
  }}
>
  <VisibilitySharpIcon fontSize="small" />  {/* Smaller icon */}
</Button>

           
</Box>

                 <Grid container direction="row" alignItems="center" spacing={2} sx={{ marginTop: '10px' }}>
       
          <Grid item md={8} sx={{ display: 'flex', justifyContent: 'center' }}>
            <Box sx={{ width: '150px', height: '150px' }}>
            <Pie
  data={calculatePieData(categoryName)}
  options={{
    plugins: {
      tooltip: {
        callbacks: {
             label: function (tooltipItem) {
            const { dataIndex, dataset, label } = tooltipItem;
            const value = dataset.data[dataIndex] as number;
            const total = dataset.data.reduce((a, b) => a + b, 0);
            const percentage = ((value / total) * 100).toFixed(2);
            //return `${label}: $${value.toFixed(2)} (${percentage}%)`;
               return `$${value.toFixed(2)} (${percentage}%)`;
          },
        },
      },
      legend: {
       
        display: true,
        labels: {
          color: '#000',
           boxWidth: 12,
        
        },
      },
    },
  }}
/>

            </Box>
          </Grid>

       
          <Grid item md={3} sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
            <Box sx={{ textAlign: 'center' }}>
            <Typography variant="body2" >
                Total  {expenses.filter((expense) => categoryMap[expense.category] === categoryName).length}
              </Typography>
              <Typography variant="h3" sx={{ fontSize: '1.2rem'}}>
                {((categoryData[categoryName] / overallExpense ) * 100).toFixed(2)}%
          
           
              </Typography>
             
            </Box>
          </Grid>
        </Grid>

                
                  <Box
                    sx={{
                      flex: 1,
                      overflowY: 'auto',
                      maxHeight: '200px', 
                      width: '100%',
                      marginTop: 2, 
                    }}
                    className={classes.thinScrollbar}
                  >
                    <Grid container direction="column" spacing={2}>
                      {expenses
  .filter((expense) => categoryMap[expense.category] === categoryName)
  .map((expense, index) => {
    const type = expense.type || "Other";

    // Get pie chart data for the category
    const pieData = calculatePieData(categoryName);

    // Map type to pie chart color
    let bgColor = "#607d8b"; // default color
    if (pieData.labels && pieData.datasets[0]) {
      const typeIndex = pieData.labels.indexOf(type);
      if (typeIndex !== -1) {
        bgColor = pieData.datasets[0].backgroundColor[typeIndex % pieData.datasets[0].backgroundColor.length];
      }
    }

    return (
      <Grid item key={index} container justifyContent="space-between" alignItems="center">
        {/* Left: Description with colored type badge */}
        <Grid item xs={8}>
          <Typography variant="body2" sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
            <span>
              {expense.date}  <Box
              component="span"
              sx={{
                display: "inline-flex",
                width: 18,
                height: 18,
                borderRadius: "50%",
                backgroundColor: bgColor,
                color: "#fff",
                fontSize: "0.75rem",
                fontWeight: 700,
                alignItems: "center",
                justifyContent: "center",
                ml: 0.5,
                boxShadow: "0 1px 3px rgba(0,0,0,0.3)",
              }}
            >
              {/* {type[0].toUpperCase()} */}
               {expense.type === "Material + Labour" ? "ML" : (expense.type || "Other")[0].toUpperCase()}
            </Box><br /> {expense.description}
            </span>
           
          </Typography>
        </Grid>

        {/* Right: Total */}
        <Grid item xs={4} textAlign="right">
          <Typography variant="body2">${netTotal(expense).toFixed(2)}</Typography>
        </Grid>

        {index < expenses.length - 1 && (
          <Grid item xs={12}>
            <Box sx={{ borderBottom: "1px solid #ccc", my: 1 }} />
          </Grid>
        )}
      </Grid>
    );
  })}

                    </Grid>
                  </Box>

               
                  <Grid container justifyContent="space-between" sx={{ padding: '16px', position: 'absolute', bottom: 0, left: 0, right: 0 }}>
          <Grid item xs={6}>
            <Typography variant="h6">Total Expense:</Typography>
            <Typography variant="body2" sx={{ fontSize: "1.00rem" }}>
              ${categoryData[categoryName]?.toFixed(2) || "0.00"}
            </Typography>
          </Grid>

          <Grid item xs={6} textAlign="right">
            <Typography variant="h6">Total HST:</Typography>
            <Typography variant="body2" sx={{ fontSize: "1.00rem" }}>
             
              ${((categoryHST[categoryName] ?? 0) as number).toFixed(2)}
            </Typography>
          </Grid>
        </Grid>

                </Grid>
              </CardContent>
            </Card>
          </Grid>
        );
      })}
    </Grid>


<Dialog open={modalOpen} onClose={() => setModalOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>Add Installment for  {categoryMap[selectedExpense?.category as keyof typeof categoryMap] || ""} ({selectedExpense?.description})</DialogTitle>
        <DialogContent>

 {/* <Typography variant="subtitle1" gutterBottom>
                <strong>Description:</strong> {selectedExpense?.description}
              </Typography>
              <Typography variant="subtitle1" gutterBottom>
              <strong>Category:</strong> {categoryMap[selectedExpense?.category as keyof typeof categoryMap] || ""}

              </Typography> */}

          <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 (selectedExpense) {
    if (typeof selectedExpense.installment_details === 'string') {
      existingInstallments = JSON.parse(selectedExpense.installment_details) as Installment[];
    } else if (Array.isArray(selectedExpense.installment_details)) {
      existingInstallments = selectedExpense.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(selectedExpense?.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"
            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>



<Dialog open={openPrint} onClose={() => setOpenPrint(false)} maxWidth="md" fullWidth>

<DialogTitle>
{selectedGroup?.group_name} Expenses
</DialogTitle>

<DialogContent id="print-section">

<table border={1} cellPadding={5} style={{ width: "100%" }}>
<thead>
<tr>
<th>Date</th>
<th>Description</th>
<th>Category</th>
<th>Type</th>
<th>Amount</th>
</tr>
</thead>

<tbody>
{expenses
.filter(
(e:any)=>
selectedGroup?.category_ids.includes(Number(e.category)) &&
Number(e.installment) !== 1
)
.map((e:any,i:number)=>(
<tr key={i}>
<td>{e.date}</td>
<td>{e.description}</td>
<td>{categoryMap[e.category]}</td>
<td>{e.type}</td>
<td>${Number(e.total).toFixed(2)}</td>
</tr>
))}
</tbody>
</table>

</DialogContent>

<DialogActions>
<Button onClick={()=>setOpenPrint(false)}>Close</Button>
<Button variant="contained" onClick={handlePrint}>
Print
</Button>
</DialogActions>

</Dialog>

<Dialog open={returnModalOpen} onClose={() => setReturnModalOpen(false)} maxWidth="sm" fullWidth>
  <DialogTitle>
    Return Item — {selectedExpense?.description}
  </DialogTitle>
  <DialogContent>
    <Typography variant="body2" color="textSecondary" sx={{ mb: 2 }}>
      Original Total: <strong>${Number(selectedExpense?.total ?? 0).toFixed(2)}</strong>
      {Number(selectedExpense?.return_amount) > 0 && (
        <> &nbsp;| Already Returned: <strong style={{ color: '#FF5722' }}>${Number(selectedExpense?.return_amount).toFixed(2)}</strong></>
      )}
    </Typography>
    <TextField
      fullWidth
      margin="dense"
      label="Return Date"
      type="date"
      InputLabelProps={{ shrink: true }}
      value={returnData.date}
      onChange={(e) => setReturnData({ ...returnData, date: e.target.value })}
    />
    <TextField
      fullWidth
      margin="dense"
      label="Return Amount"
      type="number"
      value={returnData.amount}
      onChange={(e) => {
        const val = e.target.value;
        const entered = parseFloat(val);
        const alreadyReturned = Number(selectedExpense?.return_amount ?? 0);
        const maxReturn = Number(selectedExpense?.total ?? 0) - alreadyReturned;
        if (!isNaN(entered) && entered > maxReturn) {
          showErrorMessage(`Return amount cannot exceed total $${maxReturn.toFixed(2)}`);
          return;
        }
        setReturnData({ ...returnData, amount: val });
      }}
    />
    <TextField
      fullWidth
      margin="dense"
      label="Reason for Return"
      multiline
      rows={3}
      value={returnData.reason}
      onChange={(e) => setReturnData({ ...returnData, reason: e.target.value })}
    />
  </DialogContent>
  <DialogActions sx={{ p: 3, gap: 2 }}>
    <Grid container spacing={3}>
      <Grid item lg={12} md={12} sm={12} xs={12} sx={{ display: "flex", justifyContent: "flex-end" }}>
        <Button variant="outlined" startIcon={<CloseIcon />} onClick={() => setReturnModalOpen(false)}>
          Cancel
        </Button>
        <Box m={0.5} />
        <Button
          variant="contained"
          startIcon={<SaveAltIcon />}
          sx={{ backgroundColor: '#FF5722' }}
          onClick={handleReturnExpense}
        >
          Confirm Return
        </Button>
      </Grid>
    </Grid>
  </DialogActions>
</Dialog>

      </>




       

  );
};

export default Index;