'use client';

import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { AlertTriangle, ArrowRight, Bell, Wallet, XCircle, type LucideIcon } from 'lucide-react';
import Link from 'next/link';

import { usePopover } from '@/components/layout/use-popover';
import { AllClearIllustration } from '@/components/illustrations';
import type { AttentionItem } from '@/lib/dashboard';
import { cn } from '@/lib/utils';

const kinds: Partial<Record<AttentionItem['type'], { title: string; icon: LucideIcon; chip: string }>> = {
  exception: { title: 'Shipment exception', icon: AlertTriangle, chip: 'bg-danger-soft text-danger' },
  failed: { title: 'Label purchase failed', icon: XCircle, chip: 'bg-danger-soft text-danger' },
  low_balance: { title: 'Low wallet balance', icon: Wallet, chip: 'bg-warning-soft text-warning' },
};

export function NotificationsMenu({ items }: { items: AttentionItem[] }) {
  const reduce = useReducedMotion();
  const { open, toggle, close, rootRef, triggerRef } = usePopover();
  const visible = items.filter((item) => item.type === 'exception' || item.type === 'failed' || item.type === 'low_balance').slice(0, 10);
  const count = visible.length;

  return (
    <div ref={rootRef} className="relative">
      <button
        ref={triggerRef}
        type="button"
        className={cn(
          'relative grid h-10 w-10 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-muted hover:text-foreground',
          open && 'bg-surface-muted text-foreground',
        )}
        aria-expanded={open}
        aria-haspopup="dialog"
        aria-label={count === 0 ? 'Notifications' : `Notifications, ${count} need attention`}
        onClick={toggle}
      >
        <Bell className="h-5 w-5" aria-hidden="true" />
        {count === 0 ? null : <span className="absolute right-2 top-2 h-2 w-2 rounded-full bg-danger ring-2 ring-background" aria-hidden="true" />}
      </button>
      <AnimatePresence>
        {open ? (
          <motion.div
            role="dialog"
            aria-label="Notifications"
            initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.97, y: -4 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.97 }}
            transition={{ duration: 0.14, ease: [0.2, 0.8, 0.2, 1] }}
            className="fixed inset-x-3 top-16 z-50 origin-top-right rounded-lg border border-border bg-surface shadow-md sm:absolute sm:inset-x-auto sm:right-0 sm:top-full sm:mt-2 sm:w-[360px]"
          >
            <div className="flex items-center justify-between border-b border-border px-4 py-3">
              <p className="text-small font-semibold">Notifications</p>
              {count === 0 ? null : <span className="rounded-pill bg-danger-soft px-2 py-0.5 text-[11px] font-semibold text-danger">{count}</span>}
            </div>
            {count === 0 ? (
              <div className="grid justify-items-center gap-2 px-6 py-10 text-center">
                <AllClearIllustration />
                <p className="text-small font-semibold">You are all caught up</p>
                <p className="text-caption text-muted-foreground">Exceptions and low balance alerts will show up here.</p>
              </div>
            ) : (
              <ul className="max-h-[360px] overflow-y-auto p-1">
                {visible.map((item) => {
                  const kind = kinds[item.type];
                  const Icon = kind?.icon ?? Bell;
                  return (
                    <li key={`${item.type}-${item.shipmentId ?? item.message}`}>
                      <Link
                        href={item.shipmentId === undefined ? '/wallet' : `/shipments/${item.shipmentId}`}
                        className="flex gap-3 rounded-md px-3 py-2.5 transition-colors hover:bg-surface-muted focus-visible:bg-surface-muted"
                        onClick={() => close(false)}
                      >
                        <span className={cn('grid h-8 w-8 shrink-0 place-items-center rounded-full', kind?.chip ?? 'bg-surface-muted text-muted-foreground')}>
                          <Icon className="h-4 w-4" aria-hidden="true" />
                        </span>
                        <span className="min-w-0">
                          <span className="block text-small font-semibold text-foreground">{kind?.title ?? 'Needs attention'}</span>
                          <span className="mt-0.5 line-clamp-2 block text-caption text-muted-foreground">{item.message}</span>
                        </span>
                      </Link>
                    </li>
                  );
                })}
              </ul>
            )}
            <div className="border-t border-border p-1">
              <Link
                href="/shipments"
                onClick={() => close(false)}
                className="flex h-9 items-center justify-center gap-1.5 rounded-md text-small font-semibold text-primary transition-colors hover:bg-surface-muted"
              >
                View all shipments
                <ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
              </Link>
            </div>
          </motion.div>
        ) : null}
      </AnimatePresence>
    </div>
  );
}
