"use client";

import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { ChartCard, ReportFilterBar, ReportTable, type ReportColumn } from "@/components/medora/records/reports";
import { RecordStatusBadge } from "@/components/medora/records/status";
import { type ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";
import { branches, formatDate, formatKES, salesByDay, TODAY, topProducts } from "@/lib/mock-data";

const cols: ReportColumn<(typeof topProducts)[number]>[] = [
  { key: "name", header: "Product", cell: (r) => r.name, total: "Total" },
  { key: "units", header: "Units sold", numeric: true, cell: (r) => r.units.toLocaleString("en-US"), total: topProducts.slice(0, 6).reduce((s, r) => s + r.units, 0).toLocaleString("en-US") },
  { key: "revenue", header: "Revenue", numeric: true, cell: (r) => formatKES(r.revenue), total: formatKES(topProducts.slice(0, 6).reduce((s, r) => s + r.revenue, 0)) },
  { key: "status", header: "Stock", cell: () => <RecordStatusBadge domain="stock" status="In stock" /> },
];

const rows = topProducts.slice(0, 6);
const data = salesByDay.map((d) => ({ ...d, label: formatDate(d.date, { short: true }) }));
const config = {
  revenue: { label: "Revenue", color: "var(--chart-1)" },
  cost: { label: "Cost of goods", color: "var(--chart-3)" },
} satisfies ChartConfig;

function Lines() {
  return (
    <ChartContainer config={config} className="aspect-auto h-full w-full" initialDimension={{ width: 600, height: 200 }}>
      <LineChart data={data} margin={{ left: 0, right: 8, top: 4 }}>
        <CartesianGrid vertical={false} stroke="var(--border)" />
        <XAxis dataKey="label" tickLine={false} axisLine={false} interval={4} fontSize={11} />
        <YAxis tickLine={false} axisLine={false} width={40} fontSize={11} tickFormatter={(v: number) => `${Math.round(v / 1000)}k`} />
        <ChartTooltip content={<ChartTooltipContent />} />
        <Line dataKey="revenue" stroke="var(--color-revenue)" strokeWidth={1.5} dot={false} isAnimationActive={false} />
        <Line dataKey="cost" stroke="var(--color-cost)" strokeWidth={1.5} dot={false} isAnimationActive={false} />
      </LineChart>
    </ChartContainer>
  );
}

export function ReportingSection() {
  return (
    <Section id="reporting" title="Reporting" description="The filter bar every report shares, the table with a totals footer, and the chart wrapper.">
      <Example title="Report filter bar" description="Presets set the dates; editing a date switches to custom" className="space-y-3">
        <ReportFilterBar today={TODAY} branches={branches} />
        <ReportFilterBar today={TODAY} branches={branches} exporting="excel" />
        <ReportFilterBar today={TODAY} branches={branches} disabled />
      </Example>
      <Example title="Report table with totals footer" description="Ready, loading, error, empty" className="space-y-4">
        <ReportTable columns={cols} rows={rows} rowKey={(r) => r.productId} />
        <ReportTable columns={cols} rows={[]} rowKey={(r) => r.productId} state="loading" />
        <ReportTable columns={cols} rows={[]} rowKey={(r) => r.productId} state="error" error="The sales report could not be loaded. Check the connection and try again." />
        <ReportTable columns={cols} rows={[]} rowKey={(r) => r.productId} emptyMessage="No sales between 1 Oct and 20 Oct for this branch." />
      </Example>
      <Example title="Chart card" description="Ready, loading, empty, error" className="grid gap-4 lg:grid-cols-2">
        <ChartCard title="Revenue and cost" description="Last 30 days" legend={[{ label: "Revenue", color: "var(--chart-1)" }, { label: "Cost of goods", color: "var(--chart-3)" }]}>
          <Lines />
        </ChartCard>
        <ChartCard title="Revenue and cost" description="Last 30 days" state="loading" />
        <ChartCard title="Revenue and cost" description="Last 30 days" state="empty" emptyMessage="No sales in this period." />
        <ChartCard title="Revenue and cost" description="Last 30 days" state="error" error="The chart data could not be loaded." />
      </Example>
    </Section>
  );
}
