'use client';

import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { MailWarning, Wallet, X, type LucideIcon } from 'lucide-react';
import Link from 'next/link';
import { useEffect, useState, type ReactNode } from 'react';
import { toast } from 'sonner';

import { CountdownRing } from '@/components/auth/resend-button';
import { LockIllustration } from '@/components/illustrations';
import { Button, buttonVariants } from '@/components/ui/button';
import { ApiError, api } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import { publicEnv } from '@/lib/public-env';
import { cn } from '@/lib/utils';

const dismissedKey = (id: string): string => `shiphub.banner.${id}`;

const tones = {
  info: { box: 'border-info/25 bg-info-soft', chip: 'bg-surface text-info' },
  warning: { box: 'border-warning/30 bg-warning-soft', chip: 'bg-surface text-warning' },
} as const;

function Banner({
  tone,
  icon: Icon,
  lead,
  detail,
  action,
  onDismiss,
}: {
  tone: keyof typeof tones;
  icon: LucideIcon;
  lead: string;
  detail: string;
  action: ReactNode;
  onDismiss: () => void;
}) {
  const reduce = useReducedMotion();
  return (
    <motion.div
      layout={!reduce}
      initial={reduce ? { opacity: 0 } : { opacity: 0, height: 0 }}
      animate={reduce ? { opacity: 1 } : { opacity: 1, height: 'auto' }}
      exit={reduce ? { opacity: 0 } : { opacity: 0, height: 0 }}
      transition={{ duration: 0.22, ease: [0.2, 0.8, 0.2, 1] }}
      className="overflow-hidden"
    >
      <div className={cn('flex flex-wrap items-center gap-3 rounded-lg border px-4 py-3', tones[tone].box)} role="status">
        <span className={cn('grid h-9 w-9 shrink-0 place-items-center rounded-md shadow-xs', tones[tone].chip)}>
          <Icon className="h-[18px] w-[18px]" aria-hidden="true" />
        </span>
        <p className="min-w-0 flex-1 text-small text-muted-foreground">
          <span className="font-semibold text-foreground">{lead}</span> {detail}
        </p>
        <div className="flex items-center gap-1.5">
          {action}
          <button
            type="button"
            onClick={onDismiss}
            aria-label={`Dismiss: ${lead}`}
            className="grid h-9 w-9 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface/70 hover:text-foreground"
          >
            <X className="h-4 w-4" aria-hidden="true" />
          </button>
        </div>
      </div>
    </motion.div>
  );
}

export function GlobalBanners({ lowBalance, suspended }: { lowBalance: boolean; suspended: boolean }) {
  const { user, refreshMe } = useAuth();
  const [pending, setPending] = useState(false);
  const [cooldown, setCooldown] = useState(0);
  const [hidden, setHidden] = useState<Record<string, boolean>>({});
  useEffect(() => {
    const timer = window.setTimeout(() => {
      setHidden({
        email: sessionStorage.getItem(dismissedKey('email')) === '1',
        balance: sessionStorage.getItem(dismissedKey('balance')) === '1',
      });
    }, 0);
    return () => window.clearTimeout(timer);
  }, []);
  const cooling = cooldown > 0;
  useEffect(() => {
    if (!cooling) return undefined;
    const timer = window.setInterval(() => setCooldown((current) => Math.max(0, current - 1)), 1000);
    return () => window.clearInterval(timer);
  }, [cooling]);

  const emailUnverified = user?.emailVerifiedAt === undefined;
  const dismiss = (id: string) => {
    sessionStorage.setItem(dismissedKey(id), '1');
    setHidden((current) => ({ ...current, [id]: true }));
  };
  const visible = (id: string): boolean => hidden[id] !== true;

  if (suspended) {
    return (
      <div className="grid justify-items-center rounded-xl border border-danger/25 bg-surface px-6 py-14 text-center shadow-xs" role="alert">
        <LockIllustration size={120} />
        <h1 className="mt-4 font-display text-h2 font-bold">This workspace is suspended</h1>
        <p className="mt-2 max-w-md text-body text-muted-foreground">
          Shipping and wallet actions are paused while the account is under review. Contact support and we will help you restore access.
        </p>
        <a className={cn(buttonVariants({ size: 'lg' }), 'mt-6')} href={`mailto:${publicEnv.NEXT_PUBLIC_SUPPORT_EMAIL}`}>
          Contact support
        </a>
      </div>
    );
  }

  const resend = () => {
    setPending(true);
    void api('/auth/resend-verification', { method: 'POST' })
      .then(async () => {
        toast.success('Verification email sent.');
        setCooldown(60);
        await refreshMe();
      })
      .catch((error: unknown) => {
        toast.error(error instanceof ApiError ? error.message : 'The email could not be sent.');
      })
      .finally(() => setPending(false));
  };

  const showEmail = emailUnverified && visible('email');
  const showBalance = lowBalance && visible('balance');

  return (
    <div className={cn('grid gap-3', (showEmail || showBalance) && 'mb-6')}>
      <AnimatePresence initial={false}>
        {showEmail ? (
          <Banner
            key="email"
            tone="info"
            icon={MailWarning}
            lead="Verify your email."
            detail="You need a verified email before buying a label."
            onDismiss={() => dismiss('email')}
            action={
              <Button type="button" size="sm" variant="secondary" loading={pending} disabled={cooling} onClick={resend}>
                {cooling ? (
                  <>
                    <CountdownRing remaining={cooldown} className="h-4 w-4" />
                    <span className="tabular-nums">{cooldown}s</span>
                  </>
                ) : (
                  'Resend email'
                )}
              </Button>
            }
          />
        ) : null}
        {showBalance ? (
          <Banner
            key="balance"
            tone="warning"
            icon={Wallet}
            lead="Your wallet balance is low."
            detail="Top up to keep buying labels without interruption."
            onDismiss={() => dismiss('balance')}
            action={
              <Link href="/wallet" className={buttonVariants({ size: 'sm' })}>
                Top up
              </Link>
            }
          />
        ) : null}
      </AnimatePresence>
    </div>
  );
}
