import { useEffect, useState } from "react";
import { useParams, Link } from "react-router-dom";
import { apiAccountConfirmEmailChangeRetrieve } from "@/api/generated/private/account/account";
import { useAuth } from "@/hooks/useAuth";
import Spinner from "@/components/ui/Spinner";

type Status = "loading" | "success" | "error";

export default function ConfirmEmailChangePage() {
  const { uidb64, token } = useParams<{ uidb64: string; token: string }>();
  const { refreshUser } = useAuth();
  const [status, setStatus] = useState<Status>("loading");
  const [message, setMessage] = useState("");

  useEffect(() => {
    if (!uidb64 || !token) {
      setStatus("error");
      setMessage("Neplatný odkaz.");
      return;
    }
    apiAccountConfirmEmailChangeRetrieve(uidb64, token)
      .then(() => {
        setStatus("success");
        setMessage("E-mail byl úspěšně změněn.");
        refreshUser?.();
      })
      .catch((err: any) => {
        setStatus("error");
        setMessage(err?.response?.data?.error ?? "Odkaz je neplatný nebo expirovaný.");
      });
  }, [uidb64, token]);

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
      <div className="glass rounded-2xl p-10 text-center max-w-sm w-full flex flex-col items-center gap-4">
        {status === "loading" && <Spinner size={32} />}

        {status === "success" && (
          <>
            <span className="text-5xl">✅</span>
            <h1 className="text-xl font-bold text-brand-text">E-mail změněn</h1>
            <p className="text-sm text-brand-text/60">{message}</p>
            <Link to="/social/account/settings" className="text-sm text-brand-accent hover:underline">
              Zpět na nastavení
            </Link>
          </>
        )}

        {status === "error" && (
          <>
            <span className="text-5xl">❌</span>
            <h1 className="text-xl font-bold text-brand-text">Chyba</h1>
            <p className="text-sm text-brand-text/60">{message}</p>
            <Link to="/social/account/settings" className="text-sm text-brand-accent hover:underline">
              Zpět na nastavení
            </Link>
          </>
        )}
      </div>
    </div>
  );
}
