import { useAuthActions } from "@convex-dev/auth/react";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";

export function SignIn() {
    const { signIn } = useAuthActions();
    const router = useRouter();
    const [step, setStep] = useState<"signIn" | "signUp">("signIn");
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [error, setError] = useState<string | null>(null);

    const handleSubmit = async (event: React.FormEvent) => {
        event.preventDefault();
        setError(null);
        try {
            const flow = step === "signIn" ? "signIn" : "signUp";
            await signIn("password", { email, password, flow });
            if (flow === "signIn") {
                router.push("/dashboard");
            } else {
                router.push("/onboarding");
            }
        } catch (err: any) {
            console.error(err);
            const errorMessage = err.message || "Error signing in. Please check your credentials.";
            if (errorMessage.includes("Account") && errorMessage.includes("already exists")) {
                setError("Account already exists. Please sign in instead.");
            } else {
                setError(errorMessage);
            }
        }
    };

    return (
        <Card className="w-full max-w-md mx-auto mt-20 shadow-lg">
            <CardHeader className="space-y-1">
                <CardTitle className="text-2xl font-bold text-center">
                    {step === "signIn" ? "Welcome back" : "Create an account"}
                </CardTitle>
                <CardDescription className="text-center">
                    {step === "signIn"
                        ? "Enter your email to sign in to your account"
                        : "Enter your email below to create your account"}
                </CardDescription>
            </CardHeader>
            <CardContent>
                <form onSubmit={handleSubmit} className="space-y-4">
                    {error && (
                        <div className="bg-destructive/15 text-destructive text-sm p-3 rounded-md text-center">
                            {error}
                        </div>
                    )}
                    <div className="space-y-2">
                        <Label htmlFor="email">Email</Label>
                        <Input
                            id="email"
                            type="email"
                            placeholder="m@example.com"
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            required
                        />
                    </div>
                    <div className="space-y-2">
                        <Label htmlFor="password">Password</Label>
                        <Input
                            id="password"
                            type="password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            required
                            minLength={8}
                        />
                    </div>
                    <Button type="submit" className="w-full">
                        {step === "signIn" ? "Sign In" : "Sign Up"}
                    </Button>
                </form>
            </CardContent>
            <CardFooter className="flex flex-col gap-4">
                <div className="relative w-full">
                    <div className="absolute inset-0 flex items-center">
                        <span className="w-full border-t" />
                    </div>
                    <div className="relative flex justify-center text-xs uppercase">
                        <span className="bg-background px-2 text-muted-foreground">
                            Or
                        </span>
                    </div>
                </div>
                <Button
                    variant="link"
                    onClick={() => setStep(step === "signIn" ? "signUp" : "signIn")}
                    className="w-full"
                >
                    {step === "signIn" ? "Don't have an account? Sign up" : "Already have an account? Sign in"}
                </Button>
            </CardFooter>
        </Card>
    );
}
