"use client";

import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@hexahost/ui";
import { Link } from "@/i18n/navigation";
import { ApiError, verifyEmail } from "@/lib/api/auth";

type VerifyState = "idle" | "loading" | "success" | "error";

export function VerifyEmailContent() {
  const t = useTranslations("auth");
  const searchParams = useSearchParams();
  const token = searchParams.get("token");
  const sent = searchParams.get("sent");
  const [state, setState] = useState<VerifyState>(token ? "loading" : "idle");
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  useEffect(() => {
    if (!token) {
      return;
    }

    let cancelled = false;

    async function verify() {
      try {
        await verifyEmail(token!);
        if (!cancelled) {
          setState("success");
        }
      } catch (error) {
        if (!cancelled) {
          setState("error");
          if (error instanceof ApiError) {
            setErrorMessage(error.detail ?? error.title);
          } else {
            setErrorMessage(t("errors.generic"));
          }
        }
      }
    }

    void verify();

    return () => {
      cancelled = true;
    };
  }, [token, t]);

  if (sent === "1") {
    return (
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle>{t("verifyEmailTitle")}</CardTitle>
          <CardDescription>{t("verifyEmailSent")}</CardDescription>
        </CardHeader>
        <CardContent>
          <Link href="/login" className="text-sm font-medium text-sky-600 hover:underline dark:text-sky-400">
            {t("backToLogin")}
          </Link>
        </CardContent>
      </Card>
    );
  }

  if (!token) {
    return (
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle>{t("verifyEmailTitle")}</CardTitle>
          <CardDescription>{t("verifyEmailMissingToken")}</CardDescription>
        </CardHeader>
        <CardContent>
          <Link href="/login" className="text-sm font-medium text-sky-600 hover:underline dark:text-sky-400">
            {t("backToLogin")}
          </Link>
        </CardContent>
      </Card>
    );
  }

  if (state === "loading" || state === "idle") {
    return (
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle>{t("verifyEmailTitle")}</CardTitle>
          <CardDescription>{t("verifyEmailLoading")}</CardDescription>
        </CardHeader>
      </Card>
    );
  }

  if (state === "success") {
    return (
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle>{t("verifyEmailTitle")}</CardTitle>
          <CardDescription>{t("verifyEmailSuccess")}</CardDescription>
        </CardHeader>
        <CardContent>
          <Link href="/login" className="text-sm font-medium text-sky-600 hover:underline dark:text-sky-400">
            {t("backToLogin")}
          </Link>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="w-full max-w-md">
      <CardHeader>
        <CardTitle>{t("verifyEmailTitle")}</CardTitle>
        <CardDescription>{t("verifyEmailError")}</CardDescription>
      </CardHeader>
      <CardContent>
        {errorMessage ? (
          <p className="mb-4 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-900 dark:border-red-900 dark:bg-red-950 dark:text-red-100" role="alert">
            {errorMessage}
          </p>
        ) : null}
        <Link href="/login" className="text-sm font-medium text-sky-600 hover:underline dark:text-sky-400">
          {t("backToLogin")}
        </Link>
      </CardContent>
    </Card>
  );
}
