import { AlertCircle, Copy, Inbox, Lock, RefreshCw, type LucideIcon } from "lucide-react";
import type { ReactNode } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { ApiError } from "@/api/client";
import { cn } from "@/lib/utils";

export function Shimmer({ className }: { className?: string }) {
  return <div className={cn("shimmer rounded-md", className)} aria-hidden="true" />;
}
export function KpiGridSkeleton({ n = 4 }: { n?: number }) {
  return (
    <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
      {Array.from({ length: n }, (_, i) => (
        <div key={i} className="rounded-xl border bg-card p-4">
          <Shimmer className="h-3 w-28" />
          <Shimmer className="mt-3 h-8 w-24" />
          <Shimmer className="mt-4 h-1.5 w-full" />
          <Shimmer className="mt-3 h-3 w-20" />
        </div>
      ))}
    </div>
  );
}
export function TableSkeleton({ rows = 10, cols = 6 }: { rows?: number; cols?: number }) {
  return (
    <div
      className="overflow-hidden rounded-xl border bg-card"
      aria-busy="true"
      aria-label="Loading"
    >
      <div className="flex gap-4 bg-surface-2 px-4 py-3">
        {Array.from({ length: cols }, (_, i) => (
          <Shimmer key={i} className="h-3 flex-1" />
        ))}
      </div>
      {Array.from({ length: rows }, (_, r) => (
        <div key={r} className="flex gap-4 border-t px-4 py-3.5">
          {Array.from({ length: cols }, (_, i) => (
            <Shimmer key={i} className={cn("h-3 flex-1", i === 1 && "flex-[2]")} />
          ))}
        </div>
      ))}
    </div>
  );
}
export function DetailSkeleton() {
  return (
    <div className="space-y-5">
      <Shimmer className="h-8 w-72" />
      <Shimmer className="h-4 w-96" />
      <div className="flex gap-4">
        <Shimmer className="h-8 w-24" />
        <Shimmer className="h-8 w-24" />
        <Shimmer className="h-8 w-24" />
      </div>
      <div className="grid gap-4 md:grid-cols-2">
        <Shimmer className="h-48" />
        <Shimmer className="h-48" />
      </div>
    </div>
  );
}
export function UpdatingBar({ active }: { active: boolean }) {
  if (!active) return null;
  return (
    <div
      className="absolute inset-x-0 top-0 h-0.5 overflow-hidden rounded-t-xl"
      role="progressbar"
      aria-label="Updating"
    >
      <div className="indeterminate h-full w-1/3 bg-primary" />
    </div>
  );
}
export function EmptyState({
  title,
  text,
  icon: Icon = Inbox,
  action,
  className,
}: {
  title: string;
  text: string;
  icon?: LucideIcon;
  action?: ReactNode;
  className?: string;
}) {
  return (
    <div
      className={cn("flex flex-col items-center justify-center px-6 py-14 text-center", className)}
    >
      <div className="mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-primary-soft text-primary">
        <Icon className="h-6 w-6" aria-hidden="true" />
      </div>
      <h3 className="font-display text-[15px] font-semibold">{title}</h3>
      <p className="mt-1 max-w-sm text-muted-foreground">{text}</p>
      {action && <div className="mt-5 flex flex-wrap justify-center gap-2">{action}</div>}
    </div>
  );
}
export function ErrorState({ error, onRetry }: { error: unknown; onRetry?: () => void }) {
  const api = error instanceof ApiError ? error : undefined;
  if (api?.status === 403)
    return (
      <EmptyState
        icon={Lock}
        title="You don't have access to this"
        text="Contact your administrator if you need it."
      />
    );
  return (
    <div
      role="alert"
      className="flex items-start gap-3 rounded-xl border border-danger/30 bg-danger-soft p-4"
    >
      <AlertCircle className="mt-0.5 h-5 w-5 shrink-0 text-danger" aria-hidden="true" />
      <div className="min-w-0 flex-1">
        <p className="font-semibold">
          {api?.message ?? (error instanceof Error ? error.message : "Something went wrong.")}
        </p>
        {api && (
          <p className="mt-1 flex items-center gap-2 font-mono text-[12px] text-muted-foreground">
            {api.code} · {api.requestId}
            <button
              type="button"
              aria-label="Copy request id"
              onClick={() => {
                void navigator.clipboard.writeText(api.requestId);
                toast.success("Request id copied");
              }}
            >
              <Copy className="h-3.5 w-3.5" />
            </button>
          </p>
        )}
      </div>
      {onRetry && (
        <Button variant="outline" size="sm" onClick={onRetry}>
          <RefreshCw /> Try again
        </Button>
      )}
    </div>
  );
}
