const express = require('express');
const router = express.Router();
const { addClient, isAuthorizedClient, isAdminInDb } = require('../database');
const { sendOtpEmail, sendAccessDeniedEmail } = require('../services/email');

// Validation helpers
function validateEmail(email) {
    const pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return pattern.test(email);
}

function validatePhone(phone) {
    const cleaned = phone.replace(/[\s\-\(\)]/g, '');
    return cleaned.length >= 8 && cleaned.length <= 15 && /^\d+$/.test(cleaned);
}

// Generate OTP
function generateOtp() {
    return Math.floor(100000 + Math.random() * 900000).toString();
}

// Login page
router.get('/', (req, res) => {
    // Redirect if already authenticated
    if (req.session.authenticated) {
        if (req.session.is_admin) {
            return res.redirect('/admin');
        }
        return res.redirect('/dashboard');
    }

    res.render('login', {
        show_otp_section: req.session.otp_sent || false,
        identifier: req.session.identifier || ''
    });
});

// Handle login POST
// Handle login POST
router.post('/', async (req, res) => {
    try {
        // SCENARIO 1: Email Submission (Requesting OTP)
        if (req.body.identifier) {
            const identifier = req.body.identifier.trim().toLowerCase();

            if (!identifier.includes('@')) {
                req.flash('Please enter a valid email address', 'warning');
                return res.render('login', {
                    show_otp_section: false,
                    identifier: identifier
                });
            }

            req.session.identifier = identifier;
            const otp = generateOtp();
            req.session.otp = otp;
            req.session.otp_sent = true;

            // Check user type
            if (isAdminInDb(identifier)) {
                req.session.user_type = 'admin';
                try {
                    await sendOtpEmail(identifier, otp);
                    req.flash('Admin OTP sent! Please enter it below.', 'success');
                } catch (err) {
                    console.error('Error sending OTP:', err);
                    req.flash(`Error sending OTP: ${err.message}`, 'danger');
                    req.session.otp_sent = false;
                }
            } else if (isAuthorizedClient(identifier)) {
                req.session.user_type = 'client';
                try {
                    await sendOtpEmail(identifier, otp);
                    req.flash('Client OTP sent! Please enter it below.', 'success');
                } catch (err) {
                    console.error('Error sending OTP:', err);
                    req.flash(`Error sending OTP: ${err.message}`, 'danger');
                    req.session.otp_sent = false;
                }
            } else {
                try {
                    await sendAccessDeniedEmail(identifier);
                    req.flash('Access denied. An email notification has been sent.', 'danger');
                } catch (err) {
                    req.flash('Access denied.', 'danger');
                }
                req.session.otp_sent = false;
                delete req.session.identifier;
            }

            // Save session before rendering to ensure OTP is stored
            return req.session.save((err) => {
                if (err) console.error('Session save error (OTP):', err);
                res.render('login', {
                    show_otp_section: req.session.otp_sent,
                    identifier: req.session.identifier || ''
                });
            });
        }

        // SCENARIO 2: OTP Submission (Verifying)
        if (req.body.otp) {
            const enteredOtp = req.body.otp.trim();

            // CRITICAL FIX: Check if session still has the OTP (it might have expired or been lost)
            if (!req.session.otp || !req.session.identifier) {
                console.error('Login failed: Session expired or invalid state.');
                req.flash('Session expired. Please request a new OTP.', 'warning');
                return res.render('login', {
                    show_otp_section: false,
                    identifier: ''
                });
            }

            const storedOtp = req.session.otp;

            console.log('=== OTP VERIFICATION ===');
            console.log('Entered OTP:', enteredOtp);
            console.log('Stored OTP:', storedOtp);
            console.log('Session identifier:', req.session.identifier);

            if (enteredOtp === storedOtp) {
                const email = req.session.identifier;

                // Clear temporary session data
                delete req.session.otp;
                delete req.session.otp_sent;
                delete req.session.user_type;

                // Set authenticated session
                req.session.authenticated = true;
                req.session.user_email = email;
                req.session.is_admin = isAdminInDb(email);

                console.log('=== LOGIN SUCCESS ===');
                console.log('User:', email);
                console.log('Redirecting to:', req.session.is_admin ? '/admin' : '/dashboard');

                // EXPLICIT SAVE before redirect to prevent race conditions
                return req.session.save((err) => {
                    if (err) {
                        console.error('Session save error (Login):', err);
                        req.flash('Login session error. Please try again.', 'danger');
                        return res.render('login', { show_otp_section: false, identifier: '' });
                    }

                    // Redirect based on user type
                    if (req.session.is_admin) {
                        return res.redirect('/admin');
                    } else {
                        return res.redirect('/dashboard');
                    }
                });
            } else {
                console.log('=== OTP MISMATCH ===');
                req.flash('Invalid OTP. Please try again.', 'danger');
                return res.render('login', {
                    show_otp_section: true,
                    identifier: req.session.identifier || ''
                });
            }
        }

        // Fallback if neither identifier nor otp is present
        res.render('login', {
            show_otp_section: false,
            identifier: ''
        });

    } catch (err) {
        console.error('Login error:', err);
        req.flash('An error occurred. Please try again.', 'danger');
        res.render('login', {
            show_otp_section: false,
            identifier: ''
        });
    }
});

// Register page
router.get('/register', (req, res) => {
    res.render('register', { request: { form: {} } });
});

// Handle registration
// Handle registration
router.post('/register', (req, res) => {
    try {
        console.log('Processing registration:', req.body.email);
        const { email, client_name, phone, address, company } = req.body;
        const errors = [];

        // Validation
        if (!email) {
            errors.push('Email is required');
        } else if (!validateEmail(email)) {
            errors.push('Please enter a valid email address');
        }

        if (!client_name) {
            errors.push('Full name is required');
        } else if (client_name.length < 2) {
            errors.push('Name must be at least 2 characters long');
        }

        if (!phone) {
            errors.push('Phone number is required');
        } else if (!validatePhone(phone)) {
            errors.push('Please enter a valid phone number');
        }

        // Show errors if any
        if (errors.length > 0) {
            console.log('Registration validation errors:', errors);
            errors.forEach(error => req.flash(error, 'error'));
            return res.render('register', { request: { form: req.body } });
        }

        // Try to add client
        const success = addClient(email, client_name, phone, address || '', company || '');

        if (success) {
            console.log('Registration successful for:', email);
            req.flash('Registration successful! You can now log in.', 'success');
            return res.redirect('/');
        } else {
            console.log('Registration failed: Email likely exists');
            req.flash('An account with this email already exists. Please try logging in instead.', 'error');
            return res.render('register', { request: { form: req.body } });
        }
    } catch (err) {
        console.error('Registration error:', err);
        req.flash('An internal error occurred during registration. Please try again.', 'error');
        return res.render('register', { request: { form: req.body } });
    }
});

// Logout
router.get('/logout', (req, res) => {
    req.session.destroy((err) => {
        if (err) {
            console.error('Logout error:', err);
        }
        res.redirect('/');
    });
});

module.exports = router;
