"use client";

import { AlertTriangleIcon, CalendarClockIcon, CircleCheckIcon, HelpCircleIcon, InfoIcon, OctagonXIcon, WifiOffIcon } from "lucide-react";

import { Alert, AlertAction, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card";
import { Popover, PopoverContent, PopoverDescription, PopoverHeader, PopoverTitle, PopoverTrigger } from "@/components/ui/popover";
import { Progress, ProgressLabel, ProgressValue } from "@/components/ui/progress";
import { Skeleton } from "@/components/ui/skeleton";
import { Loading } from "@/components/medora/loading";
import { Spinner } from "@/components/ui/spinner";
import { toast } from "@/components/ui/toast";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { customers, expiring, formatKES, initials, products } from "@/lib/mock-data";

export function PopoverDemo() {
  return (
    <Popover>
      <PopoverTrigger render={<Button variant="outline" />}>Stock levels</PopoverTrigger>
      <PopoverContent className="w-64">
        <PopoverHeader>
          <PopoverTitle>{products[0].name}</PopoverTitle>
          <PopoverDescription>
            On hand {products[0].stock}, reorder at {products[0].minStock}.
          </PopoverDescription>
        </PopoverHeader>
      </PopoverContent>
    </Popover>
  );
}

export function TooltipDemo() {
  return (
    <div className="flex gap-2">
      <Tooltip>
        <TooltipTrigger render={<Button variant="outline" size="icon" aria-label="Help" />}>
          <HelpCircleIcon />
        </TooltipTrigger>
        <TooltipContent>Hold the sale to continue later</TooltipContent>
      </Tooltip>
      <Tooltip>
        <TooltipTrigger render={<Button variant="outline" />}>Reorder level</TooltipTrigger>
        <TooltipContent side="bottom">Alert when stock falls to this number</TooltipContent>
      </Tooltip>
    </div>
  );
}

export function HoverCardDemo() {
  const c = customers[1];
  return (
    <HoverCard>
      <HoverCardTrigger render={<Button variant="link" className="px-0" />}>{c.name}</HoverCardTrigger>
      <HoverCardContent className="w-72">
        <div className="flex gap-3">
          <Avatar>
            <AvatarFallback>{initials(c.name)}</AvatarFallback>
          </Avatar>
          <div className="space-y-1 text-sm">
            <p className="font-medium">{c.name}</p>
            <p className="text-muted-foreground">{c.phone}</p>
            <p className="tabular-nums text-muted-foreground">
              Owes {formatKES(c.balance)} of {formatKES(c.creditLimit)}
            </p>
          </div>
        </div>
      </HoverCardContent>
    </HoverCard>
  );
}

export function ToastDemo() {
  return (
    <div className="flex flex-wrap gap-2">
      <Button variant="outline" onClick={() => toast.add({ type: "success", title: "Sale completed", description: `RCP-005201, ${formatKES(2340)} paid by M-Pesa.` })}>
        Success
      </Button>
      <Button variant="outline" onClick={() => toast.add({ type: "error", title: "Payment failed", description: "The M-Pesa request timed out. Ask the customer to retry." })}>
        Error
      </Button>
      <Button variant="outline" onClick={() => toast.add({ type: "info", title: "Shift report ready", description: "Kevin Mutua closed the 08:00 shift." })}>
        Info
      </Button>
      <Button
        variant="outline"
        onClick={() =>
          toast.add({
            type: "success",
            title: "Product archived",
            description: products[3].name,
            actionProps: { children: "Undo", onClick: () => toast.add({ type: "info", title: "Restored", description: products[3].name }) },
          })
        }
      >
        With undo
      </Button>
      <Button
        variant="outline"
        onClick={() =>
          toast.promise(new Promise<string>((res) => setTimeout(() => res("Stock count saved"), 1800)), {
            loading: "Saving stock count...",
            success: (m: string) => ({ title: m, type: "success" }),
            error: "Could not save",
          })
        }
      >
        Promise
      </Button>
    </div>
  );
}

const tone = {
  info: "border-status-info-border bg-status-info-bg text-foreground *:[svg]:text-status-info-text",
  success: "border-status-success-border bg-status-success-bg text-foreground *:[svg]:text-status-success-text",
  warning: "border-status-warning-border bg-status-warning-bg text-foreground *:[svg]:text-status-warning-text",
} as const;

export function AlertVariants() {
  return (
    <div className="space-y-3">
      <Alert className={tone.info}>
        <InfoIcon />
        <AlertTitle>Shift is open</AlertTitle>
        <AlertDescription>Started 08:02 with a float of {formatKES(5000)}.</AlertDescription>
      </Alert>
      <Alert className={tone.success}>
        <CircleCheckIcon />
        <AlertTitle>Purchase order received</AlertTitle>
        <AlertDescription>12 lines added to stock as batches.</AlertDescription>
      </Alert>
      <Alert className={tone.warning}>
        <AlertTriangleIcon />
        <AlertTitle>Credit limit nearly reached</AlertTitle>
        <AlertDescription>{customers[1].name} has used 92% of their credit limit.</AlertDescription>
      </Alert>
      <Alert variant="destructive">
        <OctagonXIcon />
        <AlertTitle>Insufficient stock</AlertTitle>
        <AlertDescription>
          Only {products[1].stock} of {products[1].name} left; the sale needs 2000.
        </AlertDescription>
        <AlertAction>
          <Button size="xs" variant="outline">
            Review
          </Button>
        </AlertAction>
      </Alert>
    </div>
  );
}

export function Banners() {
  return (
    <div className="space-y-3">
      <div role="status" className="flex items-center gap-3 rounded-lg border border-status-warning-border bg-status-warning-bg px-3 py-2 text-sm">
        <WifiOffIcon className="size-4 shrink-0 text-status-warning-text" />
        <span className="font-medium">Offline mode.</span>
        <span className="text-muted-foreground">Sales are saved on this device and sync when you reconnect.</span>
        <Button size="xs" variant="outline" className="ml-auto">
          Retry
        </Button>
      </div>
      <div role="status" className="flex items-center gap-3 rounded-lg border border-status-error-border bg-status-error-bg px-3 py-2 text-sm">
        <CalendarClockIcon className="size-4 shrink-0 text-destructive" />
        <span className="font-medium">{expiring.length} batches expire within 90 days.</span>
        <span className="hidden text-muted-foreground sm:inline">
          Soonest: {expiring[0].productName}, {expiring[0].daysLeft} days.
        </span>
        <Button size="xs" variant="outline" className="ml-auto">
          View expiring
        </Button>
      </div>
    </div>
  );
}

export function LoadingStates() {
  return (
    <div className="grid gap-6 md:grid-cols-2">
      <div className="space-y-4">
        <Progress value={64}>
          <ProgressLabel>Importing products</ProgressLabel>
          <ProgressValue className="ml-auto text-sm text-muted-foreground tabular-nums" />
        </Progress>
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <Spinner /> Syncing 3 offline sales...
        </div>
        <Button disabled>
          <Spinner data-icon="inline-start" />
          Saving
        </Button>
      </div>
      <div className="space-y-3" aria-hidden>
        <div className="flex items-center gap-3">
          <Skeleton className="size-9 rounded-full" />
          <div className="flex-1 space-y-2">
            <Skeleton className="h-3 w-1/2" />
            <Skeleton className="h-3 w-1/3" />
          </div>
        </div>
        <Skeleton className="h-24 w-full" />
        <div className="grid grid-cols-3 gap-2">
          <Skeleton className="h-8" />
          <Skeleton className="h-8" />
          <Skeleton className="h-8" />
        </div>
      </div>
      <div className="space-y-2 border-t border-border pt-4">
        <p className="text-xs font-medium text-muted-foreground">Panel skeletons, shaped like what replaces them (loading spec §8)</p>
        <Loading what="stock" rows={3} />
        <div className="grid gap-3 md:grid-cols-2">
          <Loading what="prescriptions" shape="cards" rows={2} />
          <Loading what="supplier" shape="detail" rows={4} />
        </div>
      </div>
    </div>
  );
}
