"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Shield } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";

export default function MFAVerifyPage() {
  const router = useRouter();
  const [token, setToken] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function handleVerify() {
    setError(null);
    setLoading(true);
    const res = await fetch("/api/mfa/verify-session", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ token }),
    });
    setLoading(false);

    if (!res.ok) {
      setError("Invalid code. Please try again.");
      return;
    }

    router.push("/dashboard");
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 p-4">
      <Card className="w-full max-w-sm border-slate-700 bg-slate-800/50 backdrop-blur">
        <CardHeader className="text-center">
          <div className="flex justify-center mb-2">
            <div className="rounded-full bg-emerald-500/20 p-3">
              <Shield className="h-6 w-6 text-emerald-400" />
            </div>
          </div>
          <CardTitle className="text-white">Two-factor authentication</CardTitle>
          <CardDescription className="text-slate-400">
            Enter the 6-digit code from your authenticator app
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {error && (
            <div className="rounded-lg bg-red-500/10 border border-red-500/20 px-4 py-3 text-sm text-red-400">
              {error}
            </div>
          )}
          <div className="space-y-2">
            <Label htmlFor="token" className="text-slate-300">Verification code</Label>
            <Input
              id="token"
              value={token}
              onChange={(e) => setToken(e.target.value.replace(/\D/g, "").slice(0, 6))}
              placeholder="000000"
              className="bg-slate-700/50 border-slate-600 text-white text-center text-lg tracking-widest placeholder:text-slate-500"
              maxLength={6}
            />
          </div>
          <Button
            onClick={handleVerify}
            className="w-full bg-emerald-600 hover:bg-emerald-500"
            disabled={token.length !== 6 || loading}
          >
            {loading ? "Verifying…" : "Verify"}
          </Button>
        </CardContent>
      </Card>
    </div>
  );
}
