import { useState, useEffect } from 'react';
import api from '../api';
import { Car, ArrowLeft } from 'lucide-react';

const ForgotPassword = ({ onBackToLogin }) => {
    console.log('✅✅✅ ForgotPassword component rendered!');
    console.log('onBackToLogin:', typeof onBackToLogin);

    const [email, setEmail] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [step, setStep] = useState('request');
    const [error, setError] = useState('');
    const [success, setSuccess] = useState('');
    const [loading, setLoading] = useState(false);
    const [resetToken, setResetToken] = useState('');

    useEffect(() => {
        console.log('🔄 ForgotPassword useEffect running');
        const params = new URLSearchParams(window.location.search);
        const token = params.get('token');
        console.log('🔑 Token from URL:', token);
        if (token) {
            setResetToken(token);
            setStep('reset');
            console.log('🔄 Step changed to reset');
        }
    }, []);

    const handleRequestReset = async (e) => {
        console.log('🚀🚀🚀 handleRequestReset CALLED!');
        console.log('Event:', e);

        e.preventDefault();
        console.log('📧 Form submitted!');
        console.log('📧 Email:', email);

        setLoading(true);
        setError('');
        setSuccess('');

        try {
            console.log('📧 Making API call to /auth/forgot-password');
            const res = await api.post('/auth/forgot-password', { email });
            console.log('📧 API Response:', res.data);

            if (res.data.success) {
                console.log('✅ Success!');
                setSuccess('✅ Password reset link sent to your email! Please check your inbox.');
                setEmail('');
                setTimeout(() => {
                    console.log('⏰ Redirecting to login...');
                    onBackToLogin();
                }, 5000);
            } else {
                console.log('❌ API returned success: false');
                setError(res.data.message || 'Failed to send reset link');
            }
        } catch (err) {
            console.error('❌❌❌ API Error:', err);
            console.error('Error response:', err.response?.data);
            console.error('Error message:', err.message);

            if (err.response?.data?.message) {
                setError(err.response.data.message);
            } else if (err.message) {
                setError(err.message);
            } else {
                setError('Failed to send reset link. Please try again.');
            }
        } finally {
            setLoading(false);
        }
    };

    const handleResetPassword = async (e) => {
        e.preventDefault();
        console.log('🔐 Reset password form submitted');

        if (newPassword !== confirmPassword) {
            setError('Passwords do not match');
            return;
        }

        if (newPassword.length < 6) {
            setError('Password must be at least 6 characters long');
            return;
        }

        setLoading(true);
        setError('');
        setSuccess('');

        try {
            const res = await api.post('/auth/reset-password', {
                token: resetToken,
                newPassword
            });

            if (res.data.success) {
                setSuccess('✅ Password has been reset successfully! Redirecting to login...');
                setTimeout(() => {
                    onBackToLogin();
                }, 2000);
            } else {
                setError(res.data.message || 'Failed to reset password');
            }
        } catch (err) {
            setError(err.response?.data?.message || 'Failed to reset password. Please try again.');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="login-page-container">
            <style>{`
                .login-page-container {
                    background-color: #f8fafc !important;
                    min-height: 100vh;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    font-family: 'Inter', sans-serif;
                    width: 100%;
                }
                .login-card {
                    background: #ffffff !important;
                    border-radius: 16px !important;
                    border: none !important;
                    box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.05) !important;
                    width: 100%;
                    max-width: 440px;
                    padding: 40px !important;
                    text-align: center;
                    position: relative;
                }
                .login-logo-circle {
                    display: inline-flex;
                    align-items: center;
                    justify-content: center;
                    width: 64px;
                    height: 64px;
                    background-color: #e8f0fe !important;
                    border-radius: 50% !important;
                    margin-bottom: 24px;
                    color: #1a73e8 !important;
                }
                .login-title {
                    font-size: 24px;
                    font-weight: 700;
                    color: #1e293b !important;
                    margin-bottom: 6px;
                }
                .login-subtitle {
                    font-size: 13px;
                    color: #64748b !important;
                    margin-bottom: 0px;
                }
                .login-field-group {
                    margin-bottom: 20px;
                    text-align: left;
                }
                .login-label {
                    font-size: 13px;
                    font-weight: 600;
                    color: #475569 !important;
                    margin-bottom: 6px;
                    display: block;
                }
                .login-input {
                    background-color: #ffffff !important;
                    border: 1px solid #e2e8f0 !important;
                    color: #1e293b !important;
                    font-size: 14px !important;
                    padding: 10px 14px !important;
                    border-radius: 8px !important;
                    width: 100% !important;
                    margin-bottom: 0px !important;
                    height: auto !important;
                    box-shadow: none !important;
                    transition: border-color 0.2s, box-shadow 0.2s;
                }
                .login-input:focus {
                    border-color: #1a73e8 !important;
                    outline: none !important;
                    box-shadow: 0 0 0 3px rgba(26, 115, 232, 0.15) !important;
                }
                .login-input::placeholder {
                    color: #94a3b8 !important;
                }
                .login-btn {
                    background-color: #1a73e8 !important;
                    border: none !important;
                    color: #ffffff !important;
                    font-weight: 600 !important;
                    font-size: 14px !important;
                    padding: 12px 24px !important;
                    border-radius: 8px !important;
                    width: 100% !important;
                    transition: background-color 0.2s;
                    margin-top: 8px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                .login-btn:hover {
                    background-color: #1557b0 !important;
                }
                .login-btn:disabled {
                    background-color: #bfdbfe !important;
                }
                .error-message {
                    color: #dc2626;
                    background: #fee2e2;
                    padding: 10px;
                    border-radius: 8px;
                    margin-bottom: 16px;
                    font-size: 14px;
                }
                .success-message {
                    color: #16a34a;
                    background: #dcfce7;
                    padding: 10px;
                    border-radius: 8px;
                    margin-bottom: 16px;
                    font-size: 14px;
                }
                .back-link {
                    color: #64748b;
                    cursor: pointer;
                    font-size: 13px;
                    margin-top: 16px;
                    display: inline-flex;
                    align-items: center;
                    gap: 6px;
                    transition: color 0.2s;
                }
                .back-link:hover {
                    color: #1a73e8;
                }
                .spinner-border {
                    display: inline-block;
                    width: 1rem;
                    height: 1rem;
                    border: 0.2em solid currentColor;
                    border-right-color: transparent;
                    border-radius: 50%;
                    animation: spinner-border 0.75s linear infinite;
                }
                @keyframes spinner-border {
                    to { transform: rotate(360deg); }
                }
                .me-2 {
                    margin-right: 8px;
                }
                .mb-4 {
                    margin-bottom: 24px;
                }
            `}</style>

            <div className="login-card">
                <div className="login-logo-circle">
                    <Car size={32} />
                </div>

                {step === 'request' ? (
                    <>
                        <h2 className="login-title">Forgot Password</h2>
                        <p className="login-subtitle mb-4">
                            Enter your email to receive a password reset link
                        </p>

                        {error && <div className="error-message">❌ {error}</div>}
                        {success && <div className="success-message">✅ {success}</div>}

                        <form onSubmit={handleRequestReset}>
                            <div className="login-field-group">
                                <label className="login-label">Email Address</label>
                                <input
                                    type="email"
                                    className="login-input"
                                    value={email}
                                    onChange={(e) => {
                                        console.log('✏️ Email changed:', e.target.value);
                                        setEmail(e.target.value);
                                    }}
                                    required
                                    placeholder="Enter your registered email"
                                    disabled={loading}
                                />
                            </div>

                            <button
                                type="submit"
                                className="login-btn"
                                disabled={loading}
                                onClick={() => console.log('🖱️ Submit button clicked!')}
                            >
                                {loading ? (
                                    <>
                                        <span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                                        Sending...
                                    </>
                                ) : (
                                    'Send Reset Link'
                                )}
                            </button>

                            <div
                                className="back-link"
                                onClick={() => {
                                    console.log('🔙 Back to login clicked');
                                    onBackToLogin();
                                }}
                            >
                                <ArrowLeft size={16} />
                                Back to Login
                            </div>
                        </form>
                    </>
                ) : (
                    <>
                        <h2 className="login-title">Set New Password</h2>
                        <p className="login-subtitle mb-4">
                            Create a new password for your account
                        </p>

                        {error && <div className="error-message">❌ {error}</div>}
                        {success && <div className="success-message">✅ {success}</div>}

                        <form onSubmit={handleResetPassword}>
                            <div className="login-field-group">
                                <label className="login-label">New Password</label>
                                <input
                                    type="password"
                                    className="login-input"
                                    value={newPassword}
                                    onChange={(e) => setNewPassword(e.target.value)}
                                    required
                                    placeholder="Enter new password (min 6 characters)"
                                    disabled={loading}
                                />
                            </div>

                            <div className="login-field-group">
                                <label className="login-label">Confirm Password</label>
                                <input
                                    type="password"
                                    className="login-input"
                                    value={confirmPassword}
                                    onChange={(e) => setConfirmPassword(e.target.value)}
                                    required
                                    placeholder="Confirm your new password"
                                    disabled={loading}
                                />
                            </div>

                            <button
                                type="submit"
                                className="login-btn"
                                disabled={loading}
                            >
                                {loading ? (
                                    <>
                                        <span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                                        Resetting...
                                    </>
                                ) : (
                                    'Reset Password'
                                )}
                            </button>

                            <div
                                className="back-link"
                                onClick={() => setStep('request')}
                            >
                                <ArrowLeft size={16} />
                                Back to Request Link
                            </div>
                        </form>
                    </>
                )}
            </div>
        </div>
    );
};

export default ForgotPassword;