"use client";

import * as React from "react";
import { BuildingIcon, PillIcon, SlidersHorizontalIcon, SparklesIcon } from "lucide-react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { FilterChips, LabelTag, type AppliedFilter } from "@/components/medora/chips";
import { DescriptionList } from "@/components/medora/description-list";
import { DiffView } from "@/components/medora/diff-view";
import { Button } from "@/components/ui/button";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";

const START: AppliedFilter[] = [
  { key: "branch", field: "Branch", value: "Westlands" },
  { key: "category", field: "Category", value: "Antibiotics" },
  { key: "method", field: "Payment", value: "M-Pesa" },
  { key: "period", field: "Period", value: "1–20 Oct 2026" },
];

function Chips() {
  const [filters, setFilters] = React.useState(START);
  const filtersBtn = React.useRef<HTMLButtonElement>(null);
  // Sales shown for 0–4 applied filters.
  const count = [5136, 1284, 612, 233, 41][filters.length];
  return (
    <Example title="Filter chips" description="Remove with the × (Enter, Space, Backspace or Delete); focus moves to the next chip, then back to Filters. Clear all appears with two or more">
      <div className="space-y-3">
        <div className="flex flex-wrap items-center gap-2">
          <Button ref={filtersBtn} variant="outline" size="sm" onClick={() => setFilters(START)}>
            <SlidersHorizontalIcon data-icon="inline-start" />
            Filters{filters.length ? ` (${filters.length})` : ""}
          </Button>
          <FilterChips
            filters={filters}
            onRemove={(k) => setFilters((f) => f.filter((x) => x.key !== k))}
            onClearAll={() => setFilters([])}
            returnFocusTo={filtersBtn}
            announce={`Showing ${count.toLocaleString("en-US")} sales.`}
          />
        </div>
        <p className="text-sm text-muted-foreground tabular-nums">
          Showing {count.toLocaleString("en-US")} sales. (Demo: the Filters button puts the four filters back.)
        </p>
      </div>
    </Example>
  );
}

function Tags() {
  return (
    <Example title="Label tags" description="Attributes, not states, and not interactive. Lime is for New or Featured only, one or two per screen" className="flex flex-wrap items-center gap-2">
      <LabelTag icon={PillIcon}>Rx</LabelTag>
      <LabelTag>Service</LabelTag>
      <LabelTag icon={BuildingIcon}>Company</LabelTag>
      <LabelTag>Insurance: AAR</LabelTag>
      <LabelTag size="comfortable">Wholesale</LabelTag>
      <LabelTag accent icon={SparklesIcon}>
        New
      </LabelTag>
    </Example>
  );
}

function Descriptions() {
  const [loading, setLoading] = React.useState(false);
  const [role, setRole] = React.useState<"admin" | "cashier">("admin");
  const admin = role === "admin";
  return (
    <>
      <Example title="Stacked grid" description="Profile header. Not recorded reads —; a value the role can't see isn't shown at all and the grid closes up" bare>
        <div className="flex flex-wrap items-center gap-3 border-b border-border px-4 py-3">
          <ToggleGroup variant="outline" size="sm" spacing={0} aria-label="Viewing as" value={[role]} onValueChange={(v: string[]) => v[0] && setRole(v[0] as "admin" | "cashier")}>
            <ToggleGroupItem value="admin">Admin</ToggleGroupItem>
            <ToggleGroupItem value="cashier">Cashier</ToggleGroupItem>
          </ToggleGroup>
          <Button
            size="sm"
            variant="ghost"
            onClick={() => {
              setLoading(true);
              setTimeout(() => setLoading(false), 1200);
            }}
          >
            Show loading
          </Button>
        </div>
        <div className="p-4">
          <DescriptionList
            loading={loading}
            columns={4}
            items={[
              { label: "Phone", value: "0712 345 678" },
              { label: "Email", value: "mary.wambui@example.com" },
              { label: "KRA PIN", value: "A012345678Z" },
              { label: "Customer group", value: "Insurance: AAR" },
              ...(admin
                ? [
                    { label: "Credit limit", value: "KES 20,000.00", money: true },
                    { label: "Balance", value: "KES 3,297.20", money: true },
                  ]
                : []),
              { label: "Last visit", value: "18 Oct 2026" },
              { label: "Date of birth", value: "" },
              ...(admin ? [{ label: "Allergies", value: "Penicillin (rash, 2023)", span: 2 as const }] : []),
            ]}
            note={admin ? "Viewing medical details is logged." : undefined}
          />
        </div>
      </Example>
      <div className="grid gap-4 md:grid-cols-2">
        <Example title="Inline" description="Drawers and narrow panels; money left-aligned with tabular figures; an M-Pesa secret reads Saved, never the value">
          <DescriptionList
            variant="inline"
            title="Sale SALE-005200"
            titleAction={
              <Button size="xs" variant="ghost">
                Edit
              </Button>
            }
            items={[
              { label: "Date", value: "20 Oct 2026, 14:32" },
              { label: "Customer", value: <a href="#" className="text-primary underline-offset-2 hover:underline">Mary Wambui</a> },
              { label: "Served by", value: "Kevin Mutua" },
              { label: "Total", value: "KES 481.40", money: true },
              { label: "M-Pesa passkey", value: "Saved 12 Sep 2026" },
              { label: "Notes", value: null },
            ]}
          />
        </Example>
        <Example title="Summary" description="Before a commit; the last row is emphasised and figures right-align">
          <DescriptionList
            variant="summary"
            items={[
              { label: "Lines", value: "42" },
              { label: "Quantity", value: "1,250" },
              { label: "VAT", value: "KES 2,416.00", money: true },
              { label: "Value at cost", value: "KES 84,000.00", money: true },
            ]}
          />
        </Example>
      </div>
    </>
  );
}

function Diffs() {
  const [kind, setKind] = React.useState<"updated" | "lines" | "created" | "deactivated" | "empty" | "loading" | "error">("updated");
  const base = { who: "Jane Wanjiru", where: "Westlands Main", at: "20 Oct 2026, 14:05" };
  return (
    <Example title="Diff view" description="From an activity log entry's View. Only changed fields; Before is muted, After has an arrow; not red and green" bare>
      <div className="border-b border-border px-4 py-3">
        <ToggleGroup variant="outline" size="sm" spacing={0} aria-label="Change" value={[kind]} onValueChange={(v: string[]) => v[0] && setKind(v[0] as typeof kind)} className="flex-wrap">
          {(["updated", "lines", "created", "deactivated", "empty", "loading", "error"] as const).map((k) => (
            <ToggleGroupItem key={k} value={k}>
              {{ updated: "Fields", lines: "Lines", created: "Created", deactivated: "Deactivated", empty: "No changes", loading: "Loading", error: "Error" }[k]}
            </ToggleGroupItem>
          ))}
        </ToggleGroup>
      </div>
      <div className="max-w-2xl p-4">
        {kind === "updated" || kind === "loading" || kind === "error" || kind === "empty" ? (
          <DiffView
            {...base}
            action={kind === "empty" ? "Report exported" : "Product updated"}
            record={kind === "empty" ? "Sales by branch" : "Amoxicillin 500 mg capsules"}
            module={kind === "empty" ? "Reports" : "Inventory"}
            state={kind === "loading" ? "loading" : kind === "error" ? "error" : "ready"}
            onRetry={() => setKind("updated")}
            hiddenCount={kind === "updated" ? 1 : 0}
            changes={
              kind === "empty"
                ? []
                : [
                    { field: "Selling price", before: "KES 12.00", after: "KES 15.00" },
                    { field: "Reorder quantity", before: "200 capsules", after: "300 capsules" },
                    { field: "Shelf", after: "A3" },
                    { field: "Supplier", before: "Harleys Ltd (deleted)", after: "Dawa Distributors Ltd" },
                    {
                      field: "Dosage notes",
                      long: true,
                      before: "Take one capsule three times a day.",
                      after: "Take one capsule three times a day for 7 days. Finish the course even if you feel better. Not for patients allergic to penicillin.",
                    },
                  ]
            }
          />
        ) : kind === "lines" ? (
          <DiffView
            {...base}
            action="GRN corrected"
            record="GRN-2026-0187"
            module="Purchases"
            changes={[
              { line: "Panadol 500 mg · PN30981", field: "Quantity received", before: "300", after: "280" },
              { line: "Panadol 500 mg · PN30981", field: "Expiry", before: "31 Jan 2028", after: "31 Dec 2027" },
              { line: "Amoxil 500 mg · AX55102", field: "Batch", before: "AX55120", after: "AX55102" },
            ]}
          />
        ) : kind === "created" ? (
          <DiffView
            {...base}
            kind="created"
            action="User added"
            record="Faith Njeri"
            module="Settings"
            changes={[
              { field: "Role", after: "Pharmacist" },
              { field: "Branch", after: "Westlands Main" },
              { field: "Password", after: "set", sensitive: true },
            ]}
          />
        ) : (
          <DiffView
            {...base}
            kind="deactivated"
            action="Supplier deactivated"
            record="Harleys Ltd"
            module="Purchases"
            changes={[
              { field: "Payment terms", before: "30 days" },
              { field: "Balance owed", before: "KES 0.00" },
            ]}
          />
        )}
      </div>
    </Example>
  );
}

export function RecordBitsSection() {
  return (
    <>
      <Section
        id="chips"
        title="Tags and filter chips"
        description="A filter chip shows a filter applied to a table or chart and removes it; a label tag describes a record. Neither is a status (use a badge) or an action (use a button)."
      >
        <Chips />
        <Tags />
      </Section>
      <Section id="description-list" title="Description list" description="One record's attributes as read-only label–value pairs: stacked in a profile header, inline in drawers, and as a summary before a commit.">
        <Descriptions />
      </Section>
      <Section id="diff" title="Diff view" description="What a change did, as Before → After, opened from the activity log, product history or a batch correction.">
        <Diffs />
      </Section>
    </>
  );
}
