"use client";

import * as React from "react";
import {
  BarChart3Icon,
  BookOpenIcon,
  FileTextIcon,
  HandCoinsIcon,
  PencilIcon,
  PlugIcon,
  PrinterIcon,

  SettingsIcon,
  ShoppingCartIcon,
  TruckIcon,
  UsersIcon,
  WarehouseIcon,
} from "lucide-react";

import { LabelTag } from "@/components/medora/chips";
import { DescriptionList } from "@/components/medora/description-list";
import { Launcher, type LauncherTile } from "@/components/medora/launcher";
import { MedoraPageHeader } from "@/components/medora/page-header";
import { AgingBuckets, BalanceSummary } from "@/components/medora/records/finance";
import { RecordStatusBadge } from "@/components/medora/records/status";
import { SensitiveNotice } from "@/components/medora/sensitive";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { customers, formatDate, formatKES } from "@/lib/mock-data";
import { Frame } from "./frame";

type Role = "Admin" | "Pharmacist" | "Cashier";

const customer = customers.find((c) => c.balance > 0 && c.creditLimit > 0) ?? customers[1];

const INVOICES = [
  { ref: "INV-2026-00783", date: "2026-10-03", amount: 5297.2, open: 3297.2 },
  { ref: "INV-2026-00741", date: "2026-09-12", amount: 2150, open: 0 },
  { ref: "INV-2026-00702", date: "2026-08-21", amount: 1800, open: 0 },
];
const PAYMENTS = [
  { ref: "PAY-0107", date: "2026-10-18", method: "M-Pesa", amount: 2000 },
  { ref: "PAY-0101", date: "2026-10-02", method: "Cash", amount: 2150 },
];

/** Detail / profile page template (spec 03 §11.2): record header, permission-aware tabs, content 8 / side summary 4. */
function DetailPage({ role }: { role: Role }) {
  const accounts = role === "Admin";
  const medical = role !== "Cashier";
  return (
    <div className="space-y-6">
      <MedoraPageHeader
        variant="record"
        title={customer.name}
        status={<RecordStatusBadge domain="sale" status="Credit" />}
        meta={["Customer since Mar 2024", "KRA PIN A012345678Z", "Account C-0042"]}
        breadcrumbs={[{ label: "Customers" }, { label: "Customer list", href: "#" }, { label: customer.name }]}
        secondary={role !== "Cashier" ? [{ label: "Edit", icon: PencilIcon }] : []}
        more={[{ label: "Print statement", icon: PrinterIcon }]}
      />
      <Tabs defaultValue="profile">
        <TabsList variant="line" className="w-full justify-start border-b border-border">
          <TabsTrigger value="profile">Profile</TabsTrigger>
          <TabsTrigger value="purchases">Purchases</TabsTrigger>
          {medical ? <TabsTrigger value="medical">Prescriptions &amp; medical</TabsTrigger> : null}
          {accounts ? <TabsTrigger value="account">Account</TabsTrigger> : null}
        </TabsList>
        <div className="mt-5 grid gap-6 xl:grid-cols-12">
          <div className="min-w-0 xl:col-span-8">
            <TabsContent value="profile">
              <DescriptionList
                columns={2}
                items={[
                  { label: "Phone", value: customer.phone },
                  { label: "Email", value: customer.email },
                  { label: "Customer group", value: <LabelTag>Insurance: AAR</LabelTag> },
                  { label: "Date of birth", value: "" },
                  { label: "Address", value: "Riverside Drive, Nairobi", span: 2 },
                ]}
              />
            </TabsContent>
            <TabsContent value="purchases">
              <p className="text-sm text-muted-foreground">
                {customer.visits} visits, {formatKES(customer.totalSpend)} lifetime. (A purchases table goes here.)
              </p>
            </TabsContent>
            {medical ? (
              <TabsContent value="medical" className="space-y-4">
                <SensitiveNotice kind="medical" />
                <DescriptionList
                  variant="inline"
                  items={[
                    { label: "Allergies", value: "Penicillin (rash, 2023)" },
                    { label: "Conditions", value: "Type 2 diabetes" },
                    { label: "Current medicines", value: "Metformin 500 mg twice daily" },
                  ]}
                />
              </TabsContent>
            ) : null}
            {accounts ? (
              <TabsContent value="account" className="space-y-5">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <p className="text-xs text-muted-foreground">
                    Balances are managed in{" "}
                    <a href="#" className="text-primary underline-offset-2 hover:underline">
                      Accounts
                    </a>
                    .
                  </p>
                  <div className="flex flex-wrap gap-2">
                    <Button size="sm">Receive payment</Button>
                    <Button size="sm" variant="outline">
                      Raise invoice
                    </Button>
                    <Button size="sm" variant="outline">
                      View statement
                    </Button>
                  </div>
                </div>
                <BalanceSummary kind="receivable" balance={customer.balance} creditLimit={customer.creditLimit} />
                <AgingBuckets data={{ current: customer.balance * 0.6, d31to60: customer.balance * 0.4, d61to90: 0, over90: 0 }} />
                <div className="grid gap-4 lg:grid-cols-2">
                  <div>
                    <h3 className="mb-2 text-sm font-semibold">Latest invoices</h3>
                    <Table className="text-sm">
                      <TableHeader>
                        <TableRow>
                          <TableHead>Invoice</TableHead>
                          <TableHead>Date</TableHead>
                          <TableHead className="text-right">Open</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {INVOICES.map((r) => (
                          <TableRow key={r.ref}>
                            <TableCell className="tabular-nums">{r.ref}</TableCell>
                            <TableCell>{formatDate(r.date, { short: true })}</TableCell>
                            <TableCell className="text-right tabular-nums">{r.open ? formatKES(r.open) : "Paid"}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                  <div>
                    <h3 className="mb-2 text-sm font-semibold">Latest payments</h3>
                    <Table className="text-sm">
                      <TableHeader>
                        <TableRow>
                          <TableHead>Receipt</TableHead>
                          <TableHead>Method</TableHead>
                          <TableHead className="text-right">Amount</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {PAYMENTS.map((r) => (
                          <TableRow key={r.ref}>
                            <TableCell className="tabular-nums">{r.ref}</TableCell>
                            <TableCell>{r.method}</TableCell>
                            <TableCell className="text-right tabular-nums">{formatKES(r.amount)}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                </div>
              </TabsContent>
            ) : null}
          </div>
          <aside aria-label="Summary" className="rounded-lg border border-[var(--color-border-panel)] bg-card p-4 xl:col-span-4 xl:self-start">
            <DescriptionList
              variant="inline"
              density="compact"
              title="At a glance"
              items={[
                { label: "Last visit", value: formatDate(customer.lastVisit) },
                { label: "Visits", value: String(customer.visits) },
                ...(accounts ? [{ label: "Balance", value: formatKES(customer.balance), money: true }] : []),
                { label: "Loyalty points", value: "1,240" },
              ]}
            />
          </aside>
        </div>
      </Tabs>
    </div>
  );
}

export function DetailPagePattern() {
  const [role, setRole] = React.useState<Role>("Admin");
  return (
    <Frame className="flex flex-col">
      <div className="flex items-center gap-3 border-b border-border px-4 py-2 text-sm">
        <span className="text-muted-foreground">Viewing as</span>
        <ToggleGroup variant="outline" size="sm" spacing={0} aria-label="Viewing as" value={[role]} onValueChange={(v: string[]) => v[0] && setRole(v[0] as Role)}>
          <ToggleGroupItem value="Admin">Admin</ToggleGroupItem>
          <ToggleGroupItem value="Pharmacist">Pharmacist</ToggleGroupItem>
          <ToggleGroupItem value="Cashier">Cashier</ToggleGroupItem>
        </ToggleGroup>
        <span className="hidden text-xs text-muted-foreground sm:inline">Tabs, buttons and figures the role can&apos;t use aren&apos;t shown.</span>
      </div>
      <div className="min-h-0 flex-1 overflow-y-auto p-6">
        <DetailPage key={role} role={role} />
      </div>
    </Frame>
  );
}

/* ------------------------------------- Launcher ------------------------------------- */

const ALL_TILES: (LauncherTile & { roles: Role[] })[] = [
  { title: "POS", description: "Sell, hold and return at the till", icon: ShoppingCartIcon, href: "#", roles: ["Admin", "Pharmacist", "Cashier"] },
  { title: "Inventory", description: "Stock levels, orders, transfers and stock takes", icon: WarehouseIcon, href: "#", roles: ["Admin", "Pharmacist"] },
  { title: "Customers", description: "Records, groups, prescriptions and loyalty", icon: UsersIcon, href: "#", roles: ["Admin", "Pharmacist", "Cashier"] },
  { title: "Suppliers", description: "Supplier records, GRNs and returns", icon: TruckIcon, href: "#", roles: ["Admin", "Pharmacist"] },
  { title: "Accounts", description: "Receivables, payables, expenses and the ledger", icon: BookOpenIcon, href: "#", roles: ["Admin"] },
  { title: "HRM", description: "Employees, attendance and payroll", icon: HandCoinsIcon, href: "#", roles: ["Admin"] },
  { title: "Reports", description: "Sales, stock, VAT and profit", icon: BarChart3Icon, href: "#", roles: ["Admin", "Pharmacist"] },
  { title: "Settings", description: "Store, receipts, users and permissions", icon: SettingsIcon, href: "#", roles: ["Admin"] },
  { title: "Integrations", description: "M-Pesa, KRA eTIMS, SMS and email", icon: PlugIcon, href: "#", roles: ["Admin"] },
];

export function LauncherPattern() {
  const [role, setRole] = React.useState<Role>("Admin");
  const [compact, setCompact] = React.useState(false);
  const tiles = ALL_TILES.filter((t) => t.roles.includes(role));
  return (
    <div className="space-y-4 p-4">
      <div className="flex flex-wrap items-center gap-3 text-sm">
        <ToggleGroup variant="outline" size="sm" spacing={0} aria-label="Role" value={[role]} onValueChange={(v: string[]) => v[0] && setRole(v[0] as Role)}>
          <ToggleGroupItem value="Admin">Admin</ToggleGroupItem>
          <ToggleGroupItem value="Pharmacist">Pharmacist</ToggleGroupItem>
          <ToggleGroupItem value="Cashier">Cashier</ToggleGroupItem>
        </ToggleGroup>
        <ToggleGroup variant="outline" size="sm" spacing={0} aria-label="Variant" value={[compact ? "compact" : "standard"]} onValueChange={(v: string[]) => v[0] && setCompact(v[0] === "compact")}>
          <ToggleGroupItem value="standard">Standard</ToggleGroupItem>
          <ToggleGroupItem value="compact">Compact</ToggleGroupItem>
        </ToggleGroup>
        <span className="text-xs text-muted-foreground">
          {tiles.length} of {ALL_TILES.length} menus
        </span>
      </div>
      <Launcher tiles={tiles} compact={compact} />
      <p className="flex items-center gap-1.5 text-xs text-muted-foreground">
        <FileTextIcon className="size-3.5" aria-hidden /> On the Dashboard, the panels follow below the tiles.
      </p>
    </div>
  );
}
