"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { useToast } from "@/components/ui/toast";
import { clientFetch } from "@/lib/api/client";

export function ResendVerificationBanner() {
  const [message, setMessage] = useState<{ text: string; ok: boolean } | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { toast } = useToast();

  async function handleResend() {
    setIsSubmitting(true);
    const res = await clientFetch("/api/auth/email/resend", { method: "POST" });
    setIsSubmitting(false);
    const body = await res.json().catch(() => null);

    const text = res.ok
      ? (body?.message ?? "A new verification link has been sent to your email.")
      : (body?.message ?? "Failed to resend verification link. Please try again.");
    setMessage({ text, ok: res.ok });
    toast(text, res.ok ? "success" : "error");
  }

  return (
    <div className="flex flex-col gap-2 rounded-xl border border-kolabora-tertiary/30 bg-kolabora-tertiary/10 p-4 text-sm sm:flex-row sm:items-center sm:justify-between">
      <p className="text-kolabora-neutral-dark/80">
        Your email hasn&apos;t been verified. Check your inbox for the verification link.
      </p>
      <div className="flex shrink-0 items-center gap-3">
        <Button type="button" variant="secondary" size="sm" onClick={handleResend} loading={isSubmitting}>
          Resend
        </Button>
      </div>
      {message && (
        <p className={message.ok ? "text-green-600" : "text-red-600"}>{message.text}</p>
      )}
    </div>
  );
}
