'use client';

import { useMemo, useState } from 'react';
import { useCurrencyStore } from '@/store/currencyStore';

// Lightweight, dependency-free SVG/CSS charts for the dashboard's
// daily_trend / category_sales / hourly_orders data (all already date-filter
// aware on the API side). No chart library is installed and these three
// simple shapes don't justify adding one.

export interface DailyTrendPoint { date: string; orders: number; revenue: number }
export interface CategorySalePoint { category: string; items_sold: number; revenue: number }
export interface HourlyOrderPoint { hour: number; orders: number }

const CARD_STYLE: React.CSSProperties = {
  background: 'var(--color-surface)',
  border: '1px solid var(--color-border)',
};

function ChartCard({ title, subtitle, children }: { title: string; subtitle?: string; children: React.ReactNode }) {
  return (
    <div className="p-5 rounded-xl" style={CARD_STYLE}>
      <div className="mb-4">
        <h3 className="text-sm font-semibold" style={{ color: 'var(--color-text)' }}>{title}</h3>
        {subtitle && (
          <p className="text-xs mt-0.5" style={{ color: 'var(--color-text-secondary)' }}>{subtitle}</p>
        )}
      </div>
      {children}
    </div>
  );
}

function EmptyChart() {
  return (
    <p className="text-sm text-center py-10" style={{ color: 'var(--color-text-secondary)' }}>
      No data for this period
    </p>
  );
}

// 'YYYY-MM-DD' -> 'Sep 19' without going through Date's timezone handling.
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function shortDate(ymd: string): string {
  const [, m, d] = ymd.split('-');
  const month = MONTHS[Number(m) - 1];
  return month ? `${month} ${Number(d)}` : ymd;
}

// ─── Daily revenue trend (area + line) ─────────────────────────────────────
function DailyTrendChart({ data }: { data: DailyTrendPoint[] }) {
  const formatAmount = useCurrencyStore((s) => s.formatAmount);
  const [hover, setHover] = useState<number | null>(null);

  const W = 960;
  const H = 240;
  // Side padding leaves room for the first/last date labels (centered on
  // their points) so they don't clip at the SVG edge.
  const PAD = { top: 12, right: 32, bottom: 28, left: 32 };

  const geometry = useMemo(() => {
    const max = Math.max(...data.map((d) => d.revenue), 1);
    const innerW = W - PAD.left - PAD.right;
    const innerH = H - PAD.top - PAD.bottom;
    const step = data.length > 1 ? innerW / (data.length - 1) : 0;
    const points = data.map((d, i) => ({
      x: data.length > 1 ? PAD.left + i * step : PAD.left + innerW / 2,
      y: PAD.top + innerH - (d.revenue / max) * innerH,
    }));
    const line = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(' ');
    const area = points.length
      ? `${line} L${points[points.length - 1].x.toFixed(1)},${PAD.top + innerH} L${points[0].x.toFixed(1)},${PAD.top + innerH} Z`
      : '';
    return { points, line, area, innerH };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

  if (data.length === 0) return <EmptyChart />;

  const active = hover !== null ? data[hover] : null;
  const labelEvery = Math.max(1, Math.ceil(data.length / 6));

  return (
    <div>
      <div className="h-5 mb-1 text-xs" style={{ color: 'var(--color-text-secondary)' }}>
        {active ? (
          <span>
            <strong style={{ color: 'var(--color-text)' }}>{shortDate(active.date)}</strong>
            {' · '}{formatAmount(active.revenue)}{' · '}{active.orders} order{active.orders === 1 ? '' : 's'}
          </span>
        ) : (
          <span>Hover a point for details</span>
        )}
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} className="w-full h-auto max-h-64" role="img" aria-label="Daily revenue trend">
        <defs>
          <linearGradient id="trendFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#F59E0B" stopOpacity="0.35" />
            <stop offset="100%" stopColor="#F59E0B" stopOpacity="0.02" />
          </linearGradient>
        </defs>
        <path d={geometry.area} fill="url(#trendFill)" />
        <path d={geometry.line} fill="none" stroke="#D97706" strokeWidth="2" strokeLinejoin="round" />
        {geometry.points.map((p, i) => (
          <g key={data[i].date}>
            <circle cx={p.x} cy={p.y} r={hover === i ? 5 : 3} fill="#D97706" />
            {/* Wide invisible hit target so single points are easy to hover */}
            <rect
              x={p.x - Math.max(8, (W / data.length) / 2)}
              y={0}
              width={Math.max(16, W / data.length)}
              height={H - PAD.bottom}
              fill="transparent"
              onMouseEnter={() => setHover(i)}
              onMouseLeave={() => setHover(null)}
            />
            {i % labelEvery === 0 && (
              <text x={p.x} y={H - 8} textAnchor="middle" fontSize="10" fill="var(--color-text-secondary)">
                {shortDate(data[i].date)}
              </text>
            )}
          </g>
        ))}
      </svg>
    </div>
  );
}

// ─── Category sales (horizontal bars) ──────────────────────────────────────
function CategorySalesChart({ data }: { data: CategorySalePoint[] }) {
  const formatAmount = useCurrencyStore((s) => s.formatAmount);
  if (data.length === 0) return <EmptyChart />;
  const max = Math.max(...data.map((d) => d.revenue), 1);

  return (
    <div className="space-y-3">
      {data.map((d) => (
        <div key={d.category}>
          <div className="flex justify-between text-xs mb-1">
            <span className="font-medium truncate pr-2" style={{ color: 'var(--color-text)' }}>{d.category}</span>
            <span style={{ color: 'var(--color-text-secondary)' }}>
              {formatAmount(d.revenue)} · {d.items_sold} sold
            </span>
          </div>
          <div className="h-2.5 rounded-full overflow-hidden" style={{ background: 'var(--color-border)' }}>
            <div
              className="h-full rounded-full"
              style={{ width: `${(d.revenue / max) * 100}%`, background: 'linear-gradient(90deg, #8B5CF6, #6D28D9)' }}
            />
          </div>
        </div>
      ))}
    </div>
  );
}

// ─── Orders by hour of day (24 bars) ───────────────────────────────────────
function HourlyOrdersChart({ data }: { data: HourlyOrderPoint[] }) {
  const byHour = new Map(data.map((d) => [d.hour, d.orders]));
  const hours = Array.from({ length: 24 }, (_, h) => ({ hour: h, orders: byHour.get(h) ?? 0 }));
  const max = Math.max(...hours.map((h) => h.orders), 0);
  if (max === 0) return <EmptyChart />;

  return (
    <div>
      <div className="flex items-end gap-1 h-36">
        {hours.map((h) => (
          <div
            key={h.hour}
            className="flex-1 rounded-t"
            title={`${String(h.hour).padStart(2, '0')}:00 — ${h.orders} order${h.orders === 1 ? '' : 's'}`}
            style={{
              height: `${(h.orders / max) * 100}%`,
              minHeight: h.orders > 0 ? 3 : 1,
              background: h.orders > 0 ? 'linear-gradient(180deg, #3B82F6, #1D4ED8)' : 'var(--color-border)',
            }}
          />
        ))}
      </div>
      <div className="flex justify-between text-[10px] mt-1.5" style={{ color: 'var(--color-text-secondary)' }}>
        <span>12am</span><span>6am</span><span>12pm</span><span>6pm</span><span>11pm</span>
      </div>
    </div>
  );
}

// ─── Section ───────────────────────────────────────────────────────────────
export default function DashboardCharts({
  dailyTrend,
  categorySales,
  hourlyOrders,
  isAllTime,
}: {
  dailyTrend: DailyTrendPoint[];
  categorySales: CategorySalePoint[];
  hourlyOrders: HourlyOrderPoint[];
  // "All Time" has no range to chart, so the API falls back to the last
  // 30 days (daily trend) / last 24 hours (hourly) — say so in the subtitle.
  isAllTime: boolean;
}) {
  return (
    <div className="space-y-4">
      <ChartCard
        title="Sales Trend"
        subtitle={isAllTime ? 'Item sales per day, last 30 days' : 'Item sales per day in the selected period'}
      >
        <DailyTrendChart data={dailyTrend} />
      </ChartCard>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <ChartCard title="Top Categories" subtitle="By item sales, top 5">
          <CategorySalesChart data={categorySales} />
        </ChartCard>
        <ChartCard
          title="Orders by Hour"
          subtitle={isAllTime ? 'Orders placed per hour, last 24 hours' : 'Orders placed per hour of day'}
        >
          <HourlyOrdersChart data={hourlyOrders} />
        </ChartCard>
      </div>
    </div>
  );
}
