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




import React, { useState } from "react";
import { useGetSalesReportQuery } from "../../features/report/salesAPI";
import {
  AreaChart,
  Area,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Cell,
} from "recharts";

// ─── Styles ──────────────────────────────────────────────────────────────────
const styles = `
  @import url('https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,400;9..144,600;9..144,700&family=Instrument+Sans:wght@400;500;600&display=swap');

  :root {
    --bg:          #f7f5f2;
    --surface:     #ffffff;
    --surface2:    #faf9f7;
    --border:      #e8e4de;
    --border2:     #f0ece6;
    --text:        #1a1714;
    --muted:       #9c9489;
    --ink:         #2d2a26;
    --green:       #16803c;
    --green-bg:    #f0fdf4;
    --green-bdr:   #bbf7d0;
    --orange:      #c2410c;
    --orange-bg:   #fff7ed;
    --orange-bdr:  #fed7aa;
    --blue:        #1d4ed8;
    --blue-bg:     #eff6ff;
    --blue-bdr:    #bfdbfe;
    --red:         #e8442a;
    --red-bg:      #fdf1ef;
    --amber:       #d97706;
    --amber-bg:    #fffbeb;
    --slate:       #475569;
    --shadow:      0 1px 3px rgba(0,0,0,0.06), 0 4px 12px rgba(0,0,0,0.04);
    --shadow-lg:   0 2px 8px rgba(0,0,0,0.08), 0 12px 32px rgba(0,0,0,0.06);
  }

  * { box-sizing: border-box; margin: 0; padding: 0; }

  .sr-root {
    font-family: 'Instrument Sans', sans-serif;
    background: var(--bg);
    min-height: 100vh;
    color: var(--text);
    padding: 40px 36px;
  }

  /* ── Header ── */
  .sr-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    margin-bottom: 32px;
    flex-wrap: wrap;
    gap: 16px;
  }
  .sr-eyebrow {
    font-size: 0.68rem;
    font-weight: 600;
    letter-spacing: 0.14em;
    text-transform: uppercase;
    color: var(--muted);
    margin-bottom: 6px;
  }
  .sr-title {
    font-family: 'Fraunces', serif;
    font-size: 2.2rem;
    font-weight: 700;
    color: var(--ink);
    line-height: 1;
    letter-spacing: -0.02em;
  }

  /* ── Toggle ── */
  .sr-toggle {
    display: flex;
    gap: 2px;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 4px;
    box-shadow: var(--shadow);
    align-self: flex-end;
  }
  .sr-toggle-btn {
    padding: 7px 16px;
    border: none;
    background: transparent;
    border-radius: 7px;
    font-family: 'Instrument Sans', sans-serif;
    font-size: 0.78rem;
    font-weight: 600;
    color: var(--muted);
    cursor: pointer;
    transition: all 0.18s;
    letter-spacing: 0.02em;
  }
  .sr-toggle-btn:hover { color: var(--ink); }
  .sr-toggle-btn.active {
    background: var(--ink);
    color: #ffffff;
  }

  /* ── KPI strip ── */
  .sr-kpis {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 12px;
    margin-bottom: 28px;
  }
  .sr-kpi {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 14px;
    padding: 18px 20px;
    box-shadow: var(--shadow);
    position: relative;
    overflow: hidden;
    animation: riseIn 0.3s both;
  }
  .sr-kpi::before {
    content: '';
    position: absolute;
    bottom: 0; left: 0; right: 0;
    height: 3px;
    border-radius: 0 0 14px 14px;
  }
  .sr-kpi.kpi-green::before  { background: var(--green); }
  .sr-kpi.kpi-blue::before   { background: var(--blue); }
  .sr-kpi.kpi-orange::before { background: var(--orange); }
  .sr-kpi.kpi-slate::before  { background: var(--slate); }

  .sr-kpi-label {
    font-size: 0.65rem;
    font-weight: 600;
    color: var(--muted);
    letter-spacing: 0.1em;
    text-transform: uppercase;
    margin-bottom: 8px;
  }
  .sr-kpi-val {
    font-family: 'Fraunces', serif;
    font-size: 1.7rem;
    font-weight: 700;
    color: var(--ink);
    line-height: 1;
    letter-spacing: -0.02em;
  }
  .sr-kpi-sub {
    font-size: 0.68rem;
    color: var(--muted);
    margin-top: 4px;
  }

  /* ── Main chart card ── */
  .sr-chart-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 28px;
    box-shadow: var(--shadow);
    margin-bottom: 20px;
    animation: riseIn 0.35s 0.1s both;
  }
  .sr-chart-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
    flex-wrap: wrap;
    gap: 12px;
  }
  .sr-chart-title {
    font-family: 'Fraunces', serif;
    font-size: 1.15rem;
    font-weight: 600;
    color: var(--ink);
  }
  .sr-chart-sub {
    font-size: 0.7rem;
    color: var(--muted);
    margin-top: 3px;
    letter-spacing: 0.03em;
  }
  .sr-chart-legend {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 0.72rem;
    font-weight: 500;
    color: var(--muted);
  }
  .sr-legend-dot {
    width: 8px; height: 8px;
    border-radius: 50%;
    flex-shrink: 0;
  }

  /* ── Status breakdown ── */
  .sr-bottom {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
  }
  @media (max-width: 700px) { .sr-bottom { grid-template-columns: 1fr; } }

  .sr-status-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 24px;
    box-shadow: var(--shadow);
    animation: riseIn 0.35s 0.2s both;
  }
  .sr-status-title {
    font-family: 'Fraunces', serif;
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--ink);
    margin-bottom: 20px;
  }

  /* Status rows */
  .sr-status-row {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 14px;
  }
  .sr-status-row:last-child { margin-bottom: 0; }
  .sr-status-dot {
    width: 8px; height: 8px;
    border-radius: 50%;
    flex-shrink: 0;
  }
  .sr-status-name {
    font-size: 0.78rem;
    font-weight: 600;
    color: var(--ink);
    min-width: 100px;
    text-transform: capitalize;
  }
  .sr-status-bar-bg {
    flex: 1;
    height: 6px;
    background: var(--border2);
    border-radius: 99px;
    overflow: hidden;
  }
  .sr-status-bar-fill {
    height: 100%;
    border-radius: 99px;
    transition: width 0.55s cubic-bezier(0.34,1.4,0.64,1);
  }
  .sr-status-count {
    font-size: 0.72rem;
    font-weight: 700;
    color: var(--muted);
    min-width: 20px;
    text-align: right;
  }

  /* ── Bar chart card ── */
  .sr-bar-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 24px;
    box-shadow: var(--shadow);
    animation: riseIn 0.35s 0.25s both;
  }
  .sr-bar-title {
    font-family: 'Fraunces', serif;
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--ink);
    margin-bottom: 20px;
  }

  /* ── Empty state ── */
  .sr-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 220px;
    gap: 10px;
    color: var(--border);
  }
  .sr-empty-icon { font-size: 2.2rem; opacity: 0.35; }
  .sr-empty-text {
    font-size: 0.72rem;
    font-weight: 600;
    color: var(--muted);
    letter-spacing: 0.08em;
    text-transform: uppercase;
  }

  /* ── Loading/Error ── */
  .sr-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 60vh;
    gap: 14px;
  }
  .sr-spinner {
    width: 32px; height: 32px;
    border: 2px solid var(--border);
    border-top-color: var(--ink);
    border-radius: 50%;
    animation: spin 0.75s linear infinite;
  }
  @keyframes spin { to { transform: rotate(360deg); } }
  .sr-state-text {
    font-size: 0.72rem;
    font-weight: 600;
    color: var(--muted);
    letter-spacing: 0.1em;
    text-transform: uppercase;
  }
  .sr-state-text.err { color: var(--red); }

  @keyframes riseIn {
    from { opacity: 0; transform: translateY(10px); }
    to   { opacity: 1; transform: translateY(0); }
  }

  /* ── Tooltip ── */
  .sr-tooltip {
    background: var(--ink);
    border: none;
    border-radius: 8px;
    padding: 8px 12px;
    font-family: 'Instrument Sans', sans-serif;
    font-size: 0.75rem;
    color: #fff;
    box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  }
  .sr-tooltip-label {
    font-weight: 600;
    margin-bottom: 2px;
    opacity: 0.7;
    font-size: 0.65rem;
    letter-spacing: 0.06em;
    text-transform: uppercase;
  }
  .sr-tooltip-val {
    font-family: 'Fraunces', serif;
    font-size: 1rem;
    font-weight: 700;
  }
`;

// ─── Status config ────────────────────────────────────────────────────────────
const STATUS_CONFIG = {
  DELIVERED:   { color: "#16803c", bg: "#f0fdf4" },
  CONFIRMED:   { color: "#1d4ed8", bg: "#eff6ff" },
  PROCESSING:  { color: "#d97706", bg: "#fffbeb" },
  PENDING:     { color: "#9c9489", bg: "#f7f5f2" },
  CANCELLED:   { color: "#e8442a", bg: "#fdf1ef" },
  SHIPPED:     { color: "#7c3aed", bg: "#f5f3ff" },
};
const getStatusColor = (s) => STATUS_CONFIG[s]?.color || "#9c9489";

// ─── Custom Tooltip ───────────────────────────────────────────────────────────
const CustomTooltip = ({ active, payload, label, prefix = "₹" }) => {
  if (!active || !payload?.length) return null;
  return (
    <div className="sr-tooltip">
      <div className="sr-tooltip-label">{label}</div>
      <div className="sr-tooltip-val">
        {prefix}{Number(payload[0].value).toLocaleString("en-IN")}
      </div>
    </div>
  );
};

const BarTooltip = ({ active, payload, label }) => {
  if (!active || !payload?.length) return null;
  return (
    <div className="sr-tooltip">
      <div className="sr-tooltip-label">{label}</div>
      <div className="sr-tooltip-val">{payload[0].value} orders</div>
    </div>
  );
};

// ─── Helpers ─────────────────────────────────────────────────────────────────
const fmt = (n) => new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 }).format(n);

// ─── Main component ───────────────────────────────────────────────────────────
const SalesReport = () => {
  const [view, setView] = useState("daily");
  const { data, isLoading, isError } = useGetSalesReportQuery();

  if (isLoading)
    return (
      <div className="sr-root">
        <style>{styles}</style>
        <div className="sr-state">
          <div className="sr-spinner" />
          <span className="sr-state-text">Loading sales data…</span>
        </div>
      </div>
    );

  if (isError)
    return (
      <div className="sr-root">
        <style>{styles}</style>
        <div className="sr-state">
          <span style={{ fontSize: "1.8rem" }}>✕</span>
          <span className="sr-state-text err">Failed to load sales data</span>
        </div>
      </div>
    );

  const {
    dailySales = {},
    monthlySales = {},
    totalOrders = 0,
    avgOrderValue = 0,
    statusBreakdown = [],
  } = data?.data || {};

  const dailyChartData = Object.entries(dailySales)
    .map(([date, sales]) => ({ date: date.slice(5), sales }))
    .sort((a, b) => a.date.localeCompare(b.date));

  const monthlyChartData = Object.entries(monthlySales)
    .map(([month, sales]) => ({ month, sales }))
    .sort((a, b) => a.month.localeCompare(b.month));

  const chartData = view === "daily" ? dailyChartData : monthlyChartData;
  const xKey = view === "daily" ? "date" : "month";

  const totalRevenue = Object.values(view === "daily" ? dailySales : monthlySales)
    .reduce((s, v) => s + v, 0);

  const maxStatus = Math.max(...statusBreakdown.map((s) => s.count), 1);

  const totalStatusOrders = statusBreakdown.reduce((s, i) => s + i.count, 0);

  return (
    <div className="sr-root">
      <style>{styles}</style>

      {/* ── Header ── */}
      <div className="sr-header">
        <div>
          <div className="sr-eyebrow">Admin · Reports</div>
          <div className="sr-title">Sales</div>
        </div>

        <div className="sr-toggle">
          <button
            className={`sr-toggle-btn${view === "daily" ? " active" : ""}`}
            onClick={() => setView("daily")}
          >Daily</button>
          <button
            className={`sr-toggle-btn${view === "monthly" ? " active" : ""}`}
            onClick={() => setView("monthly")}
          >Monthly</button>
        </div>
      </div>

      {/* ── KPIs ── */}
      <div className="sr-kpis">
        <div className="sr-kpi kpi-green" style={{ animationDelay: "0ms" }}>
          <div className="sr-kpi-label">Total Revenue</div>
          <div className="sr-kpi-val">{fmt(totalRevenue)}</div>
          <div className="sr-kpi-sub">{view === "daily" ? "Last 30 days" : "All time"}</div>
        </div>
        <div className="sr-kpi kpi-blue" style={{ animationDelay: "40ms" }}>
          <div className="sr-kpi-label">Total Orders</div>
          <div className="sr-kpi-val">{totalStatusOrders}</div>
          <div className="sr-kpi-sub">Across all statuses</div>
        </div>
        <div className="sr-kpi kpi-orange" style={{ animationDelay: "80ms" }}>
          <div className="sr-kpi-label">Avg Order Value</div>
          <div className="sr-kpi-val">{fmt(avgOrderValue)}</div>
          <div className="sr-kpi-sub">Paid orders only</div>
        </div>
        <div className="sr-kpi kpi-slate" style={{ animationDelay: "120ms" }}>
          <div className="sr-kpi-label">Delivered</div>
          <div className="sr-kpi-val">
            {statusBreakdown.find((s) => s.status === "DELIVERED")?.count ?? 0}
          </div>
          <div className="sr-kpi-sub">Successfully fulfilled</div>
        </div>
      </div>

      {/* ── Area Chart ── */}
      <div className="sr-chart-card">
        <div className="sr-chart-header">
          <div>
            <div className="sr-chart-title">
              {view === "daily" ? "Daily Revenue" : "Monthly Revenue"}
            </div>
            <div className="sr-chart-sub">
              {view === "daily" ? "Revenue per day (last 30 days)" : "Revenue per month (all time)"}
            </div>
          </div>
          <div className="sr-chart-legend">
            <span className="sr-legend-dot" style={{ background: "#16803c" }} />
            Revenue (INR)
          </div>
        </div>

        {chartData.length > 0 ? (
          <ResponsiveContainer width="100%" height={280}>
            <AreaChart data={chartData} margin={{ top: 4, right: 4, bottom: 0, left: 0 }}>
              <defs>
                <linearGradient id="greenGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%"  stopColor="#16803c" stopOpacity={0.15} />
                  <stop offset="95%" stopColor="#16803c" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid stroke="#f0ece6" strokeDasharray="4 4" vertical={false} />
              <XAxis
                dataKey={xKey}
                tick={{ fontFamily: "Instrument Sans", fontSize: 11, fill: "#9c9489" }}
                axisLine={false}
                tickLine={false}
                interval="preserveStartEnd"
              />
              <YAxis
                tick={{ fontFamily: "Instrument Sans", fontSize: 11, fill: "#9c9489" }}
                axisLine={false}
                tickLine={false}
                tickFormatter={(v) => `₹${v >= 1000 ? `${(v / 1000).toFixed(0)}k` : v}`}
                width={52}
              />
              <Tooltip content={<CustomTooltip />} cursor={{ stroke: "#e8e4de", strokeWidth: 1 }} />
              <Area
                type="monotone"
                dataKey="sales"
                stroke="#16803c"
                strokeWidth={2}
                fill="url(#greenGrad)"
                dot={false}
                activeDot={{ r: 5, fill: "#16803c", strokeWidth: 0 }}
              />
            </AreaChart>
          </ResponsiveContainer>
        ) : (
          <div className="sr-empty">
            <div className="sr-empty-icon">○</div>
            <div className="sr-empty-text">No {view} sales data</div>
          </div>
        )}
      </div>

      {/* ── Bottom row ── */}
      <div className="sr-bottom">

        {/* Status breakdown — horizontal bars */}
        <div className="sr-status-card">
          <div className="sr-status-title">Order Status</div>
          {statusBreakdown.length === 0 ? (
            <div className="sr-empty" style={{ height: 160 }}>
              <div className="sr-empty-icon">○</div>
              <div className="sr-empty-text">No status data</div>
            </div>
          ) : (
            statusBreakdown
              .slice()
              .sort((a, b) => b.count - a.count)
              .map((item, i) => (
                <div className="sr-status-row" key={item.status} style={{ animationDelay: `${i * 40}ms` }}>
                  <span className="sr-status-dot" style={{ background: getStatusColor(item.status) }} />
                  <span className="sr-status-name">{item.status.charAt(0) + item.status.slice(1).toLowerCase()}</span>
                  <div className="sr-status-bar-bg">
                    <div
                      className="sr-status-bar-fill"
                      style={{
                        width: `${Math.round((item.count / maxStatus) * 100)}%`,
                        background: getStatusColor(item.status),
                      }}
                    />
                  </div>
                  <span className="sr-status-count">{item.count}</span>
                </div>
              ))
          )}
        </div>

        {/* Bar chart of status counts */}
        <div className="sr-bar-card">
          <div className="sr-bar-title">Orders by Status</div>
          {statusBreakdown.length > 0 ? (
            <ResponsiveContainer width="100%" height={210}>
              <BarChart
                data={statusBreakdown.map((s) => ({
                  name: s.status.charAt(0) + s.status.slice(1).toLowerCase(),
                  count: s.count,
                  color: getStatusColor(s.status),
                }))}
                margin={{ top: 4, right: 4, bottom: 0, left: -20 }}
                barSize={28}
              >
                <CartesianGrid stroke="#f0ece6" strokeDasharray="4 4" vertical={false} />
                <XAxis
                  dataKey="name"
                  tick={{ fontFamily: "Instrument Sans", fontSize: 10, fill: "#9c9489" }}
                  axisLine={false}
                  tickLine={false}
                />
                <YAxis
                  tick={{ fontFamily: "Instrument Sans", fontSize: 10, fill: "#9c9489" }}
                  axisLine={false}
                  tickLine={false}
                  allowDecimals={false}
                />
                <Tooltip content={<BarTooltip />} cursor={{ fill: "#f7f5f2" }} />
                <Bar dataKey="count" radius={[5, 5, 0, 0]}>
                  {statusBreakdown.map((entry, i) => (
                    <Cell key={i} fill={getStatusColor(entry.status)} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          ) : (
            <div className="sr-empty" style={{ height: 210 }}>
              <div className="sr-empty-icon">○</div>
              <div className="sr-empty-text">No data</div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default SalesReport;