"use client";

import Link from "next/link";
import { ArrowUpRight, MailWarning } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { useAuth } from "./auth-context";
import { useDevMailLink } from "./dev-mail-link";
import { useEmailVerification } from "./useAccountRecovery";

/**
 * Shown on every workspace page until the email address is verified, and while a change of sign-in email waits for
 * confirmation. Verification is a reminder and never blocks an authorized action.
 */
export function EmailVerificationBanner() {
  const { user } = useAuth();
  const { address, resend, cancelChange, cooldown, isResending, isCancelling } = useEmailVerification();
  const devLink = useDevMailLink();

  // Platform support sessions cannot verify on the user's behalf.
  if (!user || user.impersonation || (user.emailVerified !== false && !user.pendingEmail)) return null;
  const isChange = user.emailVerified !== false;

  return <div role="status" className="flex flex-wrap items-center gap-x-4 gap-y-2 border-b bg-warning/10 px-4 py-2.5 text-sm md:px-6">
    <MailWarning className="size-4 shrink-0 text-warning" aria-hidden="true" />
    <p className="min-w-0 flex-1 basis-64">
      {isChange
        ? <><span className="font-medium">Confirm your new email.</span> Open the link we sent to <span className="[overflow-wrap:anywhere] font-medium">{address}</span> to finish changing your sign-in email.</>
        : <><span className="font-medium">Verify your email when convenient.</span> We sent a link to <span className="[overflow-wrap:anywhere] font-medium">{address}</span>. You can continue using the workspace in the meantime.</>}
    </p>
    <div className="flex flex-wrap items-center gap-2">
      {devLink && <Button variant="link" size="sm" className="h-auto p-0" asChild><a href={devLink}>Development: open the email link <ArrowUpRight /></a></Button>}
      <Button variant="outline" size="sm" onClick={resend} disabled={cooldown > 0 || isResending}>{isResending && <Spinner />} {cooldown > 0 ? `Resend in ${cooldown}s` : "Resend link"}</Button>
      {isChange
        ? <Button variant="ghost" size="sm" onClick={cancelChange} disabled={isCancelling}>{isCancelling && <Spinner />} Cancel change</Button>
        : <Button variant="ghost" size="sm" asChild><Link href="/verify-email">Wrong address?</Link></Button>}
    </div>
  </div>;
}
