import React from "react";
import { useGetSalesReportQuery } from "../../features/report/salesAPI";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";

const SalesReport = () => {
  const { data, isLoading, isError, error } = useGetSalesReportQuery();
  console.log(error);
  if (isLoading)
    return <p className="p-6 text-center">Loading sales data...</p>;
  if (isError)
    return (
      <p className="p-6 text-center text-red-500">Error loading sales data.</p>
    );

  const dailyData = Object.entries(data?.data?.dailySales || {}).map(
    ([date, value]) => ({
      date,
      sales: value,
    })
  );

  const monthlyData = Object.entries(data?.data?.monthlySales || {}).map(
    ([month, value]) => ({
      month,
      sales: value,
    })
  );

  return (
    <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">
      {/* Daily Sales Card */}
      <div className="p-6 bg-white shadow rounded-lg">
        <h2 className="text-lg font-bold mb-4">Daily Sales</h2>
        {dailyData.length ? (
          <ResponsiveContainer width="100%" height={300}>
            <LineChart data={dailyData}>
              <CartesianGrid stroke="#e0e0e0" strokeDasharray="5 5" />
              <XAxis dataKey="date" />
              <YAxis />
              <Tooltip />
              <Line
                type="monotone"
                dataKey="sales"
                stroke="#4f46e5"
                strokeWidth={2}
              />
            </LineChart>
          </ResponsiveContainer>
        ) : (
          <p>No daily sales data.</p>
        )}
      </div>

      {/* Monthly Sales Card */}
      <div className="p-6 bg-white shadow rounded-lg">
        <h2 className="text-lg font-bold mb-4">Monthly Sales</h2>
        {monthlyData.length ? (
          <ResponsiveContainer width="100%" height={300}>
            <LineChart data={monthlyData}>
              <CartesianGrid stroke="#e0e0e0" strokeDasharray="5 5" />
              <XAxis dataKey="month" />
              <YAxis />
              <Tooltip />
              <Line
                type="monotone"
                dataKey="sales"
                stroke="#16a34a"
                strokeWidth={2}
              />
            </LineChart>
          </ResponsiveContainer>
        ) : (
          <p>No monthly sales data.</p>
        )}
      </div>
    </div>
  );
};

export default SalesReport;
