"use client";

import * as React from "react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { EditableGrid, type GridColumn, type GridRow } from "@/components/medora/editable-grid";
import { RadarCompare, SeriesLineChart, TargetRing, type LinePoint, type RadarItem, type RadarMeasure } from "@/components/medora/report-charts";
import { kes } from "@/components/medora/payroll";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/toast";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";

/*
 * Card 040 (Gate 2, 29 Oct 2026): the interactive line (C90), radial progress (C91) and radar (C92) charts.
 * Figures agree with the rest of the design system: 1–20 Oct 2026 revenue 1,284,600 (1,207,300 the period before),
 * gross profit 442,300, stock at cost 684,210 (1,023,900 at selling prices) and 47,450 expiring within 90 days,
 * split over Westlands Main, Kilimani, Nyali and Milimani as in the dashboard and stock demos.
 */

const days = Array.from({ length: 20 }, (_, i) => i + 1);

/** Spread a total over the 20 days with a repeatable shape, the last day taking the rounding. */
const spread = (total: number, seed: number) => {
  const raw = days.map((d) => 1 + 0.18 * Math.sin((d + seed) / 2.2) + ((d * 7 + seed) % 5) * 0.03 + ([6, 13, 20].includes(d) ? 0.22 : 0));
  const sum = raw.reduce((s, v) => s + v, 0);
  const vals = raw.map((v) => Math.round((v / sum) * total));
  vals[vals.length - 1] += total - vals.reduce((s, v) => s + v, 0);
  return vals;
};

// RP-17: the same trend as the Sales trend demo, with series buttons
const thisPeriod = spread(1284600, 0);
const before = spread(1207300, 3);
const SALES: LinePoint[] = days.map((d, i) => ({ label: `${d} Oct`, current: thisPeriod[i], previous: before[i] }));

// DB-16: stock value at the end of each day, ending at today's 684,210 at cost and 1,023,900 at selling prices.
// Stock falls with sales and steps up on delivery days (7 and 15 Oct).
const STOCK: LinePoint[] = (() => {
  const cost: number[] = [];
  let v = 684210;
  for (let d = 20; d >= 1; d--) {
    cost[d - 1] = v;
    v = v + Math.round(5200 + 1400 * Math.sin(d)) - (d === 7 || d === 15 ? 61800 : 0);
  }
  return days.map((d, i) => ({ label: `${d} Oct`, cost: cost[i], selling: Math.round((cost[i] * 1023900) / 684210) }));
})();

// RP-16: one row per branch. Sales and gross profit add up to the dashboard's 1,284,600 and 442,300; stock at
// cost to 684,210; expiring to 47,450. Stock turn = the period's cost of goods ÷ stock at cost now (Gate 2, Q2).
const BRANCHES: RadarItem[] = [
  { name: "Westlands Main", values: { sales: 612400, margin: 41.0, turn: 1.04, expiring: 14200 } },
  { name: "Kilimani", values: { sales: 301900, margin: 38.9, turn: 0.98, expiring: 9850 } },
  { name: "Nyali", values: { sales: 244100, margin: 40.4, turn: 0.88, expiring: 15900 } },
  { name: "Milimani", values: { sales: 126200, margin: 36.2, turn: 0.85, expiring: 7500 } },
];
const THIKA: RadarItem = { name: "Thika", values: { sales: 98300, margin: 37.5, turn: 1.12, expiring: 3100 } };
const MEASURES: RadarMeasure[] = [
  { key: "sales", label: "Sales", format: kes },
  { key: "margin", label: "Gross margin", format: (v) => `${v.toFixed(1)}%` },
  { key: "turn", label: "Stock turn", format: (v) => `${v.toFixed(2)}×` },
  { key: "expiring", label: "Expiring stock", lowerIsBetter: true, format: kes },
];

// DB-17: October targets per branch add up to 1,800,000
const TARGETS = [
  { id: "westlands", branch: "Westlands Main", sep: 820000, oct: 850000, nov: 860000 },
  { id: "kilimani", branch: "Kilimani", sep: 410000, oct: 430000, nov: 430000 },
  { id: "nyali", branch: "Nyali", sep: 330000, oct: 350000, nov: 360000 },
  { id: "milimani", branch: "Milimani", sep: 160000, oct: 170000, nov: 175000 },
];

const Hint = ({ children }: { children: React.ReactNode }) => <p className="mt-3 text-xs text-muted-foreground">Try this: {children}</p>;

export function MoreChartsSection() {
  const [target, setTarget] = React.useState<"set" | "none" | "over">("set");
  const [fifth, setFifth] = React.useState(false);
  return (
    <Section id="more-charts" title="Interactive line, radial progress and radar" description="Card 040: DB-16 stock value over time, RP-17 series buttons on trends, DB-17 progress against a sales target, RP-16 the branch scorecard. Each keeps its table.">
      <div className="grid gap-4 lg:grid-cols-2">
        <Example title="Stock value over time" description="DB-16 · 1–20 Oct 2026, all branches, at the end of each day">
          <SeriesLineChart
            label="Stock value over time"
            points={STOCK}
            series={[
              { key: "cost", label: "At cost" },
              { key: "selling", label: "At selling price" },
            ]}
            measure="last"
            caveat="Past days are valued at today's costs. Figures are reliable from 9 Oct 2026, when stock adjustments started being recorded."
          />
          <Hint>choose At cost to draw one line, then Table for each day&apos;s figures. The buttons show the latest value, which matches Stock value (KES 684,210.00).</Hint>
        </Example>
        <Example title="Sales trend with series buttons" description="RP-17 · 1–20 Oct 2026 against 1–20 Sep 2026">
          <SeriesLineChart
            label="Sales trend"
            points={SALES}
            series={[
              { key: "current", label: "This period" },
              { key: "previous", label: "Period before" },
            ]}
          />
          <Hint>All is chosen first. The totals agree with the sales trend above: KES 1,284,600.00 and KES 1,207,300.00.</Hint>
        </Example>
        <Example title="Sales target" description="DB-17 · October 2026, all branches">
          <ToggleGroup variant="outline" size="sm" spacing={0} aria-label="Target example" value={[target]} onValueChange={(v: string[]) => v[0] && setTarget(v[0] as typeof target)} className="mb-4">
            <ToggleGroupItem value="set">Target set</ToggleGroupItem>
            <ToggleGroupItem value="over">Over target</ToggleGroupItem>
            <ToggleGroupItem value="none">No target</ToggleGroupItem>
          </ToggleGroup>
          <TargetRing value={1284600} target={target === "none" ? null : target === "over" ? 1200000 : 1800000} period="October 2026" onSetTarget={() => toast.add({ title: "Opens Settings, Sales targets" })} />
          <Hint>the four branches&apos; October targets add up to KES 1,800,000.00 (Settings demo). Over target fills the ring and says by how much; with no target the panel says so instead of showing 0%.</Hint>
        </Example>
        <Example title="Branch scorecard" description="RP-16 · 1–20 Oct 2026, each measure as a share of the best branch; expiring stock is the value expiring within 90 days">
          <RadarCompare label="Branch scorecard" measures={MEASURES} items={fifth ? [...BRANCHES, THIKA] : BRANCHES} />
          <div className="mt-3 flex flex-wrap items-center gap-2">
            <Button size="sm" variant="outline" onClick={() => setFifth((f) => !f)}>
              {fifth ? "Remove Thika" : "Add a fifth branch"}
            </Button>
          </div>
          <Hint>add a fifth branch: the header then picks which four are drawn, and the table still lists all five. Expiring stock is scored lowest-is-best, so the branch with the least expiring leads that axis (Milimani, or Thika once added).</Hint>
        </Example>
      </div>
    </Section>
  );
}

const MONTHS: GridColumn[] = [
  { key: "sep", header: "September 2026", kind: "read", align: "right" },
  { key: "oct", header: "October 2026 (this month)", kind: "number", align: "right" },
  { key: "nov", header: "November 2026", kind: "number", align: "right" },
];

/** DB-17, Settings → Sales targets: a branch per row; past months read-only; each change goes to the activity log. */
export function SalesTargetsSection() {
  const [draft, setDraft] = React.useState<Record<string, Record<string, string>>>({});
  const rows: GridRow[] = TARGETS.map((t) => ({ id: t.id, header: t.branch, values: { sep: kes(t.sep), oct: String(t.oct), nov: String(t.nov) } }));
  const value = (id: string, key: "oct" | "nov") => Number(draft[id]?.[key] ?? TARGETS.find((t) => t.id === id)?.[key] ?? 0);
  const total = (key: "oct" | "nov") => TARGETS.reduce((s, t) => s + value(t.id, key), 0);
  const changed = Object.values(draft).reduce((n, r) => n + Object.keys(r).length, 0);
  return (
    <Section id="sales-targets" title="Sales targets" description="DB-17: a monthly sales target per branch. This month and later can change; past months can't. Each change is in the activity log.">
      <Example title="Sales targets" description="Settings → Sales targets, all branches">
        <EditableGrid
          caption="Monthly sales targets per branch"
          rowLabel="Branch"
          columns={MONTHS}
          rows={rows}
          draft={draft}
          onDraftChange={(id, key, v) =>
            setDraft((d) => {
              const r = { ...(d[id] ?? {}) };
              if (v === undefined) delete r[key];
              else r[key] = v;
              return { ...d, [id]: r };
            })
          }
          onSaveDraft={() => {
            toast.add({ title: `${changed} target${changed === 1 ? "" : "s"} saved`, description: "Each change is in the activity log." });
            setDraft({});
          }}
          onDiscard={() => setDraft({})}
          footer={
            <p className="text-xs text-muted-foreground tabular-nums">
              All branches: October {kes(total("oct"))} · November {kes(total("nov"))}
            </p>
          }
        />
        <Hint>change Nyali&apos;s October target: the total under the grid follows, and Save keeps it. September is read-only because it has passed.</Hint>
      </Example>
    </Section>
  );
}
