"use client";

import { Area, AreaChart, Bar, BarChart, CartesianGrid, Cell, Line, LineChart, Pie, PieChart, XAxis, YAxis } from "recharts";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import {
  type ChartConfig,
  ChartContainer,
  ChartLegend,
  ChartLegendContent,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart";
import { categoryRevenue, formatDate, formatKES, paymentBreakdown, salesByDay, salesByHour } from "@/lib/mock-data";

const k = (v: number) => (v >= 1000 ? `${Math.round(v / 1000)}k` : String(v));

const dayData = salesByDay.map((d) => ({ ...d, label: formatDate(d.date, { short: true }) }));
const lastTen = dayData.slice(-10);

const salesConfig = { revenue: { label: "Revenue", color: "var(--chart-1)" } } satisfies ChartConfig;
const costConfig = {
  revenue: { label: "Revenue", color: "var(--chart-1)" },
  cost: { label: "Cost of goods", color: "var(--chart-3)" },
} satisfies ChartConfig;
const hourConfig = { transactions: { label: "Transactions", color: "var(--chart-1)" } } satisfies ChartConfig;
const payConfig = {
  "M-Pesa": { label: "M-Pesa", color: "var(--chart-1)" },
  Cash: { label: "Cash", color: "var(--chart-2)" },
  Card: { label: "Card", color: "var(--chart-3)" },
  Credit: { label: "Credit", color: "var(--chart-4)" },
} satisfies ChartConfig;
const catConfig = { revenue: { label: "Revenue", color: "var(--chart-1)" } } satisfies ChartConfig;

const kesFormatter = (value: unknown, name: unknown) => (
  <div className="flex w-full items-center justify-between gap-4">
    <span className="text-muted-foreground">{String(name)}</span>
    <span className="font-mono font-medium tabular-nums">{formatKES(Number(value))}</span>
  </div>
);

/** Axis-less line used inside stat tiles. */
export function Sparkline({ data, className }: { data: number[]; className?: string }) {
  const points = data.map((v, i) => ({ i, v }));
  return (
    <ChartContainer config={{ v: { label: "Value", color: "var(--chart-1)" } }} className={className ?? "aspect-auto h-10 w-full"} initialDimension={{ width: 160, height: 40 }}>
      <LineChart data={points} margin={{ top: 4, right: 2, bottom: 4, left: 2 }}>
        <Line dataKey="v" type="monotone" stroke="var(--color-v)" strokeWidth={1.5} dot={false} isAnimationActive={false} />
      </LineChart>
    </ChartContainer>
  );
}

export function ChartsSection() {
  const payData = paymentBreakdown.map((p) => ({ ...p, name: p.method }));
  const payTotal = paymentBreakdown.reduce((s, p) => s + p.amount, 0);

  return (
    <Section id="charts" title="Charts" description="shadcn chart wrappers over Recharts, coloured with the --chart-* tokens. Flat fills, light gridlines, at most four series.">
      <Example
        title="30-day sales"
        description="Single-series area, flat fill"
        code={`<ChartContainer config={{ revenue: { label: "Revenue", color: "var(--chart-1)" } }}>
  <AreaChart data={data}>
    <Area isAnimationActive={false} dataKey="revenue" stroke="var(--color-revenue)" fill="var(--color-revenue)" fillOpacity={0.12} />
  </AreaChart>
</ChartContainer>`}
      >
        <ChartContainer config={salesConfig} className="aspect-auto h-64 w-full">
          <AreaChart data={dayData} margin={{ left: 0, right: 8, top: 8 }}>
            <CartesianGrid vertical={false} />
            <XAxis dataKey="label" tickLine={false} axisLine={false} tickMargin={8} minTickGap={32} />
            <YAxis tickLine={false} axisLine={false} width={36} tickFormatter={k} />
            <ChartTooltip content={<ChartTooltipContent formatter={kesFormatter} />} />
            <Area isAnimationActive={false} dataKey="revenue" type="monotone" stroke="var(--color-revenue)" strokeWidth={1.5} fill="var(--color-revenue)" fillOpacity={0.1} dot={false} />
          </AreaChart>
        </ChartContainer>
      </Example>

      <div className="grid gap-4 lg:grid-cols-2">
        <Example title="Revenue vs cost" description="Two series, last 10 days">
          <ChartContainer config={costConfig} className="aspect-auto h-64 w-full">
            <BarChart data={lastTen} margin={{ left: 0, right: 8, top: 8 }}>
              <CartesianGrid vertical={false} />
              <XAxis dataKey="label" tickLine={false} axisLine={false} tickMargin={8} />
              <YAxis tickLine={false} axisLine={false} width={36} tickFormatter={k} />
              <ChartTooltip content={<ChartTooltipContent formatter={kesFormatter} />} />
              <ChartLegend content={<ChartLegendContent />} />
              <Bar isAnimationActive={false} dataKey="revenue" fill="var(--color-revenue)" radius={[2, 2, 0, 0]} />
              <Bar isAnimationActive={false} dataKey="cost" fill="var(--color-cost)" radius={[2, 2, 0, 0]} />
            </BarChart>
          </ChartContainer>
        </Example>

        <Example title="Hourly sales" description="24 buckets, transactions per hour">
          <ChartContainer config={hourConfig} className="aspect-auto h-64 w-full">
            <BarChart data={salesByHour} margin={{ left: 0, right: 8, top: 8 }}>
              <CartesianGrid vertical={false} />
              <XAxis dataKey="hour" tickLine={false} axisLine={false} tickMargin={8} interval={2} tickFormatter={(h: number) => `${String(h).padStart(2, "0")}h`} />
              <YAxis tickLine={false} axisLine={false} width={28} />
              <ChartTooltip content={<ChartTooltipContent labelFormatter={(_, p) => (p?.[0]?.payload as { label?: string })?.label ?? ""} />} />
              <Bar isAnimationActive={false} dataKey="transactions" fill="var(--color-transactions)" radius={[2, 2, 0, 0]} />
            </BarChart>
          </ChartContainer>
        </Example>

        <Example title="Payment methods" description="Donut with centre total">
          <div className="relative">
            <ChartContainer config={payConfig} className="mx-auto aspect-auto h-64 w-full">
              <PieChart>
                <ChartTooltip content={<ChartTooltipContent nameKey="name" hideLabel formatter={kesFormatter} />} />
                <Pie data={payData} dataKey="amount" nameKey="name" innerRadius={62} outerRadius={92} paddingAngle={1} stroke="var(--background)" strokeWidth={2} isAnimationActive={false}>
                  {payData.map((p) => (
                    <Cell key={p.method} fill={`var(--color-${p.method})`} />
                  ))}
                </Pie>
                <ChartLegend content={<ChartLegendContent nameKey="name" />} />
              </PieChart>
            </ChartContainer>
            <div className="pointer-events-none absolute inset-x-0 top-[calc(50%-1.75rem)] text-center">
              <div className="text-xs text-muted-foreground">30 days</div>
              <div className="text-sm font-semibold tabular-nums">{formatKES(payTotal)}</div>
            </div>
          </div>
        </Example>

        <Example title="Revenue by category" description="Horizontal bar, ranked">
          <ChartContainer config={catConfig} className="aspect-auto h-64 w-full">
            <BarChart data={categoryRevenue} layout="vertical" margin={{ left: 0, right: 16 }}>
              <CartesianGrid horizontal={false} />
              <YAxis dataKey="category" type="category" tickLine={false} axisLine={false} width={104} />
              <XAxis type="number" tickLine={false} axisLine={false} tickFormatter={k} />
              <ChartTooltip cursor={false} content={<ChartTooltipContent hideLabel formatter={kesFormatter} />} />
              <Bar isAnimationActive={false} dataKey="revenue" fill="var(--color-revenue)" radius={[0, 2, 2, 0]} barSize={14} />
            </BarChart>
          </ChartContainer>
        </Example>
      </div>

      <Example title="Sparkline" description="No axes, 14-day revenue; used inside stat tiles">
        <div className="max-w-xs">
          <Sparkline data={dayData.slice(-14).map((d) => d.revenue)} />
        </div>
      </Example>
    </Section>
  );
}
