import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { CircleAlert } from "lucide-react";

import { login } from "@/services/auth";


export function LoginForm({
    className,
    ...props
}: React.ComponentProps<"div">) {

    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");

    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // Redirect if already logged in
    useEffect(() => {
        const token = localStorage.getItem("access_token");
        if (token) {
            navigate("/", { replace: true }); // Redirect to homepage
        }
    }, [navigate]);

    const handelLogin = async (e) => {
        e.preventDefault();
        try {
            setLoading(true)
            await login(username, password);

            // Get the stored redirect path from localStorage
            const redirectPath = localStorage.getItem("redirect_after_login") || "/";
            localStorage.removeItem("redirect_after_login"); // clear the redirect path after use

            // Redirect to the stored path
            navigate(redirectPath, { replace: true });
        } catch (err) {
            setError("Invalid credentials. Please try again.");
            console.log(err)
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className={cn("flex flex-col gap-6", className)} {...props}>
            <Card className="overflow-hidden border-2 border-fuchsia-800">
                <CardContent className="grid p-0 md:grid-cols-2">
                    <form onSubmit={handelLogin} className="p-6 md:p-8">
                        <div className="flex flex-col gap-6">
                            <div className="flex flex-col items-center text-center">
                                <h1 className="text-2xl font-bold">Welcome back</h1>
                                <p className="text-balance text-muted-foreground">
                                    Login to your {__SITE_NAME__} account
                                </p>
                            </div>
                            {error && <div className="flex flex-row border-2 border-red-600 p-6 bg-red-400 bg-opacity-40 rounded-md">
                                <CircleAlert />
                                <p className="ps-4">{error}</p>
                            </div>}
                            <div className="grid gap-2">
                                <Label htmlFor="username">Username</Label>
                                <Input
                                    id="username"
                                    type="text"
                                    required
                                    value={username}
                                    onChange={(e) => setUsername(e.target.value)}
                                    tabIndex={1}
                                />
                            </div>
                            <div className="grid gap-2">
                                <div className="flex items-center">
                                    <Label htmlFor="password">Password</Label>
                                    <a
                                        href="#"
                                        className="ml-auto text-sm underline-offset-2 hover:underline"
                                        tabIndex={4}
                                    >
                                        Forgot your password?
                                    </a>
                                </div>
                                <Input
                                    id="password"
                                    type="password"
                                    required
                                    value={password}
                                    onChange={(e) => setPassword(e.target.value)}
                                    tabIndex={2}
                                />
                            </div>
                            <Button type="submit" className="w-full bg-primary" tabIndex={3}>
                                {loading ? "Logging in..." : "Login"}
                            </Button>
                            <div className="text-center text-sm">
                                Don&apos;t have an account?{" "}
                                <a href="/user/register" className="underline underline-offset-4">
                                    Sign up
                                </a>
                            </div>
                        </div>
                    </form>
                    <div className="relative hidden bg-muted md:block bg-zinc-300 dark:bg-indigo-950">
                        <img
                            src="/images/wave.gif"
                            alt="Image"
                            className="absolute p-12 inset-0 h-full w-full object-cover dark:brightness-[0.6]"
                        />
                    </div>
                </CardContent>
            </Card>
            <div className="text-balance text-center text-xs text-muted-foreground [&_a]:underline [&_a]:underline-offset-4 hover:[&_a]:text-primary">
                By clicking continue, you agree to our <a href="#">Terms of Service</a>{" "}
                and <a href="#">Privacy Policy</a>.
            </div>
        </div>
    )
}
