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

/**
 * Glömt lösenord (steg 1): begär återställningsmejl. Svaret är alltid samma
 * oavsett om kontot finns – ingen kontouppräkning. Mejlet innehåller en
 * app-länk (urlScheme://reset-password?token=…) som öppnar steg 2.
 */
export default function ForgotPasswordScreen() {
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const submit = async () => {
    setBusy(true);
    setError(null);
    try {
      await api("/v1/auth/forgot-password", { method: "POST", body: { email } });
      setSent(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    } finally {
      setBusy(false);
    }
  };

  if (sent) {
    return (
      <Screen scroll={false} style={{ justifyContent: "center", gap: spacing.md }}>
        <Title>{t("auth.forgotSentTitle")}</Title>
        <Body muted>{t("auth.forgotSentBody")}</Body>
        <Spacer size={spacing.sm} />
        <Link href="/(auth)/login" style={{ textAlign: "center", color: colors.primaryDark }}>
          {t("auth.backToLogin")}
        </Link>
      </Screen>
    );
  }

  return (
    <Screen scroll={false} style={{ justifyContent: "center", gap: spacing.md }}>
      <Title>{t("auth.forgotTitle")}</Title>
      <Body muted>{t("auth.forgotBody")}</Body>
      <Input
        placeholder={t("auth.email")}
        autoCapitalize="none"
        keyboardType="email-address"
        value={email}
        onChangeText={setEmail}
      />
      {error && <Text style={{ color: colors.danger }}>{error}</Text>}
      <Button label={t("auth.forgotSubmit")} onPress={() => void submit()} loading={busy} />
      <Spacer size={spacing.sm} />
      <Link href="/(auth)/login" style={{ textAlign: "center", color: colors.primaryDark }}>
        {t("auth.backToLogin")}
      </Link>
    </Screen>
  );
}
