import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Mail, Lock, LogIn, ArrowLeft } from 'lucide-react';
import Header from '../components/Header';
import { requestLogin, requestLoginGoogle } from '../config/UserRequest.jsx';
import { useStore } from '../hooks/useStore';
import { toast } from 'react-toastify';
import Footer from '../components/Footer';
import { Helmet } from 'react-helmet';
import { useGoogleLogin } from '@react-oauth/google';
import axios from 'axios';

function LoginUser() {
    const navigate = useNavigate();
    const { fetchAuth, dataWebsite } = useStore();
    const [loading, setLoading] = useState(false);
    const [googleLoading, setGoogleLoading] = useState(false);
    const [formData, setFormData] = useState({
        email: '',
        password: '',
    });

    const handleChange = (e) => {
        setFormData({
            ...formData,
            [e.target.name]: e.target.value,
        });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!formData.email || !formData.password) {
            toast.error('Vui lòng nhập đầy đủ thông tin!');
            return;
        }

        setLoading(true);
        try {
            await requestLogin(formData);
            toast.success('Đăng nhập thành công!');
            await fetchAuth();
            navigate('/');
        } catch (error) {
            toast.error(error.response?.data?.message || 'Đăng nhập thất bại!');
        } finally {
            setLoading(false);
        }
    };

    const handleGoogleLogin = useGoogleLogin({
        onSuccess: async (tokenResponse) => {
            setGoogleLoading(true);
            try {
                // Lấy thông tin user từ Google
                const userInfo = await axios.get('https://www.googleapis.com/oauth2/v3/userinfo', {
                    headers: { Authorization: `Bearer ${tokenResponse.access_token}` },
                });

                // Gửi lên server (dùng email + name từ userInfo)
                await requestLoginGoogle({ credential: tokenResponse.access_token, userInfo: userInfo.data });
                toast.success('Đăng nhập bằng Google thành công!');
                await fetchAuth();
                navigate('/');
            } catch (error) {
                toast.error(error.response?.data?.message || 'Đăng nhập Google thất bại!');
            } finally {
                setGoogleLoading(false);
            }
        },
        onError: () => {
            toast.error('Đăng nhập Google thất bại!');
        },
    });

    return (
        <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-orange-50">
            <Helmet>
                <title>Đăng nhập | {dataWebsite?.nameWebsite || 'Website'}</title>
            </Helmet>
            <header className="pb-16">
                <Header />
            </header>

            <main className="container mx-auto px-4 py-12 flex items-center justify-center min-h-[calc(100vh-64px)]">
                <div className="w-full max-w-md bg-white rounded-2xl shadow-xl border border-gray-100 overflow-hidden transform transition-all hover:shadow-2xl">
                    {/* Header Section */}
                    <div className="bg-gradient-to-r from-orange-500 to-red-500 p-8 text-center text-white relative">
                        <Link
                            to="/"
                            className="absolute top-4 left-4 p-2 bg-white/20 hover:bg-white/30 rounded-full transition-colors"
                            title="Quay lại trang chủ"
                        >
                            <ArrowLeft size={20} />
                        </Link>
                        <div className="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-4 backdrop-blur-sm">
                            <LogIn size={32} />
                        </div>
                        <h2 className="text-3xl font-bold mb-2">Đăng Nhập</h2>
                        <p className="text-orange-100 text-sm">Chào mừng bạn quay trở lại!</p>
                    </div>

                    {/* Form Section */}
                    <div className="p-8 space-y-6">
                        <form onSubmit={handleSubmit} className="space-y-5">
                            {/* Email Input */}
                            <div className="space-y-1">
                                <label className="text-sm font-semibold text-gray-700 ml-1">Email</label>
                                <div className="relative">
                                    <input
                                        type="email"
                                        name="email"
                                        value={formData.email}
                                        onChange={handleChange}
                                        placeholder="Nhập địa chỉ email"
                                        className="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-orange-400 focus:border-transparent transition-all"
                                        required
                                    />
                                    <Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
                                </div>
                            </div>

                            {/* Password Input */}
                            <div className="space-y-1">
                                <label className="text-sm font-semibold text-gray-700 ml-1">Mật khẩu</label>
                                <div className="relative">
                                    <input
                                        type="password"
                                        name="password"
                                        value={formData.password}
                                        onChange={handleChange}
                                        placeholder="Nhập mật khẩu"
                                        className="w-full pl-10 pr-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-orange-400 focus:border-transparent transition-all"
                                        required
                                    />
                                    <Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
                                </div>
                            </div>

                            {/* Forgot Password Link */}
                            <div className="flex justify-end">
                                <Link
                                    to="/forgot-password"
                                    className="text-sm text-orange-600 hover:text-orange-700 font-medium transition-colors"
                                >
                                    Quên mật khẩu?
                                </Link>
                            </div>

                            {/* Submit Button */}
                            <button
                                type="submit"
                                disabled={loading}
                                className="w-full bg-gradient-to-r from-orange-500 to-red-500 text-white font-bold py-3.5 rounded-xl shadow-lg hover:shadow-xl hover:from-orange-600 hover:to-red-600 transform transition-all active:scale-[0.98] disabled:opacity-70 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                            >
                                {loading ? (
                                    <>
                                        <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
                                        <span>Đang xử lý...</span>
                                    </>
                                ) : (
                                    <>
                                        <span>Đăng Nhập Ngay</span>
                                        <LogIn size={20} />
                                    </>
                                )}
                            </button>
                        </form>

                        {/* Divider */}
                        <div className="relative flex items-center">
                            <div className="flex-1 border-t border-gray-200"></div>
                            <span className="px-4 text-sm text-gray-400 font-medium">hoặc tiếp tục với</span>
                            <div className="flex-1 border-t border-gray-200"></div>
                        </div>

                        {/* Google Login Button */}
                        <button
                            type="button"
                            onClick={handleGoogleLogin}
                            disabled={googleLoading}
                            className="w-full flex items-center justify-center gap-3 py-3.5 px-4 bg-white border-2 border-gray-200 rounded-xl font-semibold text-gray-700 hover:bg-gray-50 hover:border-gray-300 hover:shadow-md transition-all duration-200 active:scale-[0.98] disabled:opacity-70 disabled:cursor-not-allowed"
                        >
                            {googleLoading ? (
                                <>
                                    <div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin"></div>
                                    <span>Đang kết nối Google...</span>
                                </>
                            ) : (
                                <>
                                    {/* Google Icon SVG */}
                                    <svg width="20" height="20" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
                                        <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
                                        <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
                                        <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
                                    </svg>
                                    <span>Đăng nhập với Google</span>
                                </>
                            )}
                        </button>

                        {/* Register Link */}
                        <div className="text-center pt-4 border-t border-gray-100">
                            <p className="text-gray-600 text-sm">
                                Chưa có tài khoản?{' '}
                                <Link
                                    to="/register"
                                    className="text-orange-600 font-bold hover:text-orange-700 hover:underline transition-colors"
                                >
                                    Đăng ký ngay
                                </Link>
                            </p>
                        </div>
                    </div>
                </div>
            </main>
            <Footer />
        </div>
    );
}

export default LoginUser;
