"use client";

import * as React from "react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { ReviewBeforeCommit, type CommitResult, type ReviewIssue, type ReviewLine } from "@/components/medora/review-commit";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { formatKES, products } from "@/lib/mock-data";

// Counted vs system for a stock take. In the app these lines and totals come from the API (spec P2).
const COUNTS: Record<number, number> = { 1: -6, 2: 0, 4: -2, 5: 3, 7: 0, 9: -10, 13: 0, 14: 4, 19: -1, 21: 0, 23: 12, 26: 0, 29: -3, 31: 0 };
const UNIT: Record<string, string> = { Tablet: "tablets", Capsule: "capsules", Syrup: "bottles", Cream: "tubes", Inhaler: "inhalers", Box: "boxes", Sachet: "sachets" };

const baseLines: ReviewLine[] = products
  .filter((p) => p.type === "Product" && p.id in COUNTS)
  .map((p) => ({
    id: String(p.id),
    name: `${p.name} ${p.strength}`,
    sub: `Shelf ${p.shelf}`,
    before: p.stock,
    after: p.stock + COUNTS[p.id],
    unit: UNIT[p.form] ?? "units",
    value: COUNTS[p.id] * p.costPrice,
  }));

const newBatch: ReviewLine = { id: "nb", name: "Panadol 500 mg, new batch PA25120", sub: "Found on shelf A1, not on the system", before: 0, after: 40, unit: "tablets", value: 120, problem: true };

export function ReviewCommitSection() {
  const [fixed, setFixed] = React.useState(false);
  const [partial, setPartial] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [run, setRun] = React.useState(0);

  const lines = [...baseLines, fixed ? { ...newBatch, problem: false, sub: "Found on shelf A1 · expiry 03/2028 entered" } : newBatch];
  const changed = lines.filter((l) => l.after !== l.before);
  const atCost = changed.reduce((s, l) => s + l.value, 0);
  const tramadol = baseLines.find((l) => l.name.startsWith("Tramadol"));

  const issues: ReviewIssue[] = [
    ...(fixed ? [] : [{ id: "i1", level: "blocking" as const, message: "PA25120 was counted but has no expiry date. Enter it before applying.", lineId: "nb" }]),
    ...(tramadol && tramadol.after !== tramadol.before
      ? [{ id: "i2", level: "warning" as const, message: `Tramadol is a controlled medicine and is ${Math.abs(tramadol.after - tramadol.before)} short. A pharmacist should sign off the count.`, lineId: tramadol.id }]
      : []),
  ];

  const onCommit = async (): Promise<CommitResult> => {
    await new Promise((r) => setTimeout(r, 1200));
    if (partial) {
      return {
        ok: false,
        applied: changed.slice(0, -2).map((l) => l.name),
        failed: changed.slice(-2).map((l) => `${l.name} (batch locked by an open sale)`),
      };
    }
    return {
      ok: true,
      summary: `${changed.length} adjustments applied to Westlands Main`,
      created: [
        { label: `Stock take ST-2026-041 (${lines.length} lines counted)`, href: "#st-2026-041" },
        { label: `${changed.length} stock adjustments`, href: "#adjustments" },
        { label: "Activity log entry", href: "#activity" },
      ],
    };
  };

  return (
    <Section
      id="review-commit"
      title="Review before commit"
      description="Before many stock or money changes are written at once (stock take, goods receiving, payroll, CSV import) the user sees the totals, any problems and every change. Problems link to their line; differences carry a sign and a word, not colour alone. Commit with a blocking problem moves focus to the problems; otherwise a confirmation restates the warnings. While applying, the page cannot be left. The result links to everything created, or lists exactly what failed."
    >
      <Example title="Stock take review" description="Fix the blocking problem to apply; try partly failing; the action bar sticks as the table scrolls" bare>
        <div className="flex flex-wrap items-center gap-4 border-b border-border px-4 py-2 text-xs text-muted-foreground">
          <label className="flex cursor-pointer items-center gap-2">
            <Switch checked={fixed} onCheckedChange={setFixed} /> Enter the missing expiry date
          </label>
          <label className="flex cursor-pointer items-center gap-2">
            <Switch checked={partial} onCheckedChange={setPartial} /> Make applying partly fail
          </label>
          <label className="flex cursor-pointer items-center gap-2">
            <Switch checked={loading} onCheckedChange={setLoading} /> Calculating
          </label>
          <Button variant="ghost" size="sm" className="ml-auto" onClick={() => setRun((r) => r + 1)}>
            Reset demo
          </Button>
        </div>
        <div className="max-h-[620px] overflow-y-auto px-4 pt-4">
          <ReviewBeforeCommit
            key={run}
            title="Review stock take: Westlands Main, 20 Oct 2026"
            steps={["Count", "Review", "Apply"]}
            currentStep={1}
            loading={loading}
            totals={[
              { label: "Lines counted", value: lines.length },
              { label: "Lines with a difference", value: changed.length },
              { label: "Difference at cost", value: `${atCost < 0 ? "−" : "+"}${formatKES(Math.abs(atCost), { decimals: true })}` },
              { label: "Problems", value: issues.filter((i) => i.level === "blocking").length },
            ]}
            issues={issues}
            lines={lines}
            beforeLabel="System"
            afterLabel="Counted"
            commitLabel={`Apply ${changed.length} adjustments`}
            busyLabel="Applying…"
            confirm={{
              level: "B",
              title: `Apply ${changed.length} stock adjustments?`,
              consequences: [`Stock changes by ${atCost < 0 ? "−" : "+"}${formatKES(Math.abs(atCost), { decimals: true })} at cost across ${changed.length} lines.`, "It can't be undone; a new count would be needed to correct it."],
              reasons: ["Routine stock take", "Spot check", "Investigating a discrepancy", "Other"],
            }}
            onBack={() => document.getElementById("review-commit")?.scrollIntoView({ block: "start" })}
            onCommit={onCommit}
          />
        </div>
      </Example>
    </Section>
  );
}
