
import API from "../../api.js";
import TableBasePage from "../base_table.js";
import Utils from "../../lib/utils.js";

export default class PageMtgGames extends TableBasePage {
    static hash = hashPageMtgGames;
    static attrIdRowObject = attrGameId;
    callSaveTableContent = API.saveGame;

    constructor(router) {
        super(router);
    }

    initialize() {
        this.sharedInitialize();
    }
    hookupFilters() {
        /*
        this.sharedHookupFilters();
        this.hookupFilterActive();
        */
    }

    loadRowTable(rowJson) {
        if (rowJson == null) return;
        if (_verbose) { Utils.consoleLogIfNotProductionEnvironment("applying data row: ", rowJson); }
    }
    getJsonRow(row) {
        return;
    }
    initialiseRowNew(tbody, row) {
    }
    postInitialiseRowNewCallback(tbody) {
    }

    hookupTableMain() {
        super.hookupTableMain();
        // this.hookupTableMainRows();
        this.hookupTcgGames();
        // PageMtgGames.hideNewGameForm();
    }
    hookupTcgGames() {
        console.log("hookupTableMain PageMtgGames");
        // Initialize form submission
        const newGameForm = document.getElementById('newGameForm');
        if (newGameForm) {
            newGameForm.addEventListener('submit', this.handleNewGameSubmit.bind(this)); // () => { this.handleNewGameSubmit.bind(this); });
        }

        // Initialize filter form
        const filterForm = document.getElementById('formFilters');
        if (filterForm) {
            filterForm.addEventListener('submit', PageMtgGames.handleFilterSubmit);
        }

        // Close modal on escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                PageMtgGames.hideNewGameForm();
            }
        });

        // Close modal on backdrop click
        const modal = document.getElementById('newGameModal');
        if (modal) {
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    PageMtgGames.hideNewGameForm();
                }
            });
        }

        // Button onclicks
        const newGameButton = document.getElementById('btnNewGame');
        if (newGameButton) {
            newGameButton.addEventListener('click', PageMtgGames.showNewGameForm);
        }
        const cancelNewGameButtons = document.querySelectorAll(
              '#newGameForm .form-actions .btn-tcg.btn-tcg-secondary'
            + ','
            + '#newGameModal .modal-content .modal-header .modal-close'
        );
        if (cancelNewGameButtons.length > 0) {
            cancelNewGameButtons.forEach((button) => {
                button.addEventListener('click', PageMtgGames.hideNewGameForm);
            });
        }

    }
    static showNewGameForm() {
        const modal = document.getElementById('newGameModal');
        if (modal) {
            modal.classList.remove(flagIsCollapsed);
            document.body.style.overflow = 'hidden';

            // Focus on first input
            const firstInput = modal.querySelector('input, select');
            if (firstInput) {
                firstInput.focus();
            }
        }
    }
    static hideNewGameForm() {
        const modal = document.getElementById('newGameModal');
        if (modal) {
            modal.classList.add(flagIsCollapsed);
            document.body.style.overflow = '';

            // Reset form
            const form = document.getElementById('newGameForm');
            if (form) {
                form.reset();
            }
        }
    }
    async handleNewGameSubmit(e) {
        e.preventDefault();

        const form = e.target;
        const formData = new FormData(form);

        const gameType = formData.get('game_type');
        const gameData = {
              [attrGameId]: -1
            , [flagIsCommander]: gameType === 'commander'
            , [flagIsDraft]: gameType === 'draft'
            , [flagIsSealed]: gameType === 'sealed'
            , [flagLocationName]: formData.get(flagLocationName) || null
            , [flagNotes]: formData.get(flagNotes) || null
            , [flagStartOn]: new Date().toISOString()
            , [flagStartingLife]: formData.get(flagStartingLife) || 40
            , [flagActive]: true
        };

        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.textContent = 'Creating...';
        submitBtn.disabled = true;

        const games = [gameData];
        const comment = 'Create new game';
        API.saveGame(games, form, comment)
            .then(data => {
                if (data[flagStatus] == flagSuccess) {
                    if (_verbose) { 
                        Utils.consoleLogIfNotProductionEnvironment('Records saved!');
                        Utils.consoleLogIfNotProductionEnvironment('Data received:', data);
                    }
                    const gamePageHash = `${hashPageGame}/${data[attrGameId]}`;
                    let filtersJson = {};
                    this.leave();
                    API.goToHash(gamePageHash, filtersJson);
                }
                else {
                    Utils.consoleLogIfNotProductionEnvironment("error: " + data[flagMessage]);
                    // OverlayError.show(data[flagMessage]);
                    window.location.reload();
                }
            })
            .catch(error => {
                console.error('Error creating game:', error);
                PageMtgGames.showError('An error occurred while creating the game');
            })
            .finally(() => {
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            });
    
    }
    static handleFilterSubmit(e) {
        // Let the form submit normally - it will reload with query params
        // You can add client-side filtering here if needed
    }
    static getCSRFToken() {
        // Try meta tag first
        const metaTag = document.querySelector('meta[name="csrf-token"]');
        if (metaTag) {
            return metaTag.getAttribute('content');
        }

        // Try hidden input
        const hiddenInput = document.querySelector('input[name="csrf_token"]');
        if (hiddenInput) {
            return hiddenInput.value;
        }

        // Try cookie
        const cookies = document.cookie.split(';');
        for (let cookie of cookies) {
            const [name, value] = cookie.trim().split('=');
            if (name === 'csrf_token') {
                return value;
            }
        }

        return '';
    }
    static showError(message) {
        // Check if there's an overlay error element
        const errorOverlay = document.getElementById('overlayError');
        if (errorOverlay) {
            const errorLabel = errorOverlay.querySelector('.error-message, #labelError');
            if (errorLabel) {
                errorLabel.textContent = message;
            }
            errorOverlay.classList.remove(flagIsCollapsed);
            errorOverlay.style.display = 'flex';
        } else {
            // Fallback to alert
            alert(message);
        }
    }
    static showSuccess(message) {
        // Could implement a toast notification here
        console.log('Success:', message);
    }
    static joinGame(gameId) {
        window.location.href = `${hashPageGame}/${gameId}`;
    }
    static async deleteGame(gameId) {
        if (!confirm('Are you sure you want to delete this game? This action cannot be undone.')) {
            return;
        }

        try {
            const gameData = {
                'game_id': gameId,
                'active': false
            };

            const response = await fetch(hashSaveGame, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': PageMtgGames.getCSRFToken()
                },
                body: JSON.stringify({
                    [flagGame]: [gameData],
                    'form-filters': {},
                    'comment': 'Game deleted'
                })
            });

            const result = await response.json();

            if (result.status === 'success') {
                // Remove the row from the table
                const row = document.querySelector(`tr[data-game-id="${gameId}"]`);
                if (row) {
                    row.style.animation = 'tcg-fadeOut 0.3s ease-out forwards';
                    setTimeout(() => row.remove(), 300);
                }
            } else {
                PageMtgGames.showError(result.message || 'Failed to delete game');
            }
        } catch (error) {
            console.error('Error deleting game:', error);
            PageMtgGames.showError('An error occurred while deleting the game');
        }
    }

    toggleShowButtonsSaveCancel() {}
    leave() {
        super.leave();
    }
}
