import React, { useEffect, useMemo, useState,useRef} from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableFooter,
  TableHead,
  TableRow,
  CircularProgress,
  Grid,
  Box,
  Button,
  Typography,
  TextField,
  MenuItem,
  InputAdornment,
  Card,
  Dialog,
  DialogActions, DialogContent, DialogTitle, CardContent,Paper, Stack, Chip, Divider, Select
} from "@mui/material";
import { FaMoneyBillWave, FaPlusCircle ,FaFileAlt, FaClipboardList , FaChartPie , FaCog , FaMoneyCheckAlt, 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 { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import dayjs from "dayjs";
import ReactToPrint from "react-to-print";
import LocalPrintshopSharpIcon from "@mui/icons-material/LocalPrintshopSharp";
import DownloadIcon from '@mui/icons-material/Download';
import * as XLSX from "xlsx"

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;
  updated_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;
}



const Index = () => {
  const classes = useStyles();
  const navigate = useNavigate();
  const { projectId } = useParams();
  const [expenses, setExpenses] = useState<Expense[]>([]); 
  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 [selectedCategory, setSelectedCategory] = useState('');
const [selectedType, setSelectedType] = useState('');
const [selectedDateFilter, setSelectedDateFilter] = useState(''); 
const [dateFilter, setDateFilter] = useState<string>("");
const [startDate, setStartDate] = useState<string>("");
const [endDate, setEndDate] = useState<string>("");
const [customDateRange, setCustomDateRange] = useState<[Date | null, Date | null]>([null, null]);
const componentRef = useRef<HTMLDivElement>(null);
const [zoom, setZoom] = useState(1);

const [returnModalOpen, setReturnModalOpen] = useState(false);
const [returnData, setReturnData] = useState({
  date: new Date().toLocaleDateString("en-CA", { timeZone: "America/Toronto" }),
  amount: "",
  reason: "",
});

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


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) => {
  // --- Search Query Filter ---
  const matchesSearch =
    expense.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
    (categoryMap[expense.category] || "")
      .toLowerCase()
      .includes(searchQuery.toLowerCase());

  // --- Category Filter ---
  const matchesCategory = selectedCategory
     ? expense.category.toString() === selectedCategory
    : true;

  // --- Type Filter ---
  const matchesType = selectedType
    ? expense.type === selectedType
    : true;

     const excludeInstallment = expense.installment !== 1;

  // --- Date Filter ---
  const matchesDate = 
  !dateFilter || 
  (expense.date && (() => {
    const expenseDate = new Date(expense.date).toLocaleDateString("en-CA");
    const startDateString = startDate ? new Date(startDate).toLocaleDateString("en-CA") : null;
    const endDateString = endDate ? new Date(endDate).toLocaleDateString("en-CA") : null;

    if (!startDateString || !endDateString) return true; // no custom dates selected
    return expenseDate >= startDateString && expenseDate <= endDateString;
  })());

  // --- Combine All Filters ---
  return matchesSearch && matchesCategory && matchesType  
   && excludeInstallment 
  && matchesDate;
});



// const totalHst = filteredExpenses.reduce((sum, expense) =>  {
//   return sum + (Number(expense.hst) || 0);
// }, 0);

const totalHst = filteredExpenses.reduce((sum, expense) =>  {
  return sum + (Number(expense.hst) || 0);
}, 0);

// const totalAmount = filteredExpenses.reduce((sum, expense) => {
//   return sum + (Number(expense.amount) || 0);
// }, 0);

const totalAmount = filteredExpenses.reduce((sum, expense) => {
  const returned = Number(expense.return_amount) || 0;
  return sum + (Number(expense.amount) || 0) - returned;
}, 0);




// const totalAmountWithTax = filteredExpenses.reduce((sum, expense) => {
//   return sum + (Number(expense.total) || 0);
// }, 0);

const totalAmountWithTax = filteredExpenses.reduce((sum, expense) => {
  return sum + (Number(expense.total) || 0);
}, 0);



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

  };

    useEffect(() => {
        if (dateFilter !== "custom") {
          let start = "";
          let end = dayjs().format("YYYY-MM-DD");
    
          switch (dateFilter) {
            case "today":
              start = end;
              break;
            case "yesterday":
              start = dayjs().subtract(1, "day").format("YYYY-MM-DD");
              end = start;
              break;
            case "this_week":
              start = dayjs().startOf("week").format("YYYY-MM-DD");
              break;
            case "last_week":
              start = dayjs().subtract(1, "week").startOf("week").format("YYYY-MM-DD");
              end = dayjs().subtract(1, "week").endOf("week").format("YYYY-MM-DD");
              break;
            case "this_month":
              start = dayjs().startOf("month").format("YYYY-MM-DD");
              break;
            case "last_month":
              start = dayjs().subtract(1, "month").startOf("month").format("YYYY-MM-DD");
              end = dayjs().subtract(1, "month").endOf("month").format("YYYY-MM-DD");
              break;
            default:
              break;
          }
    
          setStartDate(start);
          setEndDate(end);
        }
      }, [dateFilter]);


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

 
  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 = expense.total;
      
      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 = expense.total;

      // 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 handleAddProductClick = () => {
    navigate(`/expense/create/${projectId}`);
  };

  const handleAddCategoryClick = () => {
    navigate(`/expense-category/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 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 hst = Number(expense.hst) || 0; // Use the existing value or default to 0
    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 + Number(expense.total), 0);
const paidExpense =  expenses
.filter(expense => String(expense.status) === 'Paid')  // Convert status to string
.reduce((total, expense) => total + expense.amount, 0); 


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 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 handleToggleExpand = (id: number) => {
  setExpandedExpenseId(expandedExpenseId === id ? null : id);
};

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,
      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.");
  }
};


const handleUpdateType = async (id: any, newType: any) => {
  try {
    await axios.post(`${API_URL}/expense/update-type/${id}`, {
      type: newType,
    });

    // Update UI instantly
    setExpenses((prev) =>
      prev.map((item) =>
        item.id === id ? { ...item, type: newType } : item
      )
    );

    showMessage("Type updated Successfully");
     fetchExpenses();
  } catch (err) {
    showErrorMessage("Error updating type");
  }
};


const isRecentlyUpdated = (expense: any) => {
  if (!expense.updated_at || !expense.created_at) return false;

  return expense.updated_at !== expense.created_at;
};


const handleExportToExcel = () => {
  if (!filteredExpenses.length) return;

  const exportData = filteredExpenses.map((row, index) => {
    return {
     

         "#": index + 1,
    "Date": row.date || "",
    "Details": row.description || "",
    "Category": categoryMap[row.category] || "Unknown",
    "Type": row.type || "",
    "Amount": Number(row.amount ?? 0).toFixed(2),
    "HST": Number(row.hst ?? 0).toFixed(2),
    "Total": Number(row.total ?? 0).toFixed(2),
    "Status": row.status || "",
    };
  });

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Expenses");
  XLSX.writeFile(workbook, "expenses.xlsx");
};





  return (

    
    <>


<div>
  
   <Grid container spacing={1} sx={{ marginTop: 1 }}>
     <Grid item xs={12}>
       <Card className={classes.card}>
         <Box mb={2} padding={2}>
           <Grid container spacing={2}>
        
             {/* <Grid item lg={2} md={2} sm={6} xs={12}>
             
             </Grid> */}


 <Grid item lg={2} md={2} sm={6} xs={12}>
  <Typography variant="subtitle1" sx={{ marginBottom: 1 }}>
    Category
  </Typography>
   <Select
      className={classes.textField}
      value={selectedCategory || ""}
      onChange={(event) => setSelectedCategory(event.target.value)}
      displayEmpty
      sx={{
        height: "37px",
        fontSize: "14px",
        padding: "4px",
        minWidth: "120px"
      }}
    >
    <MenuItem value="">All Categories</MenuItem>
      {Object.entries(categoryMap)
      .sort(([, a], [, b]) => a.toLowerCase().localeCompare(b.toLowerCase()))
      .map(([key, value]) => (
        <MenuItem key={key} value={key}>{value}</MenuItem>
      ))}
    </Select>
     
</Grid>

             <Grid item lg={2} md={2} sm={6} xs={12}>
  <Typography variant="subtitle1" sx={{ marginBottom: 1 }}>
   Type
  </Typography>
   <Select
      className={classes.textField}
      value={selectedType || ""}
      onChange={(event) => setSelectedType(event.target.value)}
      displayEmpty
      sx={{
        height: "37px",
        fontSize: "14px",
        padding: "4px",
        minWidth: "120px"
      }}
    >
      <MenuItem value="">All Types</MenuItem>
       <MenuItem value="Labour">Labour</MenuItem>
      <MenuItem value="Material">Material</MenuItem>
       <MenuItem value="Material + Labour">Material + Labour</MenuItem>
      <MenuItem value="Other">Other</MenuItem>
    </Select>
 
</Grid>

    
 
             {/* Select Date */}
             <Grid item lg={2} md={2} sm={6} xs={12}>
               <Typography variant="subtitle1" sx={{ marginBottom: 1 }}>
                 Select Date
               </Typography>
               <Select
                 className={classes.textField}
                 value={dateFilter}
                 onChange={(e) => setDateFilter(e.target.value)}
                 displayEmpty
                
                 sx={{
                  height: "37px",
                  fontSize: "14px",
                  padding: "4px",
                  minWidth: "120px"
                }}
               >
                 <MenuItem value="">Select date filter</MenuItem>
                 <MenuItem value="today">Today</MenuItem>
                 <MenuItem value="yesterday">Yesterday</MenuItem>
                 <MenuItem value="this_week">This Week</MenuItem>
                 <MenuItem value="last_week">Last Week</MenuItem>
                 <MenuItem value="this_month">This Month</MenuItem>
                 <MenuItem value="last_month">Last Month</MenuItem>
                 <MenuItem value="custom">Custom</MenuItem>
               </Select>
             </Grid>
 
             {/* Custom Date Fields (Shown Only If "Custom" Is Selected) */}
             {dateFilter === "custom" && (
               <>
                 <Grid item lg={2} md={2} sm={6} xs={12}>
                   <Typography variant="subtitle1" sx={{ marginBottom: 1 }}>
                     Start Date
                   </Typography>
                   <TextField
                   variant="outlined"
                     type="date"
                     size="small"
                    className={classes.textField}
                     value={startDate}
                     onChange={(e) => setStartDate(e.target.value)}
                     InputLabelProps={{ shrink: true }}
                     
                   />
                 </Grid>
                 <Grid item lg={2} md={2} sm={6} xs={12}>
                   <Typography variant="subtitle1" sx={{ marginBottom: 1 }}>
                     End Date
                   </Typography>
                   <TextField
                     type="date"
                     size="small"
                    className={classes.textField}
                     value={endDate}
                     onChange={(e) => setEndDate(e.target.value)}
                     InputLabelProps={{ shrink: true }}
              
                   />
                 </Grid>
               </>
             )}
           </Grid>
         </Box>
       </Card>
     </Grid>
   </Grid>
 </div>


    
    <Grid container spacing={4}  >
    <Grid item xs={12} sm={12} md={12}>
             <div ref={componentRef}>
    <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 sx={{ '@media print': {
                  display: 'none',
                } }}>
                <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 .."
                  sx={{ width: "100%" }}
                  size="small" />
              </Grid>


              {filteredExpenses.length > 0 && (
                 <>
                     <Grid item sx={{ '@media print': {
                  display: 'none',
                } }}>
                            <Button
                              variant="contained"
                              className={classes.addButton}
                              onClick={handleAddProductClick}
                            >
                              Add Expense
                            </Button>
           </Grid>

                <Grid item sx={{ '@media print': {
                  display: 'none',
                } }}>
                  <ReactToPrint
                    trigger={() => (
                      <Button
                        variant="contained"
                        startIcon={<LocalPrintshopSharpIcon />}
                        className={classes.addButton}
                      >
                        Print
                      </Button>
                    )}
                    content={() => componentRef.current}
                  />
                </Grid>

                              <Grid item sx={{ '@media print': {
                    display: 'none',
                  } }}>
                        <Button
                          variant="contained"
                          startIcon={<DownloadIcon />} // You can use any icon you like
                          className={classes.addButton}
                          onClick={handleExportToExcel}
                        >
                          Excel
                        </Button>
                      </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}`)}
  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>
          </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",
    '@media print': {
      display: 'none',
    },
  }}
>
                      <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;
                // })
                  .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}  sx={{ '@media print': {
                  display: 'none',
                } }}>
        {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}>
                          <span style={{ display: "inline-flex", alignItems: "center" }}>
                        <Link 
                           to={`/project/${projectId}/category/${expense.category}`}
                  style={{ textDecoration: 'none', marginLeft: "6px", color: 'inherit' }}
                > 
                         {categoryMap[expense.category] || "Unknown"}
                        
                  {/* <LinkIcon fontSize="small" style={{ verticalAlign: "middle" }} /> */}
                </Link>
                </span>
</TableCell>
                     <TableCell scope="row" className={classes.tablCell}>
{expense.type}


  {/* <Box display="flex" alignItems="center">
    
    <TextField
      select
      size="small"
      value={expense.type}
      onChange={(e) => handleUpdateType(expense.id, e.target.value)}
      InputLabelProps={{ shrink: true }}
      sx={{ width: 160 }} 
    >
      <MenuItem value="Labour">Labour</MenuItem>
      <MenuItem value="Material">Material</MenuItem>
      <MenuItem value="Material + Labour">Material + Labour</MenuItem>
      <MenuItem value="Other">Other</MenuItem>
    </TextField>

  
    <Box sx={{ width: 12, ml: 0.5 }}>
      {isRecentlyUpdated(expense) && (
        <Typography
          sx={{
            fontSize: "10px",
            fontWeight: "bold",
            color: "#D48806",
          }}
        >
          ✱
        </Typography>
      )}
    </Box>
  </Box> */}
</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" alignItems="center" flexWrap="wrap" gap={0.5}>
     <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>

    {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" }}
                        >
                   


<Grid item sx={{ '@media print': {
                  display: 'none',
                } }}>


{(
  (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  sx={{ '@media print': {
                  display: 'none',
                } }}>
    <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 sx={{ '@media print': { display: 'none' } }}>
      {(() => {
        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>

            

              <Grid
                spacing={5}
                sx={{ '@media print': { display: 'none',  } }}
                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={filteredExpenses.length}
                    page={page}
                    rowsPerPage={rowsPerPage}
                    onPageChange={handleChangePage} />

  
                </Grid>

              </Grid>




            </TableContainer>
          


          </Card>
        </Grid>

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

  {/* 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>
             

              <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>


<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;
