"use client";

import { BoxesIcon, ClipboardListIcon, FileTextIcon, PackageSearchIcon, ReceiptTextIcon, TruckIcon, UsersIcon, WalletIcon } from "lucide-react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { ActivityRow, BranchSwitcher, NotificationItem, PermissionMatrix, SyncBanner } from "@/components/medora/records/activity";
import { ConfirmDestructive, EmptyState, InfoCallout } from "@/components/medora/records/states";
import { branches, customers, recentActivity, staff } from "@/lib/mock-data";

const actor = (id: number) => staff.find((s) => s.id === id)?.name ?? "Unknown";
const owing = customers.find((c) => c.balance > 0) ?? customers[1];

const modules = ["Point of sale", "Inventory", "Prescriptions", "Customers", "Suppliers", "Reports", "Expenses", "Users and settings"];
const grants: Record<string, boolean> = {};
for (const m of modules) {
  grants[`Pharmacist:${m}`] = ["Point of sale", "Inventory", "Prescriptions", "Customers", "Suppliers", "Reports"].includes(m);
  grants[`Cashier:${m}`] = ["Point of sale", "Customers"].includes(m);
}

export function ActivitySection() {
  return (
    <>
      <Section id="activity" title="Activity, alerts and access" description="What happened, what needs attention, whether the device is connected, and who may do what.">
        <Example title="Activity feed item and audit log row" description="Feed (dashboard) above, audit (settings) below" bare>
          <div>
            {recentActivity.slice(0, 4).map((a) => (
              <ActivityRow key={a.id} actor={actor(a.userId)} action={a.action} detail={a.detail} at={a.at.slice(11)} />
            ))}
          </div>
          <div className="border-t border-border">
            {recentActivity.slice(0, 4).map((a) => (
              <ActivityRow key={a.id} variant="audit" actor={actor(a.userId)} action={a.action} detail={a.detail} at={a.at} />
            ))}
          </div>
        </Example>
        <Example title="Notification list item" description="Low stock (unread), expiring, M-Pesa received, M-Pesa failed" bare>
          <NotificationItem kind="low-stock" unread title="Amoxicillin 500mg is low" body="12 units left; the reorder level is 40." at="16:30" action={{ label: "Create purchase order" }} />
          <NotificationItem kind="expiring" title="3 batches expire within 30 days" body="Cetirizine 10mg, batch CT2604, 48 units, expires 12 Nov." at="09:00" action={{ label: "Review expiring stock" }} />
          <NotificationItem kind="mpesa-success" title="M-Pesa payment received" body="KES 1,840 from 0712 345 678 for RCP-005200." at="16:42" />
          <NotificationItem kind="mpesa-failed" unread title="M-Pesa payment failed" body="The customer cancelled the prompt on RCP-005201. Charge another way." at="16:44" />
        </Example>
        <Example title="Offline / sync banner" description="Offline, syncing, synced, error" className="space-y-2">
          <SyncBanner state="offline" pending={3} />
          <SyncBanner state="syncing" pending={3} />
          <SyncBanner state="synced" />
          <SyncBanner state="error" pending={2} />
        </Example>
        <Example title="Branch switcher" description="Admin can switch; a cashier is fixed to their branch" className="space-y-3">
          <BranchSwitcher branches={branches} initial={1} />
          <BranchSwitcher branches={branches} initial={3} locked />
        </Example>
        <Example title="Permission matrix" description="Roles by modules; Admin is fixed on. Second is read-only." className="grid gap-4 lg:grid-cols-2">
          <PermissionMatrix roles={["Admin", "Pharmacist", "Cashier"]} modules={modules} initial={grants} />
          <PermissionMatrix roles={["Admin", "Pharmacist", "Cashier"]} modules={modules.slice(0, 4)} initial={grants} disabled />
        </Example>
      </Section>

    </>
  );
}

export function EmptyHelpSection() {
  return (
    <>
      <Section id="empty-and-help" title="Empty states, help and confirmation" description="What to say when a list has nothing in it, how to explain a rule inline, and how to word a destructive confirmation.">
        <Example title="Empty state per module" description="Says what is missing and offers the one next action" className="grid gap-3 md:grid-cols-2">
          <EmptyState icon={ReceiptTextIcon} title="No sales yet today" description="Completed sales appear here as soon as the first one is rung up." action={{ label: "Open the till" }} />
          <EmptyState icon={BoxesIcon} title="No products in stock records" description="Add your first product or import a list from a spreadsheet." action={{ label: "Add product" }} />
          <EmptyState icon={FileTextIcon} title="No prescriptions waiting" description="New prescriptions from the counter appear here for verification." action={{ label: "Record prescription" }} />
          <EmptyState icon={UsersIcon} title="No customers yet" description="Add a customer to sell on account or keep a purchase history." action={{ label: "Add customer" }} />
          <EmptyState icon={TruckIcon} title="No suppliers yet" description="Add a supplier before you raise a purchase order." action={{ label: "Add supplier" }} />
          <EmptyState icon={ClipboardListIcon} title="No purchase orders" description="Orders you raise with suppliers are tracked here until delivery." action={{ label: "New purchase order" }} />
          <EmptyState icon={WalletIcon} title="No expenses recorded" description="Record rent, wages and utilities to see net profit in reports." action={{ label: "Add expense" }} />
          <EmptyState icon={PackageSearchIcon} title="No results for that search" description="Check the spelling, or search by barcode or generic name." />
        </Example>
        <Example title="Inline help / info callout" description="Info, warning, error" className="space-y-2">
          <InfoCallout title="Credit sales need a customer">Choose a registered customer with a credit limit. Walk-in customers cannot buy on account.</InfoCallout>
          <InfoCallout tone="warning" title="Stock is per pharmacy">Branch stock levels are not tracked separately yet, so every branch sees the same quantities.</InfoCallout>
          <InfoCallout tone="error">This customer is over their credit limit. Collect a payment before selling more on account.</InfoCallout>
        </Example>
        <Example title="Confirm destructive: delete customer" description="Name the consequence, name the button after the action" className="grid gap-4 lg:grid-cols-2">
          <ConfirmDestructive
            title={`Delete ${owing.name}?`}
            consequence={
              <>
                <p>Their past sales stay in your reports but will show as walk-in customers. Their statement and payment history will no longer be available.</p>
                <p>This cannot be undone.</p>
              </>
            }
            confirmLabel="Delete customer"
          />
          <ConfirmDestructive title={`Delete ${owing.name}?`} consequence={<p>Deleting customer record and payments.</p>} confirmLabel="Delete customer" busy />
        </Example>
      </Section>
    </>
  );
}
