"use client";

import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { motion, useReducedMotion } from "motion/react";
import { ArrowRight, Plus, Sparkles } from "lucide-react";
import type { QuickAction } from "@/lib/navigation";
import { Icon } from "@/components/icon";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";

/** Colour family per action, keyed by its icon, so every tile reads at a glance. */
const TONE: Record<string, string> = {
  CalendarPlus: "bg-primary/12 text-primary",
  UserPlus: "bg-info-500/12 text-info-600 dark:text-info-500",
  LogIn: "bg-positive-500/12 text-positive-600 dark:text-positive-500",
  LogOut: "bg-warning-500/12 text-warning-600 dark:text-warning-500",
  ReceiptText: "bg-gold-500/15 text-gold-700 dark:text-gold-300",
  ListPlus: "bg-accent-500/12 text-accent-600 dark:text-accent-500",
  CalendarOff: "bg-negative-500/12 text-negative-600 dark:text-negative-500",
  Wrench: "bg-warning-500/12 text-warning-600 dark:text-warning-500",
  Sparkles: "bg-positive-500/12 text-positive-600 dark:text-positive-500",
  ShieldAlert: "bg-negative-500/12 text-negative-600 dark:text-negative-500",
  Clock: "bg-surface-3 text-fg-muted",
};
const toneFor = (icon: string) => TONE[icon] ?? "bg-surface-3 text-fg-muted";

const spring = { type: "spring", stiffness: 520, damping: 34, mass: 0.7 } as const;

/**
 * Quick actions. In the top bar it is a dropdown; as the phone FAB it opens a
 * bottom sheet of large, colour-coded tiles that spring in one after another,
 * with the primary action as a full-width hero tile.
 */
export function QuickCreate({ actions, trigger, sheet }: { actions: QuickAction[]; trigger?: React.ReactNode; sheet?: boolean }) {
  if (sheet) return <QuickSheet actions={actions} trigger={trigger} />;
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        {trigger ?? (
          <Button size="sm" className="hidden sm:inline-flex">
            <Plus className="transition-transform duration-300 [transition-timing-function:var(--ease-spring)] group-data-[state=open]:rotate-45" /> <span className="hidden lg:inline">Create</span>
          </Button>
        )}
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-64 p-1.5">
        <DropdownMenuLabel className="flex items-center gap-1.5">
          <Sparkles className="size-3 text-gold-500" /> Quick actions
        </DropdownMenuLabel>
        {actions.map((a) => (
          <DropdownMenuItem key={a.href} asChild className="py-2">
            <Link href={a.href}>
              <span className={cn("flex size-7 shrink-0 items-center justify-center rounded-md [&_svg]:size-4 [&_svg]:text-current", toneFor(a.icon))}>
                <Icon name={a.icon} />
              </span>
              <span className="flex-1 truncate">{a.label}</span>
              {a.shortcut ? <kbd className="font-mono text-2xs text-fg-subtle">{a.shortcut}</kbd> : null}
            </Link>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

function QuickSheet({ actions, trigger }: { actions: QuickAction[]; trigger?: React.ReactNode }) {
  const [open, setOpen] = React.useState(false);
  const router = useRouter();
  const reduced = useReducedMotion();
  const [primary, ...rest] = actions;
  React.useEffect(() => {
    if (open && "vibrate" in navigator) navigator.vibrate?.(8);
  }, [open]);
  const go = (href: string) => {
    setOpen(false);
    router.push(href);
  };
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{trigger ?? <Button size="icon" aria-label="Quick actions"><Plus /></Button>}</DialogTrigger>
      <DialogContent size="md" hideClose className="glass rounded-t-3xl border-x-0 border-b-0 pb-[calc(1rem+env(safe-area-inset-bottom))] sm:rounded-2xl sm:border">
        <DialogTitle className="sr-only">Quick actions</DialogTitle>
        <div className="px-4 pt-2 sm:px-5 sm:pt-4">
          <div className="mb-3 flex items-end justify-between">
            <div>
              <p className="eyebrow flex items-center gap-1.5">
                <Sparkles className="size-3 text-gold-500" /> Quick actions
              </p>
              <p className="font-display text-xl font-medium leading-tight">What do you want to do?</p>
            </div>
            <span className="text-2xs text-fg-subtle">{actions.length} actions</span>
          </div>
          {primary ? (
            <motion.button
              type="button"
              onClick={() => go(primary.href)}
              initial={reduced ? false : { opacity: 0, y: 18, scale: 0.96 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              transition={{ ...spring, delay: 0.04 }}
              className="brand-tile group relative mb-2.5 flex w-full items-center gap-3 overflow-hidden rounded-2xl p-4 text-left text-white active:scale-[0.98]"
            >
              <span className="pointer-events-none absolute -right-8 -top-10 size-32 rounded-full bg-white/15 blur-2xl" aria-hidden />
              <span className="flex size-11 shrink-0 items-center justify-center rounded-xl bg-white/20 [&_svg]:size-5">
                <Icon name={primary.icon} />
              </span>
              <span className="min-w-0 flex-1">
                <span className="block text-base font-semibold leading-tight">{primary.label}</span>
                <span className="block text-xs text-white/80">Most used · opens the booking flow</span>
              </span>
              <ArrowRight className="size-5 opacity-80 transition-transform group-hover:translate-x-0.5" />
            </motion.button>
          ) : null}
          <div className="grid grid-cols-3 gap-2">
            {rest.map((a, i) => (
              <motion.button
                key={a.href}
                type="button"
                onClick={() => go(a.href)}
                initial={reduced ? false : { opacity: 0, y: 16, scale: 0.9 }}
                animate={{ opacity: 1, y: 0, scale: 1 }}
                transition={{ ...spring, delay: 0.07 + i * 0.035 }}
                className="flex flex-col items-center gap-2 rounded-2xl border border-border bg-surface/70 px-2 py-3 text-center transition-colors hover:bg-surface-2 active:scale-95"
              >
                <span className={cn("flex size-11 items-center justify-center rounded-xl [&_svg]:size-5 [&_svg]:text-current", toneFor(a.icon))}>
                  <Icon name={a.icon} />
                </span>
                <span className="line-clamp-2 text-[11px] font-medium leading-tight text-fg">{a.label.replace(/\s*\(.*\)$/, "")}</span>
              </motion.button>
            ))}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
