"use client";

import * as React from "react";

import { Example } from "@/components/design-system/example";
import { ApprovalDialog, ApprovalQueueItem, ApprovalRecord, type ApprovalDecision, type ApprovalRequest, type Approver } from "@/components/medora/approval";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/toast";
import { TODAY } from "@/lib/mock-data";

const APPROVERS: Approver[] = [
  { id: 1, name: "Wanjiru Kamau", role: "Admin" },
  { id: 2, name: "Brian Otieno", role: "Pharmacist in charge" },
];

// A fixed time, so the server and the browser render the same thing.
const make = (r: Omit<ApprovalRequest, "requestedAt" | "requestedBy">): ApprovalRequest => ({ ...r, requestedBy: "Kevin Mutua (Cashier)", requestedAt: new Date(`${TODAY}T14:01:00`) });

const REQUESTS: { label: string; request: ApprovalRequest }[] = [
  {
    label: "25% discount",
    request: make({
      id: "APR-0141",
      action: "discount",
      title: "25% discount on Augmentin 625 mg",
      why: "Above your 10% discount limit",
      amount: 52.5,
      details: [
        { label: "Line", value: "1 strip × 210.00" },
        { label: "Discount", value: "25% (KES 52.50)" },
        { label: "Your limit", value: "10%" },
      ],
    }),
  },
  {
    label: "Void a completed sale",
    request: make({
      id: "APR-0142",
      action: "void",
      title: "Void sale RCP-005197",
      why: "Completed sales can only be voided by a manager",
      amount: 455,
      details: [
        { label: "Paid by", value: "M-Pesa SJK4L8P2QX" },
        { label: "Items", value: "4" },
      ],
    }),
  },
  {
    label: "Refund over limit",
    request: make({
      id: "APR-0143",
      action: "refund",
      title: "Refund on RCP-005178",
      why: "Refunds above KES 1,000 need a manager",
      amount: 2400,
      details: [{ label: "Item", value: "Lantus SoloStar × 1" }],
    }),
  },
  {
    label: "Sell below cost",
    request: make({
      id: "APR-0144",
      action: "below-cost",
      title: "Sell Benylin 100 ml at 180.00",
      why: "Below the batch cost of 210.00",
      amount: 30,
      details: [
        { label: "Usual price", value: "320.00" },
        { label: "Loss per bottle", value: "30.00" },
      ],
    }),
  },
];

export function ApprovalDemos() {
  const [active, setActive] = React.useState<ApprovalRequest | null>(null);
  const [open, setOpen] = React.useState(false);
  const [log, setLog] = React.useState<{ request: ApprovalRequest; decision: ApprovalDecision }[]>([]);
  const [queue, setQueue] = React.useState<ApprovalRequest[]>(() => [
    make({ id: "APR-0139", action: "price-override", title: "Change price of Vitamin C 500 mg to 6.00", why: "Shelf label shows 6.00, system says 8.00", amount: 2 }),
    make({ id: "APR-0140", action: "discount", title: "15% discount on Surgical Gloves", why: "Above Achieng's 10% limit", amount: 135 }),
  ]);

  return (
    <div className="space-y-4">
      <Example
        title="At the till"
        description="Pick a request. Manager is here: choose a reason, then PIN 1234 (try a wrong one three times to see the lock). Send to a manager: approved remotely after 4 s"
      >
        <div className="flex flex-wrap gap-2">
          {REQUESTS.map((r) => (
            <Button
              key={r.request.id}
              variant="outline"
              onClick={() => {
                setActive({ ...r.request, requestedAt: new Date() });
                setOpen(true);
              }}
            >
              {r.label}
            </Button>
          ))}
        </div>
        {active ? (
          <ApprovalDialog
            request={active}
            approvers={APPROVERS}
            open={open}
            onOpenChange={setOpen}
            onDecision={(d) => {
              setLog((l) => [{ request: active, decision: d }, ...l]);
              toast.add({ type: "success", title: `Approved by ${d.approver.name}`, description: `${active.title}. Reason: ${d.reason}.` });
            }}
          />
        ) : null}
      </Example>

      <div className="grid gap-4 lg:grid-cols-2">
        <Example title="Approval records" description="What is logged against the sale and in the audit trail">
          <div className="space-y-2">
            {log.length ? (
              log.map((e) => <ApprovalRecord key={`${e.request.id}-${e.decision.at.getTime()}`} request={e.request} decision={e.decision} />)
            ) : (
              <ApprovalRecord request={REQUESTS[0].request} />
            )}
            {log.length === 0 ? <p className="text-xs text-muted-foreground">Approve a request above to add its record here.</p> : null}
          </div>
        </Example>
        <Example title="Manager's queue" description="Requests sent from a till; declining needs a note for the cashier">
          <div className="space-y-2">
            {queue.length ? (
              queue.map((q) => (
                <ApprovalQueueItem
                  key={q.id}
                  request={q}
                  onApprove={() => {
                    setQueue((xs) => xs.filter((x) => x.id !== q.id));
                    toast.add({ type: "success", title: "Approved", description: `${q.title}. The till continues.` });
                  }}
                  onDecline={(note) => {
                    setQueue((xs) => xs.filter((x) => x.id !== q.id));
                    toast.add({ title: "Declined", description: `${q.title}. The cashier sees: “${note}”.` });
                  }}
                />
              ))
            ) : (
              <p className="py-6 text-center text-sm text-muted-foreground">No requests waiting.</p>
            )}
          </div>
        </Example>
      </div>
    </div>
  );
}
