"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { authClient } from "@/lib/auth/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";

export default function Verify2faPage() {
  const router = useRouter();
  const t = useTranslations("auth");
  const [code, setCode] = useState("");
  const [useBackupCode, setUseBackupCode] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    const { error } = useBackupCode
      ? await authClient.twoFactor.verifyBackupCode({ code: code.trim() })
      : await authClient.twoFactor.verifyTotp({ code: code.trim() });
    setLoading(false);
    if (error) {
      setError(error.message ?? t("twoFactorInvalidCode"));
    } else {
      router.push("/recipes");
    }
  }

  return (
    <Card>
      <CardHeader className="space-y-1">
        <CardTitle className="text-2xl font-semibold tracking-tight">{t("twoFactorTitle")}</CardTitle>
        <CardDescription>
          {useBackupCode ? t("twoFactorBackupDescription") : t("twoFactorAppDescription")}
        </CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit}>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="code">{useBackupCode ? t("twoFactorBackupCodeLabel") : t("twoFactorCodeLabel")}</Label>
            <Input
              id="code"
              value={code}
              onChange={(e) => setCode(e.target.value)}
              autoComplete="one-time-code"
              autoFocus
              inputMode={useBackupCode ? "text" : "numeric"}
              placeholder={useBackupCode ? undefined : "000000"}
              required
            />
          </div>
          {error && <p className="text-sm text-destructive">{error}</p>}
          <Button className="w-full" type="submit" disabled={loading || !code.trim()}>
            {loading ? t("twoFactorVerifying") : t("twoFactorVerify")}
          </Button>
        </CardContent>
      </form>
      <CardFooter className="flex justify-center">
        <button
          type="button"
          onClick={() => { setUseBackupCode(!useBackupCode); setCode(""); setError(null); }}
          className="text-sm text-muted-foreground underline underline-offset-4 hover:text-foreground"
        >
          {useBackupCode ? t("twoFactorUseApp") : t("twoFactorUseBackupCode")}
        </button>
      </CardFooter>
    </Card>
  );
}
