import React, { useState, useEffect } from "react";
import Chart from "react-apexcharts";
import { useSelector } from "react-redux";
import { useExpenseDataByProject } from "../../hooks/useDashboard_Data";
import { formatCurrency } from "../../utils/appUtils";
import { formatDate_DayMonth } from "../../utils/dateUtils";
import { useProjectName } from "../../hooks/useProjects";
import { useSelectedProject } from "../../slices/apiDataManager";
import { SpinnerLoader } from "../common/Loader";
import { useExpenseCategory } from "../../hooks/masterHook/useMaster";

const ExpenseByProject = () => {
  const projectId = useSelector((store) => store.localVariables.projectId);
  const [projectName, setProjectName] = useState("All Project");
  const [range, setRange] = useState("12M");
  const { projectNames, loading } = useProjectName();
  const [selectedType, setSelectedType] = useState("");
  const [viewMode, setViewMode] = useState("Category");
  const [chartData, setChartData] = useState({ categories: [], data: [] });
  const selectedProject = useSelectedProject();

  const {expenseCategories , loading: typeLoading } = useExpenseCategory();

  const { data: expenseApiData, isLoading } = useExpenseDataByProject(
    projectId,
    selectedType,
    range === "All" ? null : parseInt(range)
  );

  useEffect(() => {
    if (selectedProject && projectNames?.length) {
      const project = projectNames.find((p) => p.id === selectedProject);
      setProjectName(project?.name || "All Project");
    } else {
      setProjectName("All Project");
    }
  }, [projectNames, selectedProject]);

  useEffect(() => {
    if (expenseApiData) {
      const categories = expenseApiData.map((item) =>
        formatDate_DayMonth(item.monthName, item.year)
      );
      const data = expenseApiData.map((item) => item.total);
      setChartData({ categories, data });
    } else {
      setChartData({ categories: [], data: [] });
    }
  }, [expenseApiData]);

  const getSelectedTypeName = () => {
    if (!selectedType) return "All Types";
    const found = expenseCategories?.find((t) => t.id === selectedType);
    return found ? found.name : "All Types";
  };

  const options = {
    chart: { type: "bar", toolbar: { show: false } },
    plotOptions: {
      bar: { horizontal: false, columnWidth: "55%", borderRadius: 4 },
    },
    dataLabels: { enabled: true, formatter: (val) => formatCurrency(val) },
    xaxis: {
      categories: chartData.categories,
      labels: { style: { fontSize: "12px" }, rotate: -45 },
    },
    yaxis: {
      labels: {
        formatter: (val) => formatCurrency(val),
        style: { fontSize: "12px", colors: "#555" },
      },
    },
    tooltip: {
      y: {
        formatter: (val) => `${formatCurrency(val)} (${getSelectedTypeName()})`,
      },
    },

    annotations: { xaxis: [{ x: 0, strokeDashArray: 0 }] },
    fill: { opacity: 1 },
    colors: ["#2196f3"],
  };

  const series = [
    {
      name: getSelectedTypeName(),
      data: chartData.data,
    },
  ];

  return (
    <div className="card shadow-sm h-100 rounded ">
      {/* Header */}
      <div className="card-header">
        <div className="d-block justify-content-between align-items-center mb-1 mt-1">
          <div className="text-start">
            <h5 className="mb-1 me-6 card-title">Monthly Expense </h5>
            <div className="row w-100">
               <div className="col-6">          <p className="card-subtitle m-0">{projectName}</p></div>
               <div className="col-6  d-flex justify-content-between align-items-center px-0">

           
    
            <select
              className="form-select form-select-sm ms-auto  mt-sm-0"
              value={selectedType}
              onChange={(e) => setSelectedType(e.target.value)}
              disabled={typeLoading}
              style={{ maxWidth: "200px" }}
            >
              <option value="">All Categories</option>
              {expenseCategories?.map((type) => (
                <option key={type.id} value={type.id}>
                  {type.name}
                </option>
              ))}
            </select>
        
               </div>

  

          
            </div>

             
          </div>
        
        </div>

        {/* Range Buttons + Expense Dropdown */}
        <div className="d-flex align-items-center flex-wrap ">
          {["1M", "3M", "6M", "12M", "All"].map((item) => (
            <button
              key={item}
              className={`border-0 px-2 py-1 text-sm rounded ${range === item
                ? "text-white bg-primary"
                : "text-body bg-transparent"
                }`}
              style={{ cursor: "pointer", transition: "all 0.2s ease" }}
              onClick={() => setRange(item)}
            >
              {item}
            </button>
          ))}
          
        </div>
      </div>

      {/* Chart */}
      <div className="card-body bg-white text-dark p-3 rounded" style={{ minHeight: "210px" }}>
        {isLoading ? (
          <div className="d-flex justify-content-center align-items-center py-5">
            <SpinnerLoader />
          </div>
        ) : !expenseApiData || expenseApiData.length === 0 ? (
          <div className="text-center text-muted py-12">No data found</div>
        ) : (
          <Chart options={options} series={series} type="bar" height={235} />
        )}

      </div>

    </div>
  );
};

export default ExpenseByProject;
