"use client";

import * as React from "react";
import { ExternalLinkIcon, PlusIcon } from "lucide-react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { DescriptionList } from "@/components/medora/description-list";
import { DockedDetail, RecordDrawer, type DrawerState } from "@/components/medora/drawer";
import { RecordStatusBadge } from "@/components/medora/records/status";
import { SensitiveNotice, maskPhone, maskedLabel } from "@/components/medora/sensitive";
import { Button } from "@/components/ui/button";
import { Field, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { toast } from "@/components/ui/toast";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { customers, formatDate, recentSales, staff } from "@/lib/mock-data";
import { cn } from "@/lib/utils";

const SALES = recentSales.slice(0, 8);
const kes = (n: number) => `KES ${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

function SaleDetails({ i }: { i: number }) {
  const s = SALES[i];
  const customer = customers.find((c) => c.id === s.customerId);
  return (
    <DescriptionList
      variant="inline"
      density="compact"
      items={[
        { label: "Date", value: `${formatDate(s.createdAt)}, ${s.time}` },
        { label: "Customer", value: customer?.name ?? "Walk-in" },
        { label: "Served by", value: staff.find((u) => u.id === s.cashierId)?.name },
        { label: "Items", value: String(s.items) },
        { label: "Subtotal", value: kes(s.subtotal), money: true },
        { label: "VAT", value: kes(s.vat), money: true },
        { label: "Total", value: kes(s.total), money: true },
        { label: "Payment", value: s.method },
      ]}
    />
  );
}

function SaleList({ selected, onOpen }: { selected: number | null; onOpen: (i: number) => void }) {
  return (
    <ul className="divide-y divide-border text-sm">
      {SALES.map((s, i) => (
        <li key={s.id}>
          <button
            type="button"
            data-row={i}
            onClick={() => onOpen(i)}
            aria-current={selected === i || undefined}
            className={cn(
              "flex w-full cursor-pointer items-center gap-3 border-l-2 px-3 py-2 text-left outline-none hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",
              selected === i ? "border-l-[var(--color-border-strong)] bg-[var(--color-bg-selected)]" : "border-l-transparent",
            )}
          >
            <span className="font-medium tabular-nums">{s.receipt}</span>
            <span className="text-muted-foreground">{s.time}</span>
            <span className="ml-auto tabular-nums">{kes(s.total)}</span>
          </button>
        </li>
      ))}
    </ul>
  );
}

function useStateSim() {
  const [state, setState] = React.useState<DrawerState>("ready");
  const [mode, setMode] = React.useState<"ok" | "slow" | "fail">("ok");
  const load = React.useCallback(
    (m = mode) => {
      if (m === "ok") return setState("ready");
      setState("loading");
      setTimeout(() => setState(m === "fail" ? "error" : "ready"), 900);
    },
    [mode],
  );
  return { state, mode, setMode, load, setState };
}

function DetailDrawerDemo() {
  const [index, setIndex] = React.useState<number | null>(null);
  const [changed, setChanged] = React.useState(false);
  const sim = useStateSim();
  const open = (i: number) => {
    setIndex(i);
    sim.load();
  };
  const i = index ?? 0;
  return (
    <Example title="Detail drawer" description="Open a sale from the list; Previous and Next move through it without closing. The opened row stays highlighted; closing returns focus to it" bare>
      <div className="flex flex-wrap items-center gap-3 border-b border-border px-4 py-3 text-sm">
        <span className="text-muted-foreground">Loading:</span>
        <ToggleGroup variant="outline" size="sm" spacing={0} aria-label="Load behaviour" value={[sim.mode]} onValueChange={(v: string[]) => v[0] && sim.setMode(v[0] as "ok" | "slow" | "fail")}>
          <ToggleGroupItem value="ok">Instant</ToggleGroupItem>
          <ToggleGroupItem value="slow">Slow</ToggleGroupItem>
          <ToggleGroupItem value="fail">Fails</ToggleGroupItem>
        </ToggleGroup>
      </div>
      <SaleList selected={index} onOpen={open} />
      <RecordDrawer
        open={index !== null}
        onOpenChange={(o) => {
          if (!o) {
            const row = index;
            setIndex(null);
            setChanged(false);
            setTimeout(() => document.querySelector<HTMLButtonElement>(`[data-row="${row}"]`)?.focus(), 0);
          }
        }}
        title={SALES[i].receipt}
        subtitle={<RecordStatusBadge domain="sale" status={SALES[i].status === "Held" ? "Held" : "Paid"} />}
        actions={
          <Button variant="ghost" size="sm" render={<a href="#" />} nativeButton={false}>
            <ExternalLinkIcon data-icon="inline-start" />
            Full page
          </Button>
        }
        nav={{
          noun: "sale",
          position: `${i + 1} of ${SALES.length}`,
          onPrev: i > 0 ? () => open(i - 1) : undefined,
          onNext: i < SALES.length - 1 ? () => open(i + 1) : undefined,
        }}
        state={sim.state}
        onRetry={() => sim.load("slow")}
        changedElsewhere={changed}
        onReload={() => {
          setChanged(false);
          sim.load("slow");
        }}
      >
        <div className="space-y-4">
          <SaleDetails i={i} />
          <Button size="sm" variant="ghost" onClick={() => setChanged(true)}>
            Simulate a change by someone else
          </Button>
        </div>
      </RecordDrawer>
    </Example>
  );
}

function EditDrawerDemo() {
  const [open, setOpen] = React.useState(false);
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [saving, setSaving] = React.useState(false);
  const reset = () => {
    setName("");
    setPhone("");
  };
  return (
    <Example title="Edit drawer" description="Quick-add a supplier while building a PO. Backdrop clicks don't close it; closing with something typed asks first">
      <Button variant="outline" onClick={() => setOpen(true)}>
        <PlusIcon data-icon="inline-start" />
        New supplier
      </Button>
      <RecordDrawer
        open={open}
        onOpenChange={(o) => {
          setOpen(o);
          if (!o) reset();
        }}
        variant="edit"
        dirty={!!(name || phone)}
        onDiscard={reset}
        saving={saving}
        title="New supplier"
        footer={
          <>
            <Button variant="outline" onClick={() => setOpen(false)} disabled={saving}>
              Cancel
            </Button>
            <Button
              disabled={saving || !name}
              onClick={() => {
                setSaving(true);
                setTimeout(() => {
                  setSaving(false);
                  setOpen(false);
                  toast.add({ title: "Supplier saved", description: name });
                  reset();
                }, 900);
              }}
            >
              {saving ? <Spinner /> : null}
              {saving ? "Saving…" : "Save supplier"}
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Field>
            <FieldLabel htmlFor="sup-name">Supplier name</FieldLabel>
            <Input id="sup-name" value={name} onChange={(e) => setName(e.target.value)} autoFocus />
          </Field>
          <Field>
            <FieldLabel htmlFor="sup-phone">Phone</FieldLabel>
            <Input id="sup-phone" value={phone} onChange={(e) => setPhone(e.target.value)} inputMode="tel" />
          </Field>
        </div>
      </RecordDrawer>
    </Example>
  );
}

function DockedDemo() {
  const [index, setIndex] = React.useState<number | null>(2);
  const i = index ?? 0;
  return (
    <Example title="Docked master-detail" description="No backdrop: the list narrows and stays usable. A labelled region; Esc or Close panel closes it. Below 768 px it opens as a drawer" bare>
      <div className="h-[380px] overflow-hidden">
        <DockedDetail
          open={index !== null}
          onClose={() => setIndex(null)}
          label={`Sale ${SALES[i].receipt} details`}
          title={SALES[i].receipt}
          subtitle={`${formatDate(SALES[i].createdAt)}, ${SALES[i].time}`}
          nav={{ noun: "sale", onPrev: i > 0 ? () => setIndex(i - 1) : undefined, onNext: i < SALES.length - 1 ? () => setIndex(i + 1) : undefined }}
          list={<SaleList selected={index} onOpen={setIndex} />}
        >
          <SaleDetails i={i} />
        </DockedDetail>
      </div>
    </Example>
  );
}

function SensitiveDemo() {
  return (
    <div className="grid gap-4 md:grid-cols-2">
      <Example title="Sensitive-data notice" description="Top of a medical or pay section, every time; calm, not dismissible. Roles without access see neither the section nor the notice">
        <div className="space-y-3">
          <SensitiveNotice kind="medical" />
          <DescriptionList
            variant="inline"
            density="compact"
            items={[
              { label: "Allergies", value: "Penicillin (rash, 2023)" },
              { label: "Conditions", value: "Type 2 diabetes" },
              { label: "Current medicines", value: "Metformin 500 mg twice daily" },
            ]}
          />
          <SensitiveNotice kind="pay" />
        </div>
      </Example>
      <Example title="Partly masked phone" description="On screens facing the queue (M-Pesa waiting, customer display); screen readers hear the last three digits">
        <ul className="space-y-2 text-sm">
          {["0712 345 123", "+254 733 000 111", "0110 222 333"].map((p) => (
            <li key={p} className="flex justify-between gap-4">
              <span className="text-muted-foreground">{p}</span>
              <span className="font-medium tabular-nums">
                <span aria-hidden>{maskPhone(p)}</span>
                <span className="sr-only">{maskedLabel(p)}</span>
              </span>
            </li>
          ))}
        </ul>
      </Example>
    </div>
  );
}

export function DrawersSection() {
  return (
    <Section
      id="drawers"
      title="Drawers"
      description="Medora drawers (components/medora/drawer.tsx): a detail drawer to look through records from a list, an edit drawer for quick-add and quick-edit, and a docked panel beside the list. The title comes from the row, so it shows at once while the body loads; loading, failed and changed-by-someone-else states sit in the body."
    >
      <DetailDrawerDemo />
      <EditDrawerDemo />
      <DockedDemo />
    </Section>
  );
}

export function SensitiveSection() {
  return (
    <Section id="sensitive" title="Sensitive data" description="Medical and pay data are shown only to permitted roles, and access to medical records is logged. Integration secrets are on the Forms page (secret input).">
      <SensitiveDemo />
    </Section>
  );
}
