import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import toast from 'react-hot-toast';
import { Lock, Mail, User } from 'lucide-react';
import { logo } from '../assets';

const API_URL = 'http://localhost/AAbank_mob/backend/api.php';

const Login = () => {
    const [formData, setFormData] = useState({ username: '', password: '' });
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);

        try {
            const response = await fetch(`${API_URL}/login`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            const data = await response.json();

            if (response.ok) {
                localStorage.setItem('iosco_token', data.token);
                localStorage.setItem('iosco_user', JSON.stringify(data.user));
                toast.success(data.message);
                navigate('/dashboard');
            } else {
                toast.error(data.message || 'Login failed');
            }
        } catch (err) {
            toast.error('Network error. Please try again later.');
        } finally {
            setLoading(false);
        }
    };

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

    return (
        <div className="min-h-screen bg-primary flex flex-col justify-center py-12 sm:px-6 lg:px-8 relative overflow-hidden">
            <div className="absolute z-[0] w-[40%] h-[35%] top-0 right-0 pink__gradient opacity-40 pointer-events-none" />
            <div className="absolute z-[0] w-[50%] h-[50%] top-1/2 left-0 blue__gradient opacity-20 pointer-events-none" />

            <div className="sm:mx-auto sm:w-full sm:max-w-md relative z-10">
                <div className="flex justify-center">
                    <Link to="/" className="flex items-center text-white font-poppins font-bold text-3xl tracking-wide">
                        <img src={logo} alt="IOSCO Bank" className="h-10 mr-3" />
                    </Link>
                </div>
                <h2 className="mt-6 text-center text-3xl font-poppins font-semibold text-white">
                    Sign in to your account
                </h2>
                <p className="mt-2 text-center text-sm text-dimWhite font-poppins">
                    Or{' '}
                    <Link to="/register" className="font-medium text-secondary hover:text-white transition-colors">
                        create a new account
                    </Link>
                </p>
            </div>

            <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md relative z-10">
                <div className="bg-black-gradient-2 py-8 px-4 shadow-xl border border-gray-800 rounded-[20px] sm:px-10">
                    <form className="space-y-6" onSubmit={handleSubmit}>
                        <div>
                            <label className="block text-sm font-poppins font-medium text-dimWhite">Username</label>
                            <div className="mt-2 relative rounded-md shadow-sm">
                                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <User className="h-5 w-5 text-dimWhite" />
                                </div>
                                <input
                                    name="username"
                                    type="text"
                                    required
                                    value={formData.username}
                                    onChange={handleChange}
                                    className="w-full bg-primary/50 text-white border border-gray-700 focus:border-secondary rounded-xl pl-10 px-4 py-3 font-poppins outline-none transition-colors duration-300"
                                    placeholder="Enter your username"
                                />
                            </div>
                        </div>

                        <div>
                            <label className="block text-sm font-poppins font-medium text-dimWhite">Password</label>
                            <div className="mt-2 relative rounded-md shadow-sm">
                                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <Lock className="h-5 w-5 text-dimWhite" />
                                </div>
                                <input
                                    name="password"
                                    type="password"
                                    required
                                    value={formData.password}
                                    onChange={handleChange}
                                    className="w-full bg-primary/50 text-white border border-gray-700 focus:border-secondary rounded-xl pl-10 px-4 py-3 font-poppins outline-none transition-colors duration-300"
                                    placeholder="Enter your password"
                                />
                            </div>
                        </div>

                        <div className="flex items-center justify-between">
                            <div className="flex items-center">
                                <input id="remember-me" name="remember-me" type="checkbox" className="h-4 w-4 bg-primary border-gray-700 rounded text-secondary focus:ring-secondary" />
                                <label htmlFor="remember-me" className="ml-2 block text-sm text-dimWhite font-poppins">
                                    Remember me
                                </label>
                            </div>

                            <div className="text-sm">
                                <a href="#" className="font-medium text-secondary hover:text-white transition-colors font-poppins">
                                    Forgot your password?
                                </a>
                            </div>
                        </div>

                        <div>
                            <button
                                type="submit"
                                disabled={loading}
                                className={`w-full flex justify-center py-3 px-4 border border-transparent rounded-xl shadow-sm text-sm font-poppins font-semibold text-primary bg-blue-gradient hover:-translate-y-1 hover:shadow-[0_0_20px_rgba(51,187,207,0.4)] transition-all duration-300 ${loading ? 'opacity-80 cursor-wait' : ''}`}
                            >
                                {loading ? (
                                    <div className="w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin" />
                                ) : (
                                    'Sign in'
                                )}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    );
};

export default Login;
