import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useConvex } from 'convex/react';
import { usePlatform } from '../platform';
import { useSearch } from '../contexts/SearchContext';
import { api } from '../../../../convex/_generated/api';

const Login = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();
    const convex = useConvex();
    const { crypto, session } = usePlatform();
    const searchCtx = useSearch();

    async function decryptEncryptedField(encryptedJson, keyHex) {
        const obj = JSON.parse(encryptedJson);
        return crypto.decryptData(obj.content, keyHex, obj.iv, obj.tag);
    }

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

        try {
            console.log('Starting login for:', username);

            const { salt } = await convex.query(api.auth.getSalt, { username });
            console.log('Got salt');

            const { dek, dak } = await crypto.deriveAuthKeys(password, salt);
            console.log('Derived keys');

            // Derive a separate key for the local search database
            const searchKeys = await crypto.deriveAuthKeys(password, 'searchdb-' + username);
            sessionStorage.setItem('searchDbKey', searchKeys.dak);

            const verifyData = await convex.mutation(api.auth.verifyUser, { username, dak });

            if (verifyData.error) {
                throw new Error(verifyData.error);
            }

            console.log('Login verified. Response data:', verifyData);

            if (verifyData.userId) {
                console.log('Saving userId to localStorage:', verifyData.userId);
                localStorage.setItem('userId', verifyData.userId);
            } else {
                console.error('MISSING USERID IN VERIFY RESPONSE!', verifyData);
            }

            console.log('Decrypting Master Key...');
            const mkHex = await decryptEncryptedField(verifyData.encryptedMK, dek);

            console.log('Decrypting Private Keys...');
            const encryptedPrivateKeysObj = JSON.parse(verifyData.encryptedPrivateKeys);

            const signingKey = await decryptEncryptedField(JSON.stringify(encryptedPrivateKeysObj.ed), mkHex);
            const rsaPriv = await decryptEncryptedField(JSON.stringify(encryptedPrivateKeysObj.rsa), mkHex);

            sessionStorage.setItem('signingKey', signingKey);
            sessionStorage.setItem('privateKey', rsaPriv);
            console.log('Keys decrypted and stored in session.');

            localStorage.setItem('username', username);
            if (verifyData.publicKey) {
                localStorage.setItem('publicKey', verifyData.publicKey);
            }

            // Persist session via safeStorage for auto-login on restart
            if (session) {
                try {
                    await session.save({
                        userId: verifyData.userId,
                        username,
                        publicKey: verifyData.publicKey || '',
                        signingKey,
                        privateKey: rsaPriv,
                        searchDbKey: searchKeys.dak,
                        savedAt: Date.now(),
                    });
                } catch (e) {
                    console.warn('Session persistence unavailable:', e);
                }
            }

            console.log('Immediate localStorage read check:', localStorage.getItem('userId'));

            searchCtx?.initialize();
            navigate('/chat');
        } catch (err) {
            console.error('Login error:', err);
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="auth-container">
            <div className="auth-box">
                <div className="auth-header">
                    <h2>Welcome Back!</h2>
                    <p>We're so excited to see you again!</p>
                </div>
                {error && <div style={{ color: 'red', marginBottom: 10, textAlign: 'center' }}>{error}</div>}
                <form onSubmit={handleLogin}>
                    <div className="form-group">
                        <label>Username</label>
                        <input
                            type="text"
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                            required
                            disabled={loading}
                        />
                    </div>
                    <div className="form-group">
                        <label>Password</label>
                        <input
                            type="password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            required
                            disabled={loading}
                        />
                    </div>
                    <button type="submit" className="auth-button" disabled={loading}>
                        {loading ? 'Logging in...' : 'Log In'}
                    </button>
                </form>
                <div className="auth-footer">
                    Need an account? <Link to="/register">Register</Link>
                </div>
            </div>
        </div>
    );
};

export default Login;
