'use client';

import { RotateCw } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

const R = 9;
const CIRCUMFERENCE = 2 * Math.PI * R;

/** Small SVG ring that empties as a cooldown runs out. */
export function CountdownRing({ remaining, total = 60, className }: { remaining: number; total?: number; className?: string }) {
  const progress = total <= 0 ? 0 : Math.min(1, Math.max(0, remaining / total));
  return (
    <svg viewBox="0 0 24 24" className={cn('h-5 w-5 -rotate-90', className)} aria-hidden="true">
      <circle cx="12" cy="12" r={R} fill="none" className="stroke-border" strokeWidth="2.5" />
      <circle
        cx="12"
        cy="12"
        r={R}
        fill="none"
        className="stroke-primary transition-[stroke-dashoffset] duration-1000 ease-linear"
        strokeWidth="2.5"
        strokeLinecap="round"
        strokeDasharray={CIRCUMFERENCE}
        strokeDashoffset={CIRCUMFERENCE * (1 - progress)}
      />
    </svg>
  );
}

/** Resend button that shows a circular 60 second countdown while it is cooling down. */
export function ResendButton({
  cooldown,
  total = 60,
  loading = false,
  onClick,
  label = 'Resend email',
  variant = 'secondary',
  className,
}: {
  cooldown: number;
  total?: number;
  loading?: boolean;
  onClick: () => void;
  label?: string;
  variant?: 'primary' | 'secondary';
  className?: string;
}) {
  const waiting = cooldown > 0;
  return (
    <Button type="button" size="lg" variant={variant} className={cn('w-full', className)} loading={loading} disabled={waiting} onClick={onClick}>
      {waiting ? (
        <>
          <CountdownRing remaining={cooldown} total={total} />
          <span>
            Resend in <span className="tabular-nums">{cooldown}s</span>
          </span>
        </>
      ) : (
        <>
          {loading ? null : <RotateCw className="h-4 w-4" aria-hidden="true" />}
          {label}
        </>
      )}
    </Button>
  );
}
