"use client";

import Image from "next/image"
import { useState } from "react";
import { useRouter } from "next/navigation";
import axios from "axios";
import Cookies from "js-cookie";
import ErrorToast from "@/components/Error";
import { Eye, EyeClosed, Lock, Mail } from "lucide-react";

export default function LoginPage() {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [remember, setRemember] = useState(false);
    const [showPassword, setShowPassword] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState("");
    
    const router = useRouter();

    const login = async () => {
        if (!email || !password) {
            setError("Please enter both email and password");
            return;
        }

        setIsLoading(true);
        try {
            const response = await axios.post("/api/user/login", { email, password, remember });
            
            if (response.status === 200) {
                const token = response.data.token;
                if (token) {
                    Cookies.set("token", token);
                    router.push("/dashboard");
                } else {
                    setError("No login token received");
                }
            }
        } catch (error: any) {
            setError(error.response?.data?.error || "Login failed");
        } finally {
            setIsLoading(false);
        }
    };

    const handleKeyPress = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter') {
            login();
        }
    };
    
    return (
        <div className="min-h-screen flex flex-col lg:flex-row bg-base-100">
            <div className="flex-1 flex items-center justify-center p-6 lg:p-10">
                <div className="w-full max-w-md">
                    <div className="card bg-base-100 shadow-xl p-8 border border-base-300">
                        <div className="text-center mb-8">
                            <div className="mb-4 inline-flex rounded-full justify-center items-center">
                                <Image 
                                    src="/logo.png" 
                                    width={64} 
                                    height={64} 
                                    alt="Core Logo" 
                                    className="mask mask-circle" 
                                />
                            </div>
                            <h1 className="text-3xl font-bold">Welcome back</h1>
                            <p className="mt-2 text-base-content/70">Please login with your account</p>
                        </div>

                        <div className="space-y-2">
                            <div className="w-full">
                              <fieldset className="fieldset">
                                  <legend className="fieldset-legend">Email</legend>
                                  <label className="input validator w-full">
                                    <Mail className="opacity-50"/>
                                    <input 
                                        type="email" 
                                        placeholder="mail@site.com" 
                                        required 
                                        value={email}
                                        onChange={(e) => setEmail(e.target.value)}
                                        onKeyDown={handleKeyPress}
                                    />
                                  </label>
                              </fieldset>
                            </div>
                            <div className="w-full">
                              <fieldset className="fieldset">
                                  <legend className="fieldset-legend">Password</legend>
                                  <label className="input validator w-full relative">
                                    <Lock className="opacity-50"/>
                                    <input 
                                        type={showPassword ? "text" : "password"} 
                                        placeholder="* * * * * * * *" 
                                        required 
                                        value={password}
                                        onChange={(e) => setPassword(e.target.value)}
                                        onKeyDown={handleKeyPress}
                                    />
                                    <button 
                                        type="button"
                                        className="absolute right-3 top-1/2 transform -translate-y-1/2"
                                        onClick={() => setShowPassword(!showPassword)}
                                    >
                                        {showPassword ? (
                                            <EyeClosed className="h-5 w-5 opacity-50 hover:opacity-100" />
                                        ) : (
                                            <Eye className="h-5 w-5 opacity-50 hover:opacity-100" />
                                        )}
                                    </button>
                                  </label>
                              </fieldset>
                            </div>
                            <div className="w-full">
                                <label className="label cursor-pointer justify-start gap-2">
                                    <input 
                                        type="checkbox" 
                                        className="checkbox checkbox-primary" 
                                        checked={remember} 
                                        onChange={(e) => setRemember(e.target.checked)} 
                                    />
                                    <span className="label-text">Stay logged in</span>
                                </label>
                            </div>

                            <button 
                                className={`btn btn-primary w-full ${isLoading ? 'loading' : ''}`} 
                                onClick={login}
                                disabled={isLoading}
                            >
                                {isLoading ? 'Logging in...' : 'Login'}
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div className="flex-1 bg-base-200 hidden lg:block relative overflow-hidden">
                <div className="absolute inset-0 bg-gradient-to-br from-base-300/30 to-transparent z-10"></div>
                <div className="h-full w-full relative">
                    <Image
                        src="/login_wallpaper.jpg"
                        alt="Login Illustration"
                        fill
                        className="object-cover"
                        priority
                    />
                </div>
            </div>

            <div className="h-48 bg-base-200 relative lg:hidden overflow-hidden">
                <div className="absolute inset-0 bg-gradient-to-t from-primary/20 to-transparent z-10"></div>
                <Image
                    src="/login_wallpaper.jpg"
                    alt="Login Illustration"
                    fill
                    className="object-cover"
                    priority
                />
            </div>

            <ErrorToast message={error} show={error !== ""} onClose={() => setError("")} />
        </div>
    );
}
