"use client";

import { Area, AreaChart, Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";

import { Badge } from "@/components/ui/badge";
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@/components/ui/chart";
import { currentUser, expiring, formatDate, formatKES, kpis, lowStock, recentSales, salesByDay, salesByHour, staff } from "@/lib/mock-data";
import { Frame } from "./frame";

const dayCfg = { revenue: { label: "Revenue", color: "var(--chart-1)" } } satisfies ChartConfig;
const hourCfg = { transactions: { label: "Transactions", color: "var(--chart-1)" } } satisfies ChartConfig;

const pct = (n: number) => `${n >= 0 ? "+" : ""}${(n * 100).toFixed(1)}%`;
const tiles = [
  { k: "Today", v: formatKES(kpis.todayRevenue), d: pct(kpis.todayChange), up: kpis.todayChange >= 0 },
  { k: "This week", v: formatKES(kpis.weekRevenue), d: pct(kpis.weekChange), up: kpis.weekChange >= 0 },
  { k: "Gross profit (30d)", v: formatKES(kpis.grossProfit), d: `${(kpis.grossMargin * 100).toFixed(1)}% margin`, up: true },
  { k: "Receivables", v: formatKES(kpis.receivables), d: `${kpis.customersOwing} customers owe`, up: false },
];

export function DashboardPattern() {
  return (
    <Frame className="overflow-auto bg-muted/40">
      <div className="space-y-3 p-4">
        <div className="flex items-baseline justify-between">
          <h3 className="text-base font-semibold">Dashboard</h3>
          <span className="text-xs text-muted-foreground">Westlands Main, last 30 days</span>
        </div>
        <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
          {tiles.map((t) => (
            <div key={t.k} className="rounded-lg border border-border bg-card p-3">
              <p className="text-xs text-muted-foreground">{t.k}</p>
              <p className="mt-1 text-lg font-semibold tabular-nums">{t.v}</p>
              <p className={`text-xs tabular-nums ${t.up ? "text-status-success-text" : "text-muted-foreground"}`}>{t.d}</p>
            </div>
          ))}
        </div>
        <div className="grid gap-3 lg:grid-cols-5">
          <div className="rounded-lg border border-border bg-card p-3 lg:col-span-3">
            <div className="mb-2 flex items-baseline justify-between gap-2">
              <p className="text-sm font-medium">Sales, 30 days</p>
              {/* DB-09: the compact trend leads to the full Sales Summary in Reports. */}
              <a href="/design-system/reports#sales-trend" className="text-xs font-medium text-primary underline-offset-4 hover:underline">
                Sales summary →
              </a>
            </div>
            <ChartContainer config={dayCfg} className="h-48 w-full">
              <AreaChart data={salesByDay} margin={{ left: 4, right: 8 }}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="date" tickLine={false} axisLine={false} tickFormatter={(d: string) => formatDate(d, { short: true })} interval={6} />
                <YAxis tickLine={false} axisLine={false} width={44} tickFormatter={(v: number) => `${Math.round(v / 1000)}k`} />
                <ChartTooltip content={<ChartTooltipContent />} />
                <Area isAnimationActive={false} dataKey="revenue" type="monotone" stroke="var(--color-revenue)" fill="var(--color-revenue)" fillOpacity={0.12} strokeWidth={2} />
              </AreaChart>
            </ChartContainer>
          </div>
          <div className="rounded-lg border border-border bg-card p-3 lg:col-span-2">
            <p className="mb-2 text-sm font-medium">Transactions by hour</p>
            <ChartContainer config={hourCfg} className="h-48 w-full">
              <BarChart data={salesByHour.filter((h) => h.hour >= 6 && h.hour <= 22)}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="hour" tickLine={false} axisLine={false} interval={2} />
                <YAxis tickLine={false} axisLine={false} width={24} />
                <ChartTooltip content={<ChartTooltipContent />} />
                <Bar isAnimationActive={false} dataKey="transactions" fill="var(--color-transactions)" radius={2} />
              </BarChart>
            </ChartContainer>
          </div>
        </div>
        <div className="grid gap-3 lg:grid-cols-3">
          <div className="rounded-lg border border-border bg-card">
            <p className="border-b border-border px-3 py-2 text-sm font-medium">Low stock ({lowStock.length})</p>
            <ul className="divide-y divide-border text-sm">
              {lowStock.slice(0, 5).map((p) => (
                <li key={p.id} className="flex justify-between px-3 py-1.5"><span>{p.name}</span><span className="tabular-nums text-muted-foreground">{p.stock} / {p.minStock}</span></li>
              ))}
            </ul>
          </div>
          <div className="rounded-lg border border-border bg-card">
            <p className="border-b border-border px-3 py-2 text-sm font-medium">Expiring soon ({expiring.length})</p>
            <ul className="divide-y divide-border text-sm">
              {expiring.slice(0, 5).map((b) => (
                <li key={b.id} className="flex items-center justify-between px-3 py-1.5">
                  <span>{b.productName}</span>
                  <Badge variant={b.daysLeft < 0 ? "destructive" : "outline"}>{b.daysLeft < 0 ? "Expired" : `${b.daysLeft} d`}</Badge>
                </li>
              ))}
            </ul>
          </div>
          <div className="rounded-lg border border-border bg-card">
            <p className="border-b border-border px-3 py-2 text-sm font-medium">Recent activity</p>
            <ul className="divide-y divide-border text-sm">
              {recentSales.slice(0, 5).map((s) => (
                <li key={s.id} className="flex justify-between px-3 py-1.5">
                  <span>{staff.find((u) => u.id === s.cashierId)?.name ?? currentUser.name} sold {s.items} items</span>
                  <span className="tabular-nums text-muted-foreground">{formatKES(s.total)}</span>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>
    </Frame>
  );
}
