import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { Lock, Mail, AlertCircle, CheckCircle, Loader2, ArrowLeft, Eye, EyeOff, TrendingUp, DollarSign, Users, BarChart3 } from 'lucide-react';
import settingsService from '../services/settingsService';
import { clsx } from 'clsx';

const Login = () => {
    const [view, setView] = useState('login'); // login | forgot | reset
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [rememberMe, setRememberMe] = useState(false);
    const [showPassword, setShowPassword] = useState(false);
    const [identity, setIdentity] = useState('');
    const [otp, setOtp] = useState('');
    const [token, setToken] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [error, setError] = useState('');
    const [message, setMessage] = useState('');
    const [loading, setLoading] = useState(false);
    const [companyName, setCompanyName] = useState('FinancePro');
    const [companyLogo, setCompanyLogo] = useState(null);

    const { login, requestReset, verifyReset } = useAuth();
    const navigate = useNavigate();

    useEffect(() => {
        const fetchBranding = async () => {
            try {
                const res = await settingsService.getPublicBranding();
                setCompanyName(res.data.COMPANY_NAME || 'FinancePro');
                setCompanyLogo(res.data.COMPANY_LOGO || null);
            } catch (err) {
                console.error('Failed to fetch branding:', err);
            }
        };
        fetchBranding();

        const params = new URLSearchParams(window.location.search);
        const resetToken = params.get('token');
        if (resetToken) {
            setToken(resetToken);
            setView('reset');
        }
    }, []);

    const handleLogin = async (e) => {
        e.preventDefault();
        setError('');
        setLoading(true);
        try {
            await login(email, password);
            navigate('/dashboard');
        } catch (err) {
            setError(err.response?.data?.message || 'Login failed. Please check credentials.');
        } finally {
            setLoading(false);
        }
    };

    const handleRequestReset = async (e) => {
        e.preventDefault();
        setError('');
        setMessage('');
        setLoading(true);
        try {
            const res = await requestReset(identity);
            setMessage(res.data.message);
            if (!identity.includes('@')) {
                setView('reset');
            }
        } catch (err) {
            setError(err.response?.data?.message || 'Failed to request reset');
        } finally {
            setLoading(false);
        }
    };

    const handleVerifyReset = async (e) => {
        e.preventDefault();
        setError('');
        setLoading(true);
        try {
            await verifyReset({ identity, token, otp, newPassword });
            setMessage('Password updated. Verification successful.');
            setView('login');
            setIdentity('');
            setOtp('');
            setToken('');
            setNewPassword('');
        } catch (err) {
            setError(err.response?.data?.message || 'Verification failed. Error detected.');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="min-h-screen bg-slate-50 dark:bg-slate-900 flex">
            {/* Left Panel - Login Form */}
            <div className="w-full lg:w-1/2 flex items-center justify-center p-6 sm:p-12">
                <div className="w-full max-w-md">
                    {view === 'login' ? (
                        <div className="animate-in fade-in duration-500">
                            {/* Logo */}
                            <div className="mb-8">
                                {companyLogo ? (
                                    <img
                                        src={companyLogo.startsWith('http') ? companyLogo : `http://localhost:5000${companyLogo}`}
                                        alt={companyName}
                                        className="h-12 w-auto object-contain"
                                    />
                                ) : (
                                    <div className="flex items-center gap-3">
                                        <div className="w-10 h-10 bg-primary rounded-lg flex items-center justify-center">
                                            <DollarSign className="w-6 h-6 text-white" />
                                        </div>
                                        <span className="text-2xl font-bold text-slate-900 dark:text-white">{companyName}</span>
                                    </div>
                                )}
                            </div>

                            {/* Title */}
                            <div className="mb-8">
                                <h1 className="text-3xl font-bold text-slate-900 dark:text-white mb-2">Sign in to {companyName}</h1>
                                <p className="text-slate-600 dark:text-slate-400 text-sm">Track income, manage expenses, and grow your business</p>
                            </div>

                            {/* Error Message */}
                            {error && (
                                <div className="mb-6 p-4 bg-rose-50 dark:bg-rose-500/10 border border-rose-200 dark:border-rose-500/20 text-rose-600 dark:text-rose-400 rounded-xl flex items-start gap-3 text-sm">
                                    <AlertCircle className="w-5 h-5 shrink-0 mt-0.5" />
                                    <span>{error}</span>
                                </div>
                            )}

                            {/* Success Message */}
                            {message && (
                                <div className="mb-6 p-4 bg-emerald-50 dark:bg-emerald-500/10 border border-emerald-200 dark:border-emerald-500/20 text-emerald-600 dark:text-emerald-400 rounded-xl flex items-start gap-3 text-sm">
                                    <CheckCircle className="w-5 h-5 shrink-0 mt-0.5" />
                                    <span>{message}</span>
                                </div>
                            )}

                            {/* Login Form */}
                            <form onSubmit={handleLogin} className="space-y-5">
                                {/* Email Field */}
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                                        Email
                                    </label>
                                    <div className="relative">
                                        <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                                        <input
                                            type="email"
                                            required
                                            placeholder="name@company.com"
                                            className="w-full pl-11 pr-4 py-3 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl text-slate-900 dark:text-white placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
                                            value={email}
                                            onChange={(e) => setEmail(e.target.value)}
                                        />
                                    </div>
                                </div>

                                {/* Password Field */}
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                                        Password
                                    </label>
                                    <div className="relative">
                                        <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                                        <input
                                            type={showPassword ? "text" : "password"}
                                            required
                                            placeholder="••••••••"
                                            className="w-full pl-11 pr-11 py-3 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl text-slate-900 dark:text-white placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
                                            value={password}
                                            onChange={(e) => setPassword(e.target.value)}
                                        />
                                        <button
                                            type="button"
                                            onClick={() => setShowPassword(!showPassword)}
                                            className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors"
                                        >
                                            {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                                        </button>
                                    </div>
                                </div>

                                {/* Remember Me & Forgot Password */}
                                <div className="flex items-center justify-between">
                                    <label className="flex items-center gap-2 cursor-pointer group">
                                        <input
                                            type="checkbox"
                                            checked={rememberMe}
                                            onChange={(e) => setRememberMe(e.target.checked)}
                                            className="w-4 h-4 rounded border-slate-300 dark:border-slate-600 text-primary focus:ring-2 focus:ring-primary focus:ring-offset-0 cursor-pointer"
                                        />
                                        <span className="text-sm text-slate-600 dark:text-slate-400 group-hover:text-slate-900 dark:group-hover:text-slate-200 transition-colors">
                                            Remember me
                                        </span>
                                    </label>
                                    <button
                                        type="button"
                                        onClick={() => setView('forgot')}
                                        className="text-sm font-medium text-primary hover:text-primary/80 transition-colors"
                                    >
                                        Forgot Password?
                                    </button>
                                </div>

                                {/* Sign In Button */}
                                <button
                                    type="submit"
                                    disabled={loading}
                                    className="w-full bg-primary hover:bg-primary/90 disabled:bg-slate-300 dark:disabled:bg-slate-700 disabled:cursor-not-allowed text-white font-semibold py-3 px-4 rounded-xl transition-all duration-200 flex items-center justify-center gap-2 shadow-lg shadow-primary/20 hover:shadow-xl hover:shadow-primary/30"
                                >
                                    {loading ? (
                                        <>
                                            <Loader2 className="w-5 h-5 animate-spin" />
                                            <span>Signing in...</span>
                                        </>
                                    ) : (
                                        <span>Sign In</span>
                                    )}
                                </button>
                            </form>

                            {/* Footer */}
                            <div className="mt-8 pt-6 border-t border-slate-200 dark:border-slate-700">
                                <p className="text-xs text-slate-500 dark:text-slate-400 text-center">
                                    © {new Date().getFullYear()} {companyName}. All rights reserved.
                                </p>
                            </div>
                        </div>
                    ) : view === 'forgot' ? (
                        <div className="animate-in fade-in duration-500">
                            {/* Back Button */}
                            <button
                                onClick={() => setView('login')}
                                className="flex items-center gap-2 text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white font-medium text-sm mb-8 transition-colors"
                            >
                                <ArrowLeft className="w-4 h-4" />
                                Back to Sign In
                            </button>

                            {/* Title */}
                            <div className="mb-8">
                                <h1 className="text-3xl font-bold text-slate-900 dark:text-white mb-2">Forgot Password?</h1>
                                <p className="text-slate-600 dark:text-slate-400 text-sm">Enter your email or phone number and we'll send you a reset code</p>
                            </div>

                            {/* Error Message */}
                            {error && (
                                <div className="mb-6 p-4 bg-rose-50 dark:bg-rose-500/10 border border-rose-200 dark:border-rose-500/20 text-rose-600 dark:text-rose-400 rounded-xl flex items-start gap-3 text-sm">
                                    <AlertCircle className="w-5 h-5 shrink-0 mt-0.5" />
                                    <span>{error}</span>
                                </div>
                            )}

                            {/* Success Message */}
                            {message && (
                                <div className="mb-6 p-4 bg-emerald-50 dark:bg-emerald-500/10 border border-emerald-200 dark:border-emerald-500/20 text-emerald-600 dark:text-emerald-400 rounded-xl flex items-start gap-3 text-sm">
                                    <CheckCircle className="w-5 h-5 shrink-0 mt-0.5" />
                                    <span>{message}</span>
                                </div>
                            )}

                            {/* Reset Form */}
                            <form onSubmit={handleRequestReset} className="space-y-5">
                                <div>
                                    <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                                        Email or Phone Number
                                    </label>
                                    <input
                                        type="text"
                                        required
                                        placeholder="name@company.com or +254..."
                                        className="w-full px-4 py-3 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl text-slate-900 dark:text-white placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
                                        value={identity}
                                        onChange={(e) => setIdentity(e.target.value)}
                                    />
                                </div>

                                <button
                                    type="submit"
                                    disabled={loading}
                                    className="w-full bg-primary hover:bg-primary/90 disabled:bg-slate-300 dark:disabled:bg-slate-700 disabled:cursor-not-allowed text-white font-semibold py-3 px-4 rounded-xl transition-all duration-200 flex items-center justify-center gap-2 shadow-lg shadow-primary/20"
                                >
                                    {loading ? (
                                        <>
                                            <Loader2 className="w-5 h-5 animate-spin" />
                                            <span>Sending...</span>
                                        </>
                                    ) : (
                                        <span>Send Reset Code</span>
                                    )}
                                </button>
                            </form>
                        </div>
                    ) : (
                        <div className="animate-in fade-in duration-500">
                            {/* Title */}
                            <div className="mb-8">
                                <h1 className="text-3xl font-bold text-slate-900 dark:text-white mb-2">Reset Password</h1>
                                <p className="text-slate-600 dark:text-slate-400 text-sm">
                                    {token ? 'Enter your new password below' : 'Enter the verification code sent to you'}
                                </p>
                            </div>

                            {/* Error Message */}
                            {error && (
                                <div className="mb-6 p-4 bg-rose-50 dark:bg-rose-500/10 border border-rose-200 dark:border-rose-500/20 text-rose-600 dark:text-rose-400 rounded-xl flex items-start gap-3 text-sm">
                                    <AlertCircle className="w-5 h-5 shrink-0 mt-0.5" />
                                    <span>{error}</span>
                                </div>
                            )}

                            {/* Reset Form */}
                            <form onSubmit={handleVerifyReset} className="space-y-5">
                                {!token && (
                                    <div>
                                        <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                                            Verification Code
                                        </label>
                                        <input
                                            type="text"
                                            required
                                            placeholder="000000"
                                            maxLength="6"
                                            className="w-full px-4 py-3 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl text-slate-900 dark:text-white placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all text-center text-2xl tracking-widest font-bold"
                                            value={otp}
                                            onChange={(e) => setOtp(e.target.value)}
                                        />
                                    </div>
                                )}

                                <div>
                                    <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                                        New Password
                                    </label>
                                    <input
                                        type="password"
                                        required
                                        placeholder="Minimum 12 characters"
                                        className="w-full px-4 py-3 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl text-slate-900 dark:text-white placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
                                        value={newPassword}
                                        onChange={(e) => setNewPassword(e.target.value)}
                                    />
                                </div>

                                <button
                                    type="submit"
                                    disabled={loading}
                                    className="w-full bg-primary hover:bg-primary/90 disabled:bg-slate-300 dark:disabled:bg-slate-700 disabled:cursor-not-allowed text-white font-semibold py-3 px-4 rounded-xl transition-all duration-200 flex items-center justify-center gap-2 shadow-lg shadow-primary/20"
                                >
                                    {loading ? (
                                        <>
                                            <Loader2 className="w-5 h-5 animate-spin" />
                                            <span>Updating...</span>
                                        </>
                                    ) : (
                                        <span>Update Password</span>
                                    )}
                                </button>
                            </form>
                        </div>
                    )}
                </div>
            </div>

            {/* Right Panel - Branded Marketing */}
            <div className="hidden lg:flex lg:w-1/2 bg-primary relative overflow-hidden items-center justify-center p-12">
                {/* Background Pattern */}
                <div className="absolute inset-0 opacity-10">
                    <div className="absolute top-0 right-0 w-96 h-96 bg-white rounded-full blur-3xl -translate-y-1/2 translate-x-1/2"></div>
                    <div className="absolute bottom-0 left-0 w-96 h-96 bg-white rounded-full blur-3xl translate-y-1/2 -translate-x-1/2"></div>
                </div>

                {/* Content */}
                <div className="relative z-10 max-w-lg text-white">
                    {/* Decorative Cards */}
                    <div className="mb-12 relative">
                        <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6 border border-white/20 shadow-2xl">
                            <div className="flex items-center justify-between mb-4">
                                <div>
                                    <p className="text-white/70 text-sm font-medium mb-1">Total Revenue</p>
                                    <p className="text-3xl font-bold">KES 56,476.00</p>
                                </div>
                                <div className="w-12 h-12 bg-emerald-500/20 rounded-xl flex items-center justify-center">
                                    <TrendingUp className="w-6 h-6 text-emerald-400" />
                                </div>
                            </div>
                            <div className="flex items-center gap-2 text-sm">
                                <span className="text-emerald-400 font-semibold">+12.5%</span>
                                <span className="text-white/60">from last month</span>
                            </div>
                        </div>

                        {/* Mini Cards */}
                        <div className="grid grid-cols-2 gap-4 mt-4">
                            <div className="bg-white/10 backdrop-blur-sm rounded-xl p-4 border border-white/20">
                                <div className="flex items-center gap-3">
                                    <div className="w-10 h-10 bg-blue-500/20 rounded-lg flex items-center justify-center">
                                        <BarChart3 className="w-5 h-5 text-blue-400" />
                                    </div>
                                    <div>
                                        <p className="text-white/70 text-xs">Expenses</p>
                                        <p className="text-lg font-bold">KES 23,241</p>
                                    </div>
                                </div>
                            </div>
                            <div className="bg-white/10 backdrop-blur-sm rounded-xl p-4 border border-white/20">
                                <div className="flex items-center gap-3">
                                    <div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                                        <Users className="w-5 h-5 text-purple-400" />
                                    </div>
                                    <div>
                                        <p className="text-white/70 text-xs">Clients</p>
                                        <p className="text-lg font-bold">142</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Marketing Text */}
                    <div className="space-y-4">
                        <h2 className="text-4xl font-bold leading-tight">
                            Get better with money
                        </h2>
                        <p className="text-white/80 text-lg leading-relaxed">
                            FinancePro by Delight Office Solutions helps you track income, manage expenses, and grow your business.
                            Get real-time insights and make smarter financial decisions.
                        </p>
                    </div>

                    {/* Pagination Dots */}
                    <div className="flex items-center gap-2 mt-8">
                        <div className="w-2 h-2 bg-white rounded-full"></div>
                        <div className="w-2 h-2 bg-white/30 rounded-full"></div>
                        <div className="w-2 h-2 bg-white/30 rounded-full"></div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Login;
