import { useState } from 'react';
import { Logout, StorePasswordForSession, VerifyPassword } from '../../wailsjs/go/app/Application';

function PasswordPrompt({ email, onPasswordVerified }) {
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);

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

        if (!password) {
            setError('Please enter your password');
            setLoading(false);
            return;
        }

        try {
            // Verify password against stored encrypted data
            const isValid = await VerifyPassword(password);

            if (!isValid) {
                setError('Incorrect password. Please try again.');
                setLoading(false);
                return;
            }

            // Store password in RAM
            await StorePasswordForSession(password);

            // Notify parent component
            await onPasswordVerified(password);

            // Success - parent will handle navigation
        } catch (err) {
            console.error('Password verification error:', err);
            setError('Failed to verify password: ' + err.message);
            setLoading(false);
        }
    };

    const handleLogout = async () => {
        try {
            await Logout();
            window.location.reload();
        } catch (error) {
            console.error('Logout failed:', error);
        }
    };

    return (
        <div style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100vh',
            background: '#f8f9fa'
        }}>
            <div style={{
                background: 'white',
                padding: '40px',
                borderRadius: '10px',
                boxShadow: '0 2px 10px rgba(0,0,0,0.1)',
                maxWidth: '450px',
                width: '100%'
            }}>
                <h2 style={{ marginTop: 0 }}>Welcome Back</h2>
                <p style={{ color: '#666', marginBottom: '30px' }}>
                    Enter your password to unlock your encrypted files
                </p>

                <form onSubmit={handleSubmit}>
                    <div style={{ marginBottom: '20px' }}>
                        <label style={{ display: 'block', marginBottom: '5px' }}>Email</label>
                        <input
                            type="text"
                            value={email}
                            disabled
                            style={{
                                width: '100%',
                                padding: '10px',
                                background: '#f5f5f5',
                                border: '1px solid #ddd',
                                borderRadius: '5px'
                            }}
                        />
                    </div>

                    <div style={{ marginBottom: '20px' }}>
                        <label htmlFor="password" style={{ display: 'block', marginBottom: '5px' }}>
                            Password
                        </label>
                        <input
                            type="password"
                            id="password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            placeholder="Enter your password"
                            autoFocus
                            disabled={loading}
                            style={{
                                width: '100%',
                                padding: '10px',
                                border: '1px solid #ddd',
                                borderRadius: '5px'
                            }}
                        />
                        <small style={{ color: '#666', fontSize: '0.9em' }}>
                            Your password will be kept in memory until you close the app.
                        </small>
                    </div>

                    {error && (
                        <div style={{
                            padding: '10px',
                            marginBottom: '15px',
                            background: '#f8d7da',
                            border: '1px solid #f5c6cb',
                            borderRadius: '5px',
                            color: '#721c24'
                        }}>
                            {error}
                        </div>
                    )}

                    <div style={{ display: 'flex', gap: '10px' }}>
                        <button
                            type="submit"
                            disabled={loading}
                            style={{
                                flex: 1,
                                padding: '12px',
                                background: loading ? '#6c757d' : '#007bff',
                                color: 'white',
                                border: 'none',
                                borderRadius: '5px',
                                cursor: loading ? 'not-allowed' : 'pointer',
                                fontSize: '16px'
                            }}
                        >
                            {loading ? 'Verifying...' : 'Unlock'}
                        </button>
                        <button
                            type="button"
                            onClick={handleLogout}
                            disabled={loading}
                            style={{
                                padding: '12px 20px',
                                background: 'white',
                                color: '#dc3545',
                                border: '1px solid #dc3545',
                                borderRadius: '5px',
                                cursor: loading ? 'not-allowed' : 'pointer'
                            }}
                        >
                            Logout
                        </button>
                    </div>
                </form>

                <div style={{
                    marginTop: '20px',
                    padding: '10px',
                    background: '#d1ecf1',
                    border: '1px solid #bee5eb',
                    borderRadius: '5px',
                    fontSize: '0.9em',
                    color: '#0c5460'
                }}>
                    <strong>🔒 Security:</strong> Your password is stored securely in memory
                    and will be automatically cleared when you close the app.
                </div>
            </div>
        </div>
    );
}

export default PasswordPrompt;
