"use client";

import Link from "next/link";
import { useEffect, useState } from "react";

import { useLocale } from "@/components/providers/locale-provider";

export function VerifyEmailClient({ token }: { token: string }) {
  const { dict } = useLocale();
  const [message, setMessage] = useState<string | null>(dict.verifyEmail.verifying);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function verify() {
      if (!token) {
        setError(dict.verifyEmail.tokenMissing);
        setMessage("");
        return;
      }

      try {
        const response = await fetch("/api/v1/auth/verify-email", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ token })
        });
        const payload = (await response.json()) as { message?: string };
        if (!response.ok) {
          throw new Error(payload.message ?? dict.verifyEmail.failure);
        }
        setMessage(payload.message ?? dict.verifyEmail.success);
      } catch (err) {
        setError(err instanceof Error ? err.message : dict.verifyEmail.failure);
        setMessage("");
      }
    }

    void verify();
  }, [token, dict.verifyEmail.failure, dict.verifyEmail.success, dict.verifyEmail.tokenMissing]);

  return (
    <main className="flex min-h-screen items-center justify-center bg-canvas px-6 py-10">
      <div className="w-full max-w-xl rounded-lg border border-line/70 bg-white p-8 shadow-panel sm:p-12">
        <h1 className="text-[36px] font-semibold tracking-tight text-ink">{dict.verifyEmail.title}</h1>
        {message ? <div className="mt-6 rounded border border-moss/30 bg-moss/10 px-4 py-3 text-sm text-moss">{message}</div> : null}
        {error ? <div className="mt-6 rounded border border-ember/30 bg-ember/10 px-4 py-3 text-sm text-ember">{error}</div> : null}
        <div className="mt-8">
          <Link href="/login" className="text-sm font-semibold text-moss">
            {dict.common.continueToLogin}
          </Link>
        </div>
      </div>
    </main>
  );
}
