import { useEffect, useState } from "react";
import { Link, useLocalSearchParams } from "expo-router";
import { api } from "@/lib/api";
import { t } from "@/lib/i18n";
import { Body, LoadingView, Screen, Spacer, Title } from "@/components/ui";
import { colors, spacing } from "@/lib/theme";

/** Öppnas via länken i välkomstmejlet (urlScheme://verify-email?token=…). */
export default function VerifyEmailScreen() {
  const params = useLocalSearchParams<{ token?: string }>();
  const [state, setState] = useState<"working" | "done" | "failed">("working");

  useEffect(() => {
    if (!params.token) {
      setState("failed");
      return;
    }
    api("/v1/auth/verify-email", { method: "POST", body: { token: params.token } })
      .then(() => setState("done"))
      .catch(() => setState("failed"));
  }, [params.token]);

  if (state === "working") return <LoadingView />;
  return (
    <Screen scroll={false} style={{ justifyContent: "center", gap: spacing.md }}>
      <Title>{state === "done" ? t("auth.verifyDoneTitle") : t("auth.verifyFailedTitle")}</Title>
      <Body muted>{state === "done" ? t("auth.verifyDoneBody") : t("auth.verifyFailedBody")}</Body>
      <Spacer size={spacing.sm} />
      <Link href="/(tabs)" style={{ textAlign: "center", color: colors.primaryDark }}>
        {t("common.done")}
      </Link>
    </Screen>
  );
}
