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

const ExpenseAnalysis = () => {
  const projectId = useSelectedProject();
  const [projectName, setProjectName] = useState("All Project");
  const { projectNames, loading } = 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 <div>{error.message}</div>;

  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 },
    dataLabels: { enabled: true, formatter: (val) => `${val.toFixed(0)}%` },
    colors: ["#7367F0", "#28C76F", "#FF9F43", "#EA5455", "#00CFE8", "#FF78B8"],
    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 (
    <>
     
        <div className="card-header d-flex flex-column flex-sm-row justify-content-between align-items-start align-items-sm-center gap-2">
          <div className="text-start w-100">
            <h5 className="mb-1 card-title">Expense Breakdown</h5>
            {/* <p className="card-subtitle mb-0">Category Wise Expense Breakdown</p> */}
            <p className="card-subtitle m-0">{projectName}</p>
          </div>

          <div className="text-start text-sm-end w-75">
            <FormProvider {...methods}>
              <DateRangePicker1 />
            </FormProvider>
          </div>
        </div>

        {/* Card body */}
        <div className="card-body position-relative">
          {isLoading && (
            <div
              className="d-flex justify-content-center align-items-center"
              style={{ height: "200px" }}
            >
              <span>Loading...</span>
            </div>
          )}

          {!isLoading && report.length === 0 && (
            <div className="text-center py-5 text-muted">No data found</div>
          )}

          {!isLoading && report.length > 0 && (
            <>
              {isFetching && (
                <div className="position-absolute top-0 start-0 w-100 h-100 d-flex justify-content-center align-items-center bg-white bg-opacity-75">
                  <span>Loading...</span>
                </div>
              )}

              <div className="d-flex justify-content-center mb-3">
                <Chart
                  options={donutOptions}
                  series={series}
                  type="donut"
                  width="100%"
                  height={320}
                />
              </div>

              <div className="mb-2 w-100">
                <div className="row g-2">
                  {report.map((item, idx) => (
                    <div
                      className="col-12 col-sm-6 d-flex align-items-start"
                      key={idx}
                    >
                      <div className="avatar me-2">
                        <span
                          className="avatar-initial rounded-2"
                          style={{
                            backgroundColor:
                              donutOptions.colors[idx % donutOptions.colors.length],
                          }}
                        >
                          <i className="bx bx-receipt fs-4"></i>
                        </span>
                      </div>
                      <div className="d-flex flex-column gap-1 text-start">
                        <small className="fw-semibold">{item.projectName}</small>
                        <span className="fw-semibold text-muted ms-1">
                          {formatCurrency(item.totalApprovedAmount)}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </>
          )}
        </div>
   
      {/* Header */}

    </>
  );
};

export default ExpenseAnalysis;
