"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, useRouter } from "@/i18n/navigation";
import { ApiError, consumeSsoTicket } from "@/lib/api/auth";
import { useAuth } from "@/components/providers/auth-provider";

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

export function SsoContent() {
  const t = useTranslations("auth");
  const searchParams = useSearchParams();
  const router = useRouter();
  const { refresh } = useAuth();
  const ticket = searchParams.get("ticket");
  const [state, setState] = useState<SsoState>(ticket ? "loading" : "idle");
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

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

    let cancelled = false;

    async function redeem() {
      try {
        const result = await consumeSsoTicket(ticket!);
        await refresh();
        if (!cancelled) {
          setState("success");
          router.replace(result.redirectPath);
        }
      } catch (error) {
        if (!cancelled) {
          setState("error");
          if (error instanceof ApiError) {
            setErrorMessage(error.detail ?? error.title);
          } else {
            setErrorMessage(t("errors.generic"));
          }
        }
      }
    }

    void redeem();

    return () => {
      cancelled = true;
    };
  }, [ticket, refresh, router, t]);

  if (!ticket) {
    return (
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle>{t("ssoTitle")}</CardTitle>
          <CardDescription>{t("ssoMissingTicket")}</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" || state === "success") {
    return (
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle>{t("ssoTitle")}</CardTitle>
          <CardDescription>{t("ssoLoading")}</CardDescription>
        </CardHeader>
      </Card>
    );
  }

  return (
    <Card className="w-full max-w-md">
      <CardHeader>
        <CardTitle>{t("ssoTitle")}</CardTitle>
        <CardDescription>{t("ssoError")}</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>
  );
}
