const API_BASE = '/api';
let currentList = [];
let filteredList = [];

document.addEventListener('DOMContentLoaded', async () => {
    await loadList();
    setupEventListeners();
});

function getEntryLink(item) {
    const isAnime = item.entry_type?.toUpperCase() === 'ANIME';
    const baseRoute = isAnime ? '/anime' : '/book';
    const source = item.source || 'anilist';

    if (source === 'anilist') {
        return `${baseRoute}/${item.entry_id}`;
    } else {
        return `${baseRoute}/${source}/${item.entry_id}`;
    }
}

async function populateSourceFilter() {
    const select = document.getElementById('source-filter');
    if (!select) return;

    select.innerHTML = `
        <option value="all">All Sources</option>
        <option value="anilist">AniList</option>
    `;

    try {
        const [animeRes, bookRes] = await Promise.all([
            fetch(`${API_BASE}/extensions/anime`),
            fetch(`${API_BASE}/extensions/book`)
        ]);

        const extensions = new Set();

        if (animeRes.ok) {
            const data = await animeRes.json();
            (data.extensions || []).forEach(ext => extensions.add(ext));
        }

        if (bookRes.ok) {
            const data = await bookRes.json();
            (data.extensions || []).forEach(ext => extensions.add(ext));
        }

        extensions.forEach(extName => {
            const lower = extName.toLowerCase();
            if (lower !== 'anilist' && lower !== 'local') {
                const option = document.createElement('option');
                option.value = extName;
                option.textContent = extName.charAt(0).toUpperCase() + extName.slice(1);
                select.appendChild(option);
            }
        });
    } catch (error) {
        console.error('Error loading extensions:', error);
    }
}

function updateLocalList(entryData, action) {
    const entryId = entryData.entry_id;
    const source = entryData.source;

    const findIndex = (list) => list.findIndex(e =>
        e.entry_id === entryId && e.source === source
    );

    const currentIndex = findIndex(currentList);
    if (currentIndex !== -1) {
        if (action === 'update') {

            currentList[currentIndex] = { ...currentList[currentIndex], ...entryData };
        } else if (action === 'delete') {
            currentList.splice(currentIndex, 1);
        }
    } else if (action === 'update') {

        currentList.push(entryData);
    }

    filteredList = [...currentList];

    updateStats();
    applyFilters();
    window.ListModalManager.close();
}

function setupEventListeners() {

    document.querySelectorAll('.view-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            const view = btn.dataset.view;
            const container = document.getElementById('list-container');
            if (view === 'list') {
                container.classList.add('list-view');
            } else {
                container.classList.remove('list-view');
            }
        });
    });

    document.getElementById('status-filter').addEventListener('change', applyFilters);
    document.getElementById('source-filter').addEventListener('change', applyFilters);
    document.getElementById('type-filter').addEventListener('change', applyFilters);
    document.getElementById('sort-filter').addEventListener('change', applyFilters);

    document.querySelector('.search-input').addEventListener('input', (e) => {
        const query = e.target.value.toLowerCase();
        if (query) {
            filteredList = currentList.filter(item =>
                item.title?.toLowerCase().includes(query)
            );
        } else {
            filteredList = [...currentList];
        }
        applyFilters();
    });

    document.getElementById('modal-save-btn')?.addEventListener('click', async () => {

        const entryToSave = window.ListModalManager.currentEntry || window.ListModalManager.currentData;

        if (!entryToSave) return;

        const success = await window.ListModalManager.save(entryToSave.entry_id, entryToSave.source);

        if (success) {

            const updatedEntry = window.ListModalManager.currentEntry;
            updatedEntry.updated_at = new Date().toISOString();

            updateLocalList(updatedEntry, 'update');
        }

    });

    document.getElementById('modal-delete-btn')?.addEventListener('click', async () => {
        const entryToDelete = window.ListModalManager.currentEntry || window.ListModalManager.currentData;

        if (!entryToDelete) return;

        const success = await window.ListModalManager.delete(entryToDelete.entry_id, entryToDelete.source);

        if (success) {
            updateLocalList(entryToDelete, 'delete');
        }

    });

    document.getElementById('add-list-modal')?.addEventListener('click', (e) => {
        if (e.target.id === 'add-list-modal') {
            window.ListModalManager.close();
        }
    });
}

async function loadList() {
    const loadingState = document.getElementById('loading-state');
    const emptyState = document.getElementById('empty-state');
    const container = document.getElementById('list-container');

    await populateSourceFilter();

    try {
        loadingState.style.display = 'flex';
        emptyState.style.display = 'none';
        container.innerHTML = '';

        const response = await fetch(`${API_BASE}/list`, {
            headers: window.AuthUtils.getSimpleAuthHeaders()
        });

        if (!response.ok) {
            throw new Error('Failed to load list');
        }

        const data = await response.json();
        currentList = data.results || [];
        filteredList = [...currentList];

        loadingState.style.display = 'none';

        if (currentList.length === 0) {
            emptyState.style.display = 'flex';
        } else {
            updateStats();
            applyFilters();
        }
    } catch (error) {
        console.error('Error loading list:', error);
        loadingState.style.display = 'none';
        if (window.NotificationUtils) {
            window.NotificationUtils.error('Failed to load your list. Please try again.');
        } else {
            alert('Failed to load your list. Please try again.');
        }
    }
}

function updateStats() {

    const total = currentList.length;
    const watching = currentList.filter(item => item.status === 'WATCHING').length;
    const completed = currentList.filter(item => item.status === 'COMPLETED').length;
    const planning = currentList.filter(item => item.status === 'PLANNING').length;

    document.getElementById('total-count').textContent = total;
    document.getElementById('watching-count').textContent = watching;
    document.getElementById('completed-count').textContent = completed;
    document.getElementById('planned-count').textContent = planning;
}

function applyFilters() {
    const statusFilter = document.getElementById('status-filter').value;
    const sourceFilter = document.getElementById('source-filter').value;
    const typeFilter = document.getElementById('type-filter').value;
    const sortFilter = document.getElementById('sort-filter').value;

    let filtered = [...filteredList];

    if (statusFilter !== 'all') {
        filtered = filtered.filter(item => item.status === statusFilter);
    }

    if (sourceFilter !== 'all') {
        filtered = filtered.filter(item => item.source === sourceFilter);
    }

    if (typeFilter !== 'all') {
        filtered = filtered.filter(item => item.entry_type === typeFilter);
    }

    switch (sortFilter) {
        case 'title':
            filtered.sort((a, b) => (a.title || '').localeCompare(b.title || ''));
            break;
        case 'score':
            filtered.sort((a, b) => (b.score || 0) - (a.score || 0));
            break;
        case 'progress':
            filtered.sort((a, b) => (b.progress || 0) - (a.progress || 0));
            break;
        case 'updated':
        default:

            filtered.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
            break;
    }

    renderList(filtered);
}

function renderList(items) {
    const container = document.getElementById('list-container');
    container.innerHTML = '';

    if (items.length === 0) {

        if (currentList.length === 0) {
            document.getElementById('empty-state').style.display = 'flex';
        } else {

            container.innerHTML = '<div class="empty-state"><p>No entries match your filters</p></div>';
        }
        return;
    }

    document.getElementById('empty-state').style.display = 'none';

    items.forEach(item => {
        const element = createListItem(item);
        container.appendChild(element);
    });
}

function createListItem(item) {
    const div = document.createElement('div');
    div.className = 'list-item';

    const itemLink = getEntryLink(item);

    const posterUrl = item.poster || '/public/assets/placeholder.svg';
    const progress = item.progress || 0;

    const totalUnits = item.entry_type === 'ANIME' ?
        item.total_episodes || 0 :
        item.total_chapters || 0;

    const progressPercent = totalUnits > 0 ? (progress / totalUnits) * 100 : 0;
    const score = item.score ? item.score.toFixed(1) : null;
    const repeatCount = item.repeat_count || 0;

    const entryType = (item.entry_type).toUpperCase();
    let unitLabel = 'units';
    if (entryType === 'ANIME') {
        unitLabel = 'episodes';
    } else if (entryType === 'MANGA') {
        unitLabel = 'chapters';
    } else if (entryType === 'NOVEL') {
        unitLabel = 'chapters/volumes';
    }

    const statusLabels = {
        'CURRENT': entryType === 'ANIME' ? 'Watching' : 'Reading',
        'COMPLETED': 'Completed',
        'PLANNING': 'Planning',
        'PAUSED': 'Paused',
        'DROPPED': 'Dropped',
        'REPEATING': entryType === 'ANIME' ? 'Rewatching' : 'Rereading'
    };

    const extraInfo = [];
    if (repeatCount > 0) {
        extraInfo.push(`<span class="meta-pill repeat-pill">🔁 ${repeatCount}</span>`);
    }
    if (item.is_private) {
        extraInfo.push('<span class="meta-pill private-pill">🔒 Private</span>');
    }

    const entryDataString = JSON.stringify(item).replace(/'/g, '&#39;');

    div.innerHTML = `
        <a href="${itemLink}" class="item-poster-link">
            <img src="${posterUrl}" alt="${item.title || 'Entry'}" class="item-poster" onerror="this.src='/public/assets/placeholder.png'">
        </a>
        <div class="item-content">
            <div>
                <a href="${itemLink}" style="text-decoration:none; color:inherit;">
                    <h3 class="item-title">${item.title || 'Unknown Title'}</h3>
                </a>
                <div class="item-meta">
                    <span class="meta-pill status-pill">${statusLabels[item.status] || item.status}</span>
                    <span class="meta-pill type-pill">${entryType}</span> 
                    <span class="meta-pill source-pill">${item.source.toUpperCase()}</span>
                    ${extraInfo.join('')}
                </div>
            </div>

            <div>
                <div class="progress-bar-container">
                    <div class="progress-bar" style="width: ${progressPercent}%"></div>
                </div>
                <div class="progress-text">
                    <span>${progress}${totalUnits > 0 ? ` / ${totalUnits}` : ''} ${unitLabel}</span> ${score ? `<span class="score-badge">⭐ ${score}</span>` : ''}
                </div>
            </div>
        </div>

        <button class="edit-icon-btn" data-entry='${entryDataString}'>
            <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
                <path d="M15.232 5.232l3.536 3.536m-2.036-5.808a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.536L15.232 5.232z"/>
            </svg>
        </button>
        `;

    const editBtn = div.querySelector('.edit-icon-btn');
    editBtn.addEventListener('click', (e) => {
        try {
            const entryData = JSON.parse(e.currentTarget.dataset.entry);

            window.ListModalManager.isInList = true;
            window.ListModalManager.currentEntry = entryData;
            window.ListModalManager.currentData = entryData;

            window.ListModalManager.open(entryData, entryData.source);
        } catch (error) {
            console.error('Error parsing entry data for modal:', error);
            if (window.NotificationUtils) {
                window.NotificationUtils.error('Could not open modal. Check HTML form IDs.');
            }
        }
    });

    return div;
}