import React, { useEffect, useMemo, useState } from "react"; import Chart from "react-apexcharts"; import { useExpenseAnalysis } from "../../hooks/useDashboard_Data"; import { useSelectedProject } from "../../slices/apiDataManager"; import { DateRangePicker1 } from "../common/DateRangePicker"; import { FormProvider, useForm } from "react-hook-form"; import { formatCurrency, localToUtc } from "../../utils/appUtils"; import { useProjectName } from "../../hooks/useProjects"; import { SpinnerLoader } from "../common/Loader"; import flatColors from "../Charts/flatColor"; const ExpenseAnalysis = () => { const projectId = useSelectedProject(); const [projectName, setProjectName] = useState("All Project"); const { projectNames } = useProjectName(); const methods = useForm({ defaultValues: { startDate: "", endDate: "" }, }); useEffect(() => { if (projectId && projectNames?.length) { const project = projectNames.find((p) => p.id === projectId); setProjectName(project?.name || "All Project"); } else { setProjectName("All Project"); } }, [projectNames, projectId]); const { watch } = methods; const [startDate, endDate] = watch(["startDate", "endDate"]); const { data, isLoading, isError, error, isFetching } = useExpenseAnalysis( projectId, startDate ? localToUtc(startDate) : null, endDate ? localToUtc(endDate) : null ); if (isError) return
{error.message}
; const report = data?.report ?? []; const { labels, series, total } = useMemo(() => { const labels = report.map((item) => item.projectName); const series = report.map((item) => item.totalApprovedAmount || 0); const total = formatCurrency(data?.totalAmount || 0); return { labels, series, total }; }, [report, data?.totalAmount]); const donutOptions = { chart: { type: "donut" }, labels, legend: { show: false }, tooltip: { y: { formatter: (value) => formatCurrency(value), }, }, dataLabels: { enabled: true, formatter: (val) => `${val.toFixed(0)}%` }, colors: flatColors, plotOptions: { pie: { donut: { size: "70%", labels: { show: true, total: { show: true, label: "Total", fontSize: "16px", formatter: () => `${total}`, }, }, }, }, }, responsive: [ { breakpoint: 576, // mobile breakpoint options: { chart: { width: "100%" }, }, }, ], }; return ( <>
Expense Breakdown

{projectName}

{isLoading && (
)} {!isLoading && report.length === 0 && (
No data found
)} {!isLoading && report.length > 0 && ( <> {isFetching && (
Loading...
)}
{/* Chart Column */}
{/* Data/Legend Column */}
{report.map((item, idx) => (
{item.projectName} {formatCurrency(item.totalApprovedAmount)}
))}
)}
); }; export default ExpenseAnalysis;