"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
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"
import { AlertCircle, Loader2 } from "lucide-react"
import { sendVerificationCode, verifyCode } from "@/lib/sms/verification-actions"
import { createClient } from "@/lib/supabase-browser"

export default function Verify2FAPage() {
    const router = useRouter()
    const [code, setCode] = useState("")
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<string | null>(null)
    const [sent, setSent] = useState(false)
    const [maskedPhone, setMaskedPhone] = useState("")

    useEffect(() => {
        // Init: Send code automatically
        const init = async () => {
            setLoading(true)
            const result = await sendVerificationCode()
            setLoading(false)
            if (result.error) {
                setError(result.error)
            } else {
                setSent(true)
                setMaskedPhone(result.phone || "")
            }
        }
        init()
    }, [])

    const handleVerify = async (e: React.FormEvent) => {
        e.preventDefault()
        setLoading(true)
        setError(null)

        try {
            const result = await verifyCode(code)
            if (result.error) {
                setError(result.error)
            } else {
                router.push("/dashboard")
                router.refresh()
            }
        } catch {
            setError("Bir hata oluştu.")
        } finally {
            setLoading(false)
        }
    }

    const handleResend = async () => {
        setLoading(true)
        setError(null)
        const result = await sendVerificationCode()
        setLoading(false)
        if (result.error) {
            setError(result.error)
        } else {
            setSent(true)
        }
    }

    return (
        <div className="flex items-center justify-center min-h-screen bg-slate-50 dark:bg-slate-950 px-4">
            <Card className="w-full max-w-md">
                <CardHeader className="space-y-1">
                    <CardTitle className="text-2xl font-bold">SMS Doğrulama</CardTitle>
                    <CardDescription>
                        {sent ? `Telefonunuza (***${maskedPhone}) gönderilen 6 haneli kodu girin.` : "Doğrulama kodu gönderiliyor..."}
                    </CardDescription>
                </CardHeader>
                <CardContent>
                    {error && (
                        <div className="mb-4 flex items-center space-x-2 text-sm text-red-600 bg-red-50 p-3 rounded-md">
                            <AlertCircle className="h-4 w-4" />
                            <span>{error}</span>
                        </div>
                    )}

                    <form onSubmit={handleVerify} className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="code">Doğrulama Kodu</Label>
                            <Input
                                id="code"
                                type="text"
                                placeholder="123456"
                                value={code}
                                onChange={(e) => setCode(e.target.value)}
                                maxLength={6}
                                className="text-center text-lg tracking-widest"
                                required
                            />
                        </div>
                        <Button className="w-full" type="submit" disabled={loading || !sent}>
                            {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            Doğrula
                        </Button>
                    </form>
                </CardContent>
                <CardFooter className="flex flex-col gap-4 text-center text-sm text-muted-foreground">
                    <button
                        type="button"
                        onClick={handleResend}
                        disabled={loading}
                        className="underline underline-offset-4 hover:text-primary disabled:opacity-50"
                    >
                        Kodu Tekrar Gönder
                    </button>
                    <button
                        type="button"
                        onClick={async () => {
                            const supabase = createClient()
                            await supabase.auth.signOut()
                            router.push("/login")
                        }}
                        className="text-xs"
                    >
                        Giriş ekranına dön
                    </button>
                </CardFooter>
            </Card>
        </div>
    )
}
