"use client";

import { useState } from "react";
import { ChevronsUpDownIcon, FileTextIcon, LogOutIcon, ReceiptIcon, SearchIcon, SettingsIcon } from "lucide-react";

import { useSidebarTone } from "@/components/design-system/sidebar-tone";
import { NOTICES, NOW } from "@/components/design-system/sections/overlays/notifications-demo";
import { PHARMACY_NAV } from "@/components/medora/nav";
import { NotificationsBell, useNotices } from "@/components/medora/notifications";
import { SidebarLogo } from "@/components/medora/sidebar-logo";
import { UserMenu } from "@/components/medora/user-menu";
import { toast } from "@/components/ui/toast";

import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from "@/components/ui/breadcrumb";
import { Button } from "@/components/ui/button";
import { Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Kbd } from "@/components/ui/kbd";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInset, SidebarMenu, SidebarMenuBadge, SidebarMenuButton, SidebarMenuItem, SidebarProvider, SidebarRail, SidebarTrigger } from "@/components/ui/sidebar";
import { branches, currentUser, expiring, formatKES, initials, lowStock, recentSales } from "@/lib/mock-data";
import { Frame } from "./frame";

/** Counts shown as menu badges, keyed by destination title. */
const BADGES: Record<string, number> = { "Stock Management": lowStock.length, "Batch & Expiry": expiring.length };

export function AppShellPattern() {
  const { tone, setTone } = useSidebarTone();
  const [textSize, setTextSize] = useState<"default" | "large">("default");
  const [active, setActive] = useState("Dashboard");
  const [open, setOpen] = useState(false);
  const [branch, setBranch] = useState(branches[0].name);
  const notices = useNotices(NOTICES);
  return (
    <Frame>
      <SidebarProvider keyboardShortcut={false} className="h-full min-h-0">
        <Sidebar collapsible="icon" tone={tone} className="absolute h-full">
          <SidebarHeader className="items-center px-3 pt-4 pb-2">
            <SidebarLogo tone={tone} className="group-data-[collapsible=icon]:hidden" />
            <SidebarLogo tone={tone} symbol className="hidden group-data-[collapsible=icon]:block" />
          </SidebarHeader>
          <SidebarContent className="gap-0">
            {PHARMACY_NAV.map((g) => (
              <SidebarGroup key={g.label} className="py-1">
                <SidebarGroupLabel>{g.label}</SidebarGroupLabel>
                <SidebarGroupContent>
                  <SidebarMenu>
                    {g.items.map((it) => (
                      <SidebarMenuItem key={it.title}>
                        <SidebarMenuButton tooltip={it.title} isActive={active === it.title} onClick={() => setActive(it.title)}>
                          <it.icon />
                          <span>{it.title}</span>
                        </SidebarMenuButton>
                        {BADGES[it.title] ? <SidebarMenuBadge>{BADGES[it.title]}</SidebarMenuBadge> : null}
                      </SidebarMenuItem>
                    ))}
                  </SidebarMenu>
                </SidebarGroupContent>
              </SidebarGroup>
            ))}
          </SidebarContent>
          <SidebarFooter className="border-t border-sidebar-border">
            <SidebarMenu>
              <SidebarMenuItem>
                <DropdownMenu>
                  <DropdownMenuTrigger render={<SidebarMenuButton size="lg" className="h-10" />}>
                    <Avatar className="size-7">
                      <AvatarFallback>{initials(currentUser.name)}</AvatarFallback>
                    </Avatar>
                    <div className="grid flex-1 text-left leading-tight">
                      <span className="truncate text-sm font-medium">{currentUser.name}</span>
                      <span className="truncate text-xs text-(--sidebar-muted)">{currentUser.role}</span>
                    </div>
                    <ChevronsUpDownIcon className="ml-auto size-4" />
                  </DropdownMenuTrigger>
                  <DropdownMenuContent side="right" align="end" className="min-w-48">
                    <DropdownMenuGroup>
                      <DropdownMenuLabel>{currentUser.email}</DropdownMenuLabel>
                    </DropdownMenuGroup>
                    <DropdownMenuSeparator />
                    <DropdownMenuItem><SettingsIcon /> Account settings</DropdownMenuItem>
                    <DropdownMenuItem><LogOutIcon /> Sign out</DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </SidebarMenuItem>
            </SidebarMenu>
          </SidebarFooter>
          <SidebarRail />
        </Sidebar>
        <SidebarInset className="min-w-0 bg-muted/40">
          <header className="flex h-14 shrink-0 items-center gap-3 border-b border-border bg-background px-4">
            <SidebarTrigger className="-ml-1" />
            <Separator orientation="vertical" className="h-5" />
            <Breadcrumb className="hidden md:block">
              <BreadcrumbList>
                <BreadcrumbItem><BreadcrumbLink href="#">Medora</BreadcrumbLink></BreadcrumbItem>
                <BreadcrumbSeparator />
                <BreadcrumbItem><BreadcrumbPage>{active}</BreadcrumbPage></BreadcrumbItem>
              </BreadcrumbList>
            </Breadcrumb>
            <div className="ml-auto flex items-center gap-2">
              <Button variant="outline" size="sm" className="w-48 justify-start text-muted-foreground" onClick={() => setOpen(true)}>
                <SearchIcon data-icon="inline-start" />
                Search
                <Kbd className="ml-auto">Ctrl K</Kbd>
              </Button>
              <Select value={branch} onValueChange={(v) => v && setBranch(v)}>
                <SelectTrigger size="sm" className="w-40"><SelectValue /></SelectTrigger>
                <SelectContent>{branches.map((b) => <SelectItem key={b.id} value={b.name}>{b.name}</SelectItem>)}</SelectContent>
              </Select>
              <NotificationsBell items={notices.items} now={NOW} onOpenNotice={notices.open} onReadAll={notices.readAll} settingsHref="#" />
              <UserMenu
                name={currentUser.name}
                email={currentUser.email}
                role={currentUser.role}
                branch={branch}
                appearance={{ sidebar: tone, text: textSize }}
                onAppearance={(a) => {
                  setTone(a.sidebar);
                  setTextSize(a.text);
                }}
                onProfile={() => toast.add({ title: "Opens your profile" })}
                onPassword={() => toast.add({ title: "Opens change password or passcode" })}
                onSignOut={() => toast.add({ title: "Signed out" })}
              />
            </div>
          </header>
          <div className="flex-1 space-y-4 overflow-auto p-4">
            <div>
              <h3 className="text-base font-semibold">{active}</h3>
              <p className="text-sm text-muted-foreground">{branch}. Page content renders here.</p>
            </div>
            <div className="grid gap-3 sm:grid-cols-3">
              {[["Low stock", String(lowStock.length)], ["Expiring in 90 days", String(expiring.length)], ["Sales today", formatKES(recentSales[0].total)]].map(([k, v]) => (
                <div key={k} className="rounded-lg border border-border bg-card p-3">
                  <p className="text-xs text-muted-foreground">{k}</p>
                  <p className="mt-1 text-lg font-semibold tabular-nums">{v}</p>
                </div>
              ))}
            </div>
            <div className="rounded-lg border border-border bg-card">
              <p className="flex items-center gap-2 border-b border-border px-3 py-2 text-sm font-medium"><ReceiptIcon className="size-4" /> Recent receipts</p>
              <ul className="divide-y divide-border text-sm">
                {recentSales.slice(0, 6).map((s) => (
                  <li key={s.id} className="flex items-center justify-between px-3 py-2">
                    <span className="flex items-center gap-2"><FileTextIcon className="size-4 text-muted-foreground" />{s.receipt}</span>
                    <Badge variant="outline">{s.method}</Badge>
                    <span className="tabular-nums">{formatKES(s.total)}</span>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </SidebarInset>
      </SidebarProvider>
      <CommandDialog open={open} onOpenChange={setOpen}>
        <Command>
          <CommandInput placeholder="Search pages, products, customers..." />
          <CommandList>
            <CommandEmpty>No results.</CommandEmpty>
            <CommandGroup heading="Pages">
              {PHARMACY_NAV.flatMap((g) => g.items).map((it) => (
                <CommandItem key={it.title} onSelect={() => { setActive(it.title); setOpen(false); }}><it.icon /> {it.title}</CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </CommandDialog>
    </Frame>
  );
}
