const { app, BrowserWindow, dialog, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs').promises;

// Enable MP4 codec support in Electron
app.commandLine.appendSwitch('enable-features', 'VaapiVideoDecoder');
app.commandLine.appendSwitch('use-file-for-fake-video-capture', 'false');
app.commandLine.appendSwitch('enable-experimental-web-platform-features');
app.commandLine.appendSwitch('enable-blink-features', 'MediaRecorder');

let mainWindow;

// Window state management
let windowState = {
    width: 1200,
    height: 800,
    x: undefined,
    y: undefined,
    isMaximized: false
};

// Load saved window state
async function loadWindowState() {
    try {
        const stateFile = path.join(app.getPath('userData'), 'window-state.json');
        const data = await fs.readFile(stateFile, 'utf8');
        const savedState = JSON.parse(data);
        
        // Validate saved state
        if (savedState.width && savedState.height && 
            savedState.width >= 800 && savedState.height >= 600) {
            windowState = { ...windowState, ...savedState };
        }
    } catch (error) {
        // File doesn't exist or is invalid, use defaults
        console.log('Using default window state');
    }
}

// Save window state
async function saveWindowState() {
    try {
        if (mainWindow) {
            const bounds = mainWindow.getBounds();
            const isMaximized = mainWindow.isMaximized();
            
            if (!isMaximized) {
                windowState = { ...bounds, isMaximized: false };
            } else {
                windowState.isMaximized = true;
            }
            
            const stateFile = path.join(app.getPath('userData'), 'window-state.json');
            await fs.writeFile(stateFile, JSON.stringify(windowState, null, 2));
        }
    } catch (error) {
        console.error('Failed to save window state:', error);
    }
}

async function createWindow() {
    // Load saved window state
    await loadWindowState();
    
    mainWindow = new BrowserWindow({
        width: windowState.width,
        height: windowState.height,
        x: windowState.x,
        y: windowState.y,
        minWidth: 800,
        minHeight: 600,
        resizable: true,
        maximizable: true,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            enableRemoteModule: false,
            webSecurity: false,  // Allow requests to localhost
            preload: path.join(__dirname, 'preload.js'),
            // Enable media features for MP4 recording
            allowRunningInsecureContent: true,
            experimentalFeatures: true
        },
        icon: path.join(__dirname, 'assets', 'icon.png'),
        show: false,
        titleBarStyle: 'default'
    });

    mainWindow.loadFile(path.join(__dirname, '..', '..', 'index.html'));
    
    mainWindow.once('ready-to-show', () => {
        if (windowState.isMaximized) {
            mainWindow.maximize();
        }
        mainWindow.show();
    });

    // Save window state when it changes
    mainWindow.on('resize', saveWindowState);
    mainWindow.on('move', saveWindowState);
    mainWindow.on('maximize', saveWindowState);
    mainWindow.on('unmaximize', saveWindowState);
    
    // Save state before closing
    mainWindow.on('close', saveWindowState);
    
    mainWindow.once('ready-to-show', () => {
        mainWindow.show();
    });

    // Open DevTools in development
    if (process.argv.includes('--dev')) {
        mainWindow.webContents.openDevTools();
    }
}

// Register all IPC handlers before app is ready
function registerIpcHandlers() {
    console.log('📝 Registering all IPC handlers...');
    
    // Move the child window handler here for early registration
    // Child window management
    let childWindows = new Map();

    console.log('📝 Registering open-child-window IPC handler...');
    ipcMain.handle('open-child-window', async (event, options) => {
        console.log('🖥️ Child window requested:', options);
        try {
            const { url, windowName, width = 1200, height = 800 } = options;
            
            // Check if window already exists and focus it instead of creating a new one
            if (childWindows.has(windowName)) {
                const existingWindow = childWindows.get(windowName);
                if (!existingWindow.isDestroyed()) {
                    console.log(`Focusing existing window: ${windowName}`);
                    existingWindow.focus();
                    return { success: true, windowName, action: 'focused' };
                } else {
                    // Window was destroyed, remove from map
                    childWindows.delete(windowName);
                }
            }
            
            // Create new child window
            const childWindow = new BrowserWindow({
                width,
                height,
                // Remove parent relationship to prevent focus issues
                modal: false,
                resizable: true,
                minimizable: true,
                maximizable: true,
                webPreferences: {
                    nodeIntegration: false,
                    contextIsolation: true,
                    enableRemoteModule: false,
                    webSecurity: false,
                    preload: path.join(__dirname, 'preload.js'),
                    allowRunningInsecureContent: true,
                    experimentalFeatures: true
                },
                show: true, // Show immediately instead of waiting
                title: `${windowName} - Gooner Training Academy`
            });
            
            // Parse URL to separate file path from query string
            const [filePath, queryString] = url.split('?');
            const fullPath = path.join(__dirname, '..', '..', filePath);
            
            console.log(`Loading child window file: ${fullPath}`);
            if (queryString) {
                console.log(`With query string: ?${queryString}`);
            }
            
            try {
                // Load the file with query string if present
                const loadUrl = queryString ? `${fullPath}?${queryString}` : fullPath;
                await childWindow.loadFile(filePath, queryString ? { search: queryString } : {});
                console.log(`✅ Successfully loaded: ${loadUrl}`);
                childWindow.focus();
            } catch (loadError) {
                console.error(`❌ Failed to load file: ${fullPath}`, loadError);
                // Try to show the window anyway with an error message
                childWindow.show();
                childWindow.focus();
            }
            
            // Handle window closed
            childWindow.on('closed', () => {
                console.log(`Child window closed: ${windowName}`);
                childWindows.delete(windowName);
            });
            
            // Add error handling
            childWindow.on('unresponsive', () => {
                console.warn(`Child window unresponsive: ${windowName}`);
            });
            
            childWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
                console.error(`Child window failed to load: ${windowName}`, {
                    errorCode,
                    errorDescription,
                    validatedURL
                });
            });
            
            // Store reference
            childWindows.set(windowName, childWindow);
            
            console.log(`✅ Created and showing child window: ${windowName} (${url})`);
            return { success: true, windowName, action: 'created' };
            
        } catch (error) {
            console.error('Error creating child window:', error);
            return { success: false, error: error.message };
        }
    });
}

// Add main window focus handler
ipcMain.handle('focus-main-window', async () => {
    if (mainWindow && !mainWindow.isDestroyed()) {
        mainWindow.show();
        mainWindow.focus();
        mainWindow.moveTop();
        return { success: true };
    }
    return { success: false };
});

// Register IPC handlers
registerIpcHandlers();

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

// File system operations for the renderer process
ipcMain.handle('select-images', async () => {
    const result = await dialog.showOpenDialog(mainWindow, {
        properties: ['openFile', 'multiSelections'],
        filters: [
            { name: 'Images', extensions: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'] }
        ]
    });
    
    if (!result.canceled) {
        return result.filePaths;
    }
    return [];
});

ipcMain.handle('select-directory', async () => {
    const result = await dialog.showOpenDialog(mainWindow, {
        properties: ['openDirectory']
    });
    
    if (!result.canceled) {
        return result.filePaths[0];
    }
    return null;
});

ipcMain.handle('read-directory', async (event, dirPath) => {
    try {
        const files = await fs.readdir(dirPath);
        const imageFiles = files.filter(file => {
            const ext = path.extname(file).toLowerCase();
            return ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'].includes(ext);
        });
        
        return imageFiles.map(file => ({
            name: file,
            path: path.join(dirPath, file)
        }));
    } catch (error) {
        console.error('Error reading directory:', error);
        return [];
    }
});

ipcMain.handle('copy-image', async (event, sourcePath, destPath) => {
    try {
        await fs.mkdir(path.dirname(destPath), { recursive: true });
        await fs.copyFile(sourcePath, destPath);
        return true;
    } catch (error) {
        console.error('Error copying image:', error);
        return false;
    }
});

ipcMain.handle('get-app-path', () => {
    return app.getAppPath();
});

ipcMain.handle('path-join', (event, ...paths) => {
    return path.join(...paths);
});

ipcMain.handle('file-exists', async (event, filePath) => {
    try {
        await fs.access(filePath);
        return true;
    } catch {
        return false;
    }
});

ipcMain.handle('create-directory', async (event, dirPath) => {
    try {
        await fs.mkdir(dirPath, { recursive: true });
        return true;
    } catch (error) {
        console.error('Error creating directory:', error);
        return false;
    }
});

ipcMain.handle('delete-file', async (event, filePath) => {
    try {
        await fs.unlink(filePath);
        return true;
    } catch (error) {
        console.error('Error deleting file:', error);
        return false;
    }
});

// Save base64 image to file
ipcMain.handle('save-base64-image', async (event, filePath, base64Data) => {
    try {
        // Ensure the directory exists
        await fs.mkdir(path.dirname(filePath), { recursive: true });
        
        // Convert base64 to buffer and write to file
        const buffer = Buffer.from(base64Data, 'base64');
        await fs.writeFile(filePath, buffer);
        
        console.log(`📸 Saved image: ${filePath}`);
        return true;
    } catch (error) {
        console.error('Error saving base64 image:', error);
        return false;
    }
});

// Audio-specific IPC handlers
ipcMain.handle('select-audio', async () => {
    const result = await dialog.showOpenDialog(mainWindow, {
        properties: ['openFile', 'multiSelections'],
        filters: [
            { name: 'Audio Files', extensions: ['mp3', 'wav', 'ogg', 'm4a', 'aac', 'flac'] }
        ]
    });
    
    if (!result.canceled) {
        return result.filePaths;
    }
    return [];
});

ipcMain.handle('read-audio-directory', async (event, dirPath) => {
    try {
        const files = await fs.readdir(dirPath);
        const audioFiles = files.filter(file => {
            const ext = path.extname(file).toLowerCase();
            return ['.mp3', '.wav', '.ogg', '.m4a', '.aac', '.flac'].includes(ext);
        });
        
        return audioFiles.map(file => ({
            name: file,
            path: path.join(dirPath, file),
            title: file.replace(/\.[^/.]+$/, "").replace(/[-_]/g, ' ').replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase())
        }));
    } catch (error) {
        console.error('Error reading audio directory:', error);
        return [];
    }
});

ipcMain.handle('copy-audio', async (event, sourcePath, destPath) => {
    try {
        await fs.mkdir(path.dirname(destPath), { recursive: true });
        await fs.copyFile(sourcePath, destPath);
        return true;
    } catch (error) {
        console.error('Error copying audio file:', error);
        return false;
    }
});

// Video file operations
ipcMain.handle('select-videos', async () => {
    const result = await dialog.showOpenDialog(mainWindow, {
        properties: ['openFile', 'multiSelections'],
        filters: [
            { name: 'Video Files', extensions: ['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv'] }
        ]
    });
    
    if (!result.canceled) {
        return result.filePaths;
    }
    return [];
});

ipcMain.handle('read-video-directory', async (event, dirPath) => {
    try {
        const files = await fs.readdir(dirPath);
        const videoFiles = files.filter(file => {
            const ext = path.extname(file).toLowerCase();
            return ['.mp4', '.webm', '.ogv', '.mov', '.avi', '.mkv'].includes(ext);
        });
        
        const videoFilePromises = videoFiles.map(async file => {
            const filePath = path.join(dirPath, file);
            const stats = await fs.stat(filePath);
            const ext = path.extname(file).toLowerCase();
            
            // Map file extension to MIME type
            const mimeTypeMap = {
                '.mp4': 'video/mp4',
                '.webm': 'video/webm',
                '.ogv': 'video/ogg',
                '.mov': 'video/quicktime',
                '.avi': 'video/x-msvideo',
                '.mkv': 'video/x-matroska'
            };
            
            return {
                name: file,
                path: filePath,
                url: `file:///${filePath.replace(/\\/g, '/')}`,
                title: file.replace(/\.[^/.]+$/, "").replace(/[-_]/g, ' ').replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()),
                size: stats.size,
                type: mimeTypeMap[ext] || 'video/mp4'
            };
        });
        
        // Wait for all async operations to complete
        return Promise.all(videoFilePromises);
    } catch (error) {
        console.error('Error reading video directory:', error);
        return [];
    }
});

// Recursive video directory scanner
ipcMain.handle('read-video-directory-recursive', async (event, dirPath) => {
    const videoExtensions = ['.mp4', '.webm', '.ogv', '.mov', '.avi', '.mkv', '.m4v', '.3gp', '.flv'];
    const mimeTypeMap = {
        '.mp4': 'video/mp4',
        '.webm': 'video/webm',
        '.ogv': 'video/ogg',
        '.mov': 'video/quicktime',
        '.avi': 'video/x-msvideo',
        '.mkv': 'video/x-matroska',
        '.m4v': 'video/mp4',
        '.3gp': 'video/3gpp',
        '.flv': 'video/x-flv'
    };

    async function scanDirectory(currentPath) {
        let videoFiles = [];
        
        try {
            const items = await fs.readdir(currentPath, { withFileTypes: true });
            
            for (const item of items) {
                const itemPath = path.join(currentPath, item.name);
                
                if (item.isDirectory()) {
                    // Recursively scan subdirectories
                    const subDirVideos = await scanDirectory(itemPath);
                    videoFiles.push(...subDirVideos);
                } else if (item.isFile()) {
                    const ext = path.extname(item.name).toLowerCase();
                    if (videoExtensions.includes(ext)) {
                        try {
                            const stats = await fs.stat(itemPath);
                            videoFiles.push({
                                name: item.name,
                                path: itemPath,
                                url: `file:///${itemPath.replace(/\\/g, '/')}`,
                                title: item.name.replace(/\.[^/.]+$/, "").replace(/[-_]/g, ' ').replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()),
                                size: stats.size,
                                type: mimeTypeMap[ext] || 'video/mp4',
                                directory: path.dirname(itemPath)
                            });
                        } catch (statError) {
                            console.warn(`Could not stat video file: ${itemPath}`, statError);
                        }
                    }
                }
            }
        } catch (readError) {
            console.warn(`Could not read directory: ${currentPath}`, readError);
        }
        
        return videoFiles;
    }

    try {
        console.log(`🔍 Starting recursive scan of: ${dirPath}`);
        const allVideos = await scanDirectory(dirPath);
        console.log(`✅ Recursive scan complete: Found ${allVideos.length} videos`);
        return allVideos;
    } catch (error) {
        console.error('Error in recursive video directory scan:', error);
        return [];
    }
});

// Recursive image directory scanner
ipcMain.handle('read-image-directory-recursive', async (event, dirPath) => {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg', '.tiff', '.ico'];
    
    async function scanDirectory(currentPath) {
        let imageFiles = [];
        
        try {
            const items = await fs.readdir(currentPath, { withFileTypes: true });
            
            for (const item of items) {
                const itemPath = path.join(currentPath, item.name);
                
                if (item.isDirectory()) {
                    // Recursively scan subdirectories
                    const subDirImages = await scanDirectory(itemPath);
                    imageFiles.push(...subDirImages);
                } else if (item.isFile()) {
                    const ext = path.extname(item.name).toLowerCase();
                    if (imageExtensions.includes(ext)) {
                        try {
                            const stats = await fs.stat(itemPath);
                            imageFiles.push({
                                name: item.name,
                                path: itemPath,
                                url: `file:///${itemPath.replace(/\\/g, '/')}`,
                                title: item.name.replace(/\.[^/.]+$/, "").replace(/[-_]/g, ' ').replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()),
                                size: stats.size,
                                type: `image/${ext.slice(1)}`,
                                directory: path.dirname(itemPath)
                            });
                        } catch (statError) {
                            console.warn(`Could not stat image file: ${itemPath}`, statError);
                        }
                    }
                }
            }
        } catch (readError) {
            console.warn(`Could not read directory: ${currentPath}`, readError);
        }
        
        return imageFiles;
    }

    try {
        console.log(`🔍 Starting recursive image scan of: ${dirPath}`);
        const allImages = await scanDirectory(dirPath);
        console.log(`✅ Recursive image scan complete: Found ${allImages.length} images`);
        return allImages;
    } catch (error) {
        console.error('Error in recursive image directory scan:', error);
        return [];
    }
});

ipcMain.handle('copy-video', async (event, sourcePath, destPath) => {
    try {
        await fs.mkdir(path.dirname(destPath), { recursive: true });
        await fs.copyFile(sourcePath, destPath);
        return true;
    } catch (error) {
        console.error('Error copying video file:', error);
        return false;
    }
});

ipcMain.handle('delete-video', async (event, filePath) => {
    try {
        await fs.unlink(filePath);
        return true;
    } catch (error) {
        console.error('Error deleting video file:', error);
        return false;
    }
});