import React, { useState, useEffect } from "react";
import { toast } from "react-toastify";
import { API_URL } from "@/config";

export default function LoginPage() {
    const [redirectTo, setRedirectTo] = useState("/");
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const [loading, setLoading] = useState(false);

    // On mount, determine where to redirect after login:
    // 1. Use sessionStorage 'redirectTo' if present
    // 2. Else use document.referrer if same-origin
    // 3. Else fallback to "/"
    useEffect(() => {
        try {
            const savedRedirect = sessionStorage.getItem("redirectTo");
            if (savedRedirect) {
                setRedirectTo(savedRedirect);
            } else if (document.referrer) {
                const refUrl = new URL(document.referrer);
                // Only accept same origin referrers for security
                if (refUrl.origin === window.location.origin) {
                    const pathAndQuery = refUrl.pathname + refUrl.search;
                    setRedirectTo(pathAndQuery);
                    sessionStorage.setItem("redirectTo", pathAndQuery);
                }
            }
        } catch (error) {
            // Fail silently; fallback to "/"
            console.error("Error determining redirect target:", error);
            setRedirectTo("/");
        }
    }, []);

    async function handleSubmit(e) {
        e.preventDefault();
        setLoading(true);

        try {
            const formData = new URLSearchParams();
            formData.append("username", username);
            formData.append("password", password);
            formData.append("grant_type", "password");
            formData.append("scope", "");
            formData.append("client_id", "");
            formData.append("client_secret", "");

            const resp = await fetch(`${API_URL}/auth/login`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                credentials: "include", // Important for cookies
                body: formData.toString(),
            });

            if (resp.status === 401) {
                toast.error("Invalid username or password");
                setLoading(false);
                return;
            }

            if (!resp.ok) {
                if (resp.json().detail) {
                    toast.error(`Login failed: ${resp.json().detail}`);
                }
                else {
                    toast.error("Login failed");
                }
                setLoading(false);
                return;
            }

            const data = await resp.json();

            if (data.access_token) {
                toast.success("Login successful!");

                // Clear stored redirect after use
                sessionStorage.removeItem("redirectTo");

                // Redirect to stored path or fallback "/"
                window.location.href = redirectTo || "/";
            } else {
                toast.error("Login failed: no access token received");
                setLoading(false);
            }
        } catch (error) {
            toast.error("Network error during login");
            console.error("Login error:", error);
            setLoading(false);
        }
    }

    return (
        <div className="flex items-start justify-center bg-gray-50 dark:bg-[#121212] px-4 pt-20 py-50">
            <div className="max-w-md w-full bg-white dark:bg-[#1E1E1E] rounded-2xl shadow-xl px-10 pb-6">
                <h2 className="flex flex-col items-center text-3xl font-semibold text-gray-900 dark:text-white mb-8 font-sans">
                    <img className="logo-auth mb-4" src="/images/kode.png" alt="Logo" />
                    Authentication Required
                </h2>

                <form className="space-y-6" onSubmit={handleSubmit} noValidate>
                    <div>
                        <label
                            htmlFor="username"
                            className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                        >
                            Username
                        </label>
                        <input
                            type="text"
                            id="username"
                            name="username"
                            autoComplete="username"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                            required
                            className="appearance-none block w-full px-4 py-3 border border-gray-300 dark:border-gray-700 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-[#121212] dark:text-white"
                            placeholder="Your username"
                            disabled={loading}
                        />
                    </div>

                    <div>
                        <label
                            htmlFor="password"
                            className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                        >
                            Password
                        </label>
                        <input
                            type="password"
                            id="password"
                            name="password"
                            autoComplete="current-password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            required
                            className="appearance-none block w-full px-4 py-3 border border-gray-300 dark:border-gray-700 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-[#121212] dark:text-white"
                            placeholder="••••••••"
                            disabled={loading}
                        />
                    </div>

                    <button
                        type="submit"
                        disabled={loading}
                        className={`w-full py-3 bg-blue-600 hover:bg-blue-700 focus:ring-4 focus:ring-blue-300 text-white rounded-lg font-semibold shadow-md transition-colors ${loading ? "opacity-60 cursor-not-allowed" : ""
                            }`}
                    >
                        {loading ? "Signing In..." : "Sign In"}
                    </button>
                </form>
            </div>
        </div>
    );
}
