"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { verifyPlanPassword } from "@/app/actions/auth"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { toast } from "sonner"

interface PlanLoginFormProps {
    planId: string;
    dict: any;
}

export function PlanLoginForm({ planId, dict }: PlanLoginFormProps) {
    const [password, setPassword] = useState("")
    const [isPending, setIsPending] = useState(false)
    const router = useRouter()

    async function handleSubmit(e: React.FormEvent) {
        e.preventDefault()
        setIsPending(true)

        try {
            const success = await verifyPlanPassword(planId, password)
            if (success) {
                router.refresh()
            } else {
                toast.error(dict.error)
            }
        } catch (error) {
            toast.error("An error occurred")
        } finally {
            setIsPending(false)
        }
    }

    return (
        <Card className="w-full max-w-sm">
            <CardHeader>
                <CardTitle>{dict.title}</CardTitle>
                <CardDescription>
                    {dict.description}
                </CardDescription>
            </CardHeader>
            <CardContent>
                <form onSubmit={handleSubmit} className="space-y-4">
                    <Input
                        type="password"
                        placeholder="••••••••"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        required
                    />
                    <Button type="submit" className="w-full" disabled={isPending}>
                        {isPending ? "..." : dict.submit}
                    </Button>
                </form>
            </CardContent>
        </Card>
    )
}
