"use client";

import * as React from "react";
import { ArchiveIcon, DownloadIcon, PencilIcon, PlusIcon, PrinterIcon, StoreIcon, UploadIcon } from "lucide-react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { MedoraPageHeader, type HeaderAction } from "@/components/medora/page-header";
import { RecordStatusBadge } from "@/components/medora/records/status";
import { Badge } from "@/components/ui/badge";
import { toast } from "@/components/ui/toast";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";

const say = (title: string) => () => toast.add({ title, description: "Design-system preview." });

const PO_SECONDARY: HeaderAction[] = [
  { label: "Import CSV", icon: UploadIcon, onSelect: say("Import CSV") },
  { label: "Export", icon: DownloadIcon, onSelect: say("Export") },
];
const PO_MORE: HeaderAction[] = [
  { label: "Print list", icon: PrinterIcon, onSelect: say("Print list") },
  { label: "Archive received orders", icon: ArchiveIcon, onSelect: say("Archive"), destructive: true },
];

const WIDTHS = { wide: 1040, middling: 760, narrow: 380 } as const;

function Branch({ name }: { name: string }) {
  return (
    <>
      <StoreIcon className="size-3.5" aria-hidden /> {name}
    </>
  );
}

export function PageHeaderSection() {
  const [width, setWidth] = React.useState<keyof typeof WIDTHS>("wide");
  return (
    <Section
      id="page-header"
      title="Page header"
      description="The top of every page: title, one-sentence description, meta (branch · period · As at · status), at most one primary action on the right, up to two secondary actions, and More for the rest. It lays out by its own width: secondary actions fold into More before they would wrap, and on narrow screens the actions move under the title and breadcrumbs become a back link."
    >
      <Example title="Standard, at three widths" description="List page. Change the width to see the actions fold into More, then wrap below with the primary first" bare>
        <div className="border-b border-border px-4 py-3">
          <ToggleGroup variant="outline" size="sm" spacing={0} aria-label="Header width" value={[width]} onValueChange={(v: string[]) => v[0] && setWidth(v[0] as keyof typeof WIDTHS)}>
            <ToggleGroupItem value="wide">Wide</ToggleGroupItem>
            <ToggleGroupItem value="middling">Middling</ToggleGroupItem>
            <ToggleGroupItem value="narrow">Narrow</ToggleGroupItem>
          </ToggleGroup>
        </div>
        <div className="overflow-x-auto bg-muted/40 p-4">
          <div className="rounded-lg border border-dashed border-border bg-background p-4" style={{ width: WIDTHS[width] }}>
            <MedoraPageHeader
              title="Purchase orders"
              description="Create, approve and receive orders to suppliers."
              meta={[<Branch key="b" name="Westlands Main" />, "1–20 Oct 2026", "As at 14:32"]}
              breadcrumbs={[{ label: "Purchases" }, { label: "Suppliers", href: "#" }, { label: "Purchase orders" }]}
              primary={{ label: "New purchase order", icon: PlusIcon, onSelect: say("New purchase order") }}
              secondary={PO_SECONDARY}
              more={PO_MORE}
            />
          </div>
        </div>
      </Example>

      <div className="grid gap-4">
        <Example title="Record" description="Detail page: the record's name, identifiers and status in the meta row, Edit as the only main action">
          <MedoraPageHeader
            variant="record"
            title="Mary Wambui"
            status={<RecordStatusBadge domain="user" status="Active" />}
            meta={["Customer since Mar 2024", "KRA PIN A012345678Z", "Account C-0042"]}
            breadcrumbs={[{ label: "Customers" }, { label: "Customer list", href: "#" }, { label: "Mary Wambui" }]}
            secondary={[{ label: "Edit", icon: PencilIcon, onSelect: say("Edit") }]}
            more={[
              { label: "View statement", onSelect: say("View statement") },
              { label: "Print statement", icon: PrinterIcon, onSelect: say("Print statement") },
            ]}
          />
        </Example>

        <Example title="Dashboard" description="The one large heading on the screen; meta repeats the applied period and branch from the filter bar">
          <MedoraPageHeader variant="dashboard" title="Good afternoon, Grace" meta={[<Branch key="b" name="All branches" />, "Today, 20 Oct 2026", "As at 14:32"]} />
        </Example>

        <Example title="Read-only record, deep trail" description="Five crumbs collapse the middle into a … menu; an approved record says it can't be edited">
          <MedoraPageHeader
            variant="record"
            title="Payroll, October 2026"
            status={<Badge variant="outline">Approved, can&apos;t be edited</Badge>}
            meta={["PAY-2026-10", "42 employees", "Approved by Peter Kamau, 18 Oct 2026"]}
            breadcrumbs={[{ label: "HR" }, { label: "Payroll", href: "#" }, { label: "2026", href: "#" }, { label: "Westlands Main", href: "#" }, { label: "Payroll, October 2026" }]}
            more={[
              { label: "Print payslips", icon: PrinterIcon, onSelect: say("Print payslips") },
              { label: "Export bank file", icon: DownloadIcon, onSelect: say("Export bank file") },
            ]}
          />
        </Example>

        <div className="grid gap-4 lg:grid-cols-2">
          <Example title="Primary hidden by permission" description="A Cashier sees no New action; Export stays secondary rather than being promoted">
            <MedoraPageHeader title="Expenses" description="Rent, utilities and other running costs." meta={["Westlands Main", "October 2026"]} secondary={[{ label: "Export", icon: DownloadIcon, onSelect: say("Export") }]} />
          </Example>
          <Example title="Action needs approval" description="Said before the user starts">
            <MedoraPageHeader
              title="Stock take"
              description="Count stock and post the differences."
              meta={["Westlands Main", "Last count 30 Sep 2026"]}
              primary={{ label: "Submit for approval", onSelect: say("Submit for approval") }}
              primaryNote="An Admin approves before stock changes."
            />
          </Example>
          <Example title="Loading" description="Title renders at once; As at shows a skeleton">
            <MedoraPageHeader title="Sales report" meta={["All branches", "1–20 Oct 2026"]} metaLoading secondary={[{ label: "Export", icon: DownloadIcon, disabled: true }]} />
          </Example>
          <Example title="Wizard and compact" description="Wizard: step in the meta, actions live in the wizard footer. Compact: POS tools, no description">
            <div className="space-y-5">
              <MedoraPageHeader variant="wizard" title="Receive goods" meta={["Step 2 of 3", "PO-2041 · Dawa Distributors Ltd"]} />
              <MedoraPageHeader variant="compact" title="Held sales" meta={["3 waiting"]} secondary={[{ label: "Clear all", onSelect: say("Clear all") }]} />
            </div>
          </Example>
        </div>
      </div>
    </Section>
  );
}
