# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
from __python__ import hash_literals

from elementmaker import E
from gettext import gettext as _

from book_list.library_data import all_virtual_libraries
from book_list.saved_virtual_libraries import DEFAULT_SAVED_VIRTUAL_LIBRARY_ICON, normalize_saved_virtual_library_icon, saved_virtual_library_item
from book_list.saved_virtual_library_icon_picker import create_saved_virtual_library_icon_picker
from book_list.theme import get_color
from dom import add_extra_css, clear
from modals import create_custom_dialog
from widgets import create_button


add_extra_css(def (): return '''

.cs-virtual-library-dialog {
    width: 100%;
    min-width: 0;
    max-width: min(42rem, calc(100vw - 2rem));
    box-sizing: border-box;

    & .vl-row {
        margin-bottom: 0.75rem;
    }
    & .vl-checkbox-row {
        display: flex;
        align-items: center;
        margin-bottom: 0.35rem;
    }
    & .vl-label {
        display: block;
        margin: 0 0 0.45rem 0;
        font-weight: 700;
        opacity: 0.9;
    }
    & input[type="text"] {
        width: 100%;
        box-sizing: border-box;
        color: inherit;
    }
    & .vl-actions-save-cancel {
        display: flex;
        flex-wrap: wrap;
        align-items: stretch;
        justify-content: space-between;
        gap: 0.5rem;
        margin-top: 0.65rem;
    }
    & .vl-actions-save-cancel > a.calibre-push-button {
        flex: 1 1 0;
        min-width: 0;
        justify-content: center;
    }
    & .vl-actions-save-cancel--toprule {
        margin-top: 0.35rem;
        padding-top: 0.6rem;
        border-top: var(--calibre-border-style-subtle);
    }
}

.cs-vl-import-dialog {
    position: relative;
    width: 100%;
    min-width: 0;
    max-width: min(42rem, calc(100vw - 2rem));
    max-height: calc(min(60vh, 100vh - 6rem) - 5rem);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    & .vl-import-empty {
        opacity: 0.7;
        padding: 0.5rem 0;
    }
    & .vl-import-list {
        min-height: 8ex;
        overflow-y: auto;
        margin-bottom: 0.5rem;
        border: var(--calibre-border-style-subtle);
        border-radius: 6px;
        padding: 0.25rem 0;
    }
    & .vl-import-row {
        display: flex;
        align-items: center;
        gap: 0.55rem;
        padding: 0.45rem 0.65rem;
    }
    & .vl-import-row:not(:last-child) {
        border-bottom: var(--calibre-border-style-subtle);
    }
    & .vl-import-row input[type="checkbox"] {
        flex-shrink: 0;
        width: 1.1rem;
        height: 1.1rem;
        cursor: pointer;
    }
    & .vl-import-name {
        flex: 1 1 0;
        min-width: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    & .vl-import-icon-wrap {
        display: flex;
        align-items: center;
        gap: 0.3rem;
        flex-shrink: 0;
    }
    & .vl-import-icon-label {
        font-size: 0.8rem;
        opacity: 0.75;
        white-space: nowrap;
    }
    & .vl-import-icon-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 2.35rem;
        height: 2.35rem;
        padding: 0;
        margin: 0;
        font-size: 1.2rem;
        line-height: 1;
        border: var(--calibre-border-style-subtle);
        border-radius: 8px;
        background: rgba(0,0,0,0.02);
        color: inherit;
        cursor: pointer;
        transition: background 120ms ease, border-color 120ms ease;
    }
    & .vl-import-icon-btn:hover {
        background: var(--calibre-color-primary-light);
        border-color: var(--calibre-color-border);
    }
    & .vl-import-icon-btn:focus {
        outline: none;
        box-shadow: var(--calibre-focus-ring);
    }
    & .vl-import-icon-overlay {
        position: absolute;
        inset: 0;
        display: none;
        flex-direction: column;
        gap: 0.65rem;
        padding: 0.75rem;
        border-radius: 6px;
        overflow-y: auto;
        z-index: 10;
    }
    & .vl-import-overlay-title {
        font-weight: 700;
        font-size: 1rem;
        flex-shrink: 0;
    }
    & .vl-import-overlay-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        justify-content: space-between;
        margin-top: 0.25rem;
        flex-shrink: 0;
    }
    & .vl-import-overlay-actions > a.calibre-push-button {
        flex: 1 1 0;
        min-width: 0;
        justify-content: center;
    }
    & .vl-actions-save-cancel {
        display: flex;
        flex-wrap: wrap;
        align-items: stretch;
        justify-content: space-between;
        gap: 0.5rem;
        margin-top: 0.65rem;
        flex-shrink: 0;
    }
    & .vl-actions-save-cancel > a.calibre-push-button {
        flex: 1 1 0;
        min-width: 0;
        justify-content: center;
    }
    & .vl-actions-save-cancel--toprule {
        margin-top: 0.35rem;
        padding-top: 0.6rem;
        border-top: var(--calibre-border-style-subtle);
    }
}
'''
)


def show_import_virtual_libraries_dialog(library_id, on_save):
    create_custom_dialog(_('Import Virtual Libraries'), def (parent, close_modal):
        vls = all_virtual_libraries()
        vl_names = sorted(Object.keys(vls))
        if not vl_names.length:
            parent.appendChild(E.div(class_='cs-vl-import-dialog',
                E.div(_('No virtual libraries found in calibre settings.'), class_='vl-import-empty'),
                E.div(class_='vl-actions-save-cancel vl-actions-save-cancel--toprule',
                    create_button(_('Close'), 'close', def (ev = None): close_modal();),
                ),
            ))
            return
        # Shared overlay for icon picking – rendered over the import dialog
        overlay = E.div(class_='vl-import-icon-overlay')
        overlay.style.backgroundColor = get_color('dialog-background')
        def hide_overlay(ev=None):
            overlay.style.display = 'none'
            clear(overlay)
        def show_icon_overlay(row):
            picker = create_saved_virtual_library_icon_picker(row.icon)
            def confirm_icon(ev=None):
                row.icon = normalize_saved_virtual_library_icon(picker.get_value())
                row.icon_btn.textContent = row.icon
                hide_overlay()
            clear(overlay)
            overlay.appendChild(E.div(class_='vl-import-overlay-title', _('Choose icon')))
            overlay.appendChild(picker.root)
            overlay.appendChild(E.div(class_='vl-import-overlay-actions',
                create_button(_('Cancel'), 'close', hide_overlay),
                create_button(_('Select'), 'check', confirm_icon, highlight=True),
            ))
            overlay.style.display = 'flex'
        rows = []
        list_div = E.div(class_='vl-import-list')
        for vl_name in vl_names:
            search = vls[vl_name]
            cb = E.input(type='checkbox')
            cb.checked = True
            icon_btn = E.button(type='button', class_='vl-import-icon-btn',
                title=_('Click to change icon'))
            icon_btn.textContent = DEFAULT_SAVED_VIRTUAL_LIBRARY_ICON
            row_state = {'name': vl_name, 'search': search, 'checkbox': cb,
                         'icon': DEFAULT_SAVED_VIRTUAL_LIBRARY_ICON, 'icon_btn': icon_btn}
            def make_icon_handler(r):
                def handler(ev):
                    ev.preventDefault()
                    show_icon_overlay(r)
                return handler
            icon_btn.addEventListener('click', make_icon_handler(row_state))
            rows.push(row_state)
            list_div.appendChild(E.div(class_='vl-import-row',
                cb,
                E.span(vl_name, class_='vl-import-name', title=vl_name),
                E.div(class_='vl-import-icon-wrap',
                    E.span(_('Icon:'), class_='vl-import-icon-label'),
                    icon_btn,
                ),
            ))
        def do_import(ev=None):
            for row in rows:
                if row.checkbox.checked:
                    item = saved_virtual_library_item(library_id, row.name, row.search, '',
                                                      row.icon or DEFAULT_SAVED_VIRTUAL_LIBRARY_ICON, True)
                    if item:
                        on_save(item)
            close_modal()
        parent.appendChild(E.div(class_='cs-vl-import-dialog',
            list_div,
            overlay,
            E.div(class_='vl-actions-save-cancel vl-actions-save-cancel--toprule',
                create_button(_('Cancel'), 'close', def (ev = None): close_modal();),
                create_button(_('Import'), 'plus', do_import, highlight=True),
            ),
        ))
    )


def show_saved_virtual_library_dialog(
        title, save_label, on_save, library_id, virtual_library='', initial_name='', initial_search='',
        initial_icon=DEFAULT_SAVED_VIRTUAL_LIBRARY_ICON, initial_use_icon=True, on_delete=None, save_icon='check'):
    create_custom_dialog(title, def (parent, close_modal):
        name_input = E.input(type='text', value=((initial_name or '') + ''), placeholder=_('Virtual library name'))
        search_input = E.input(type='text', value=((initial_search or '') + ''), placeholder=_('Search expression'))
        icon_picker = create_saved_virtual_library_icon_picker((initial_icon or DEFAULT_SAVED_VIRTUAL_LIBRARY_ICON) + '')
        use_icon_cb = E.input(type='checkbox')
        use_icon_cb.checked = initial_use_icon is not False
        icon_section = E.div(class_='vl-icon-section',
            E.div(class_='vl-row',
                E.label(_('Icon'), class_='vl-label'),
                icon_picker.root
            ),
        )
        use_icon_help = E.div(_('When disabled, only the first character of the name is shown while the navigation is collapsed.'), class_='help')
        def sync_icon_section_visibility(ev=None):
            on = use_icon_cb.checked
            icon_section.style.display = 'block' if on else 'none'
            use_icon_help.style.display = 'none' if on else 'block'
        def save_item(ev=None):
            item = saved_virtual_library_item(library_id, name_input.value, search_input.value, virtual_library, icon_picker.get_value(), use_icon_cb.checked)
            if not item:
                return
            if on_save(item) is False:
                return
            close_modal()
        def delete_item(ev=None):
            if on_delete and on_delete() is False:
                return
            close_modal()
        def open_import(ev=None):
            close_modal()
            show_import_virtual_libraries_dialog(library_id, on_save)
        dialog = E.div(class_='cs-virtual-library-dialog',
            E.div(class_='vl-row',
                E.label(_('Virtual library name'), class_='vl-label'),
                name_input
            ),
            E.div(class_='vl-row',
                E.label(_('Search expression'), class_='vl-label'),
                search_input
            ),
            E.div(class_='vl-checkbox-row',
                use_icon_cb,
                E.span(_('Show icon in sidebar'), style='margin-left:0.45rem'),
            ),
            use_icon_help,
            icon_section,
        )
        actions_class = 'vl-actions-save-cancel'
        if not on_delete:
            actions_class += ' vl-actions-save-cancel--toprule'
        dialog.appendChild(E.div(class_=actions_class,
            create_button(_('Cancel'), 'close', def (ev = None): close_modal();),
            create_button(save_label, save_icon, save_item, highlight=True),
        ))
        if on_delete:
            dialog.lastChild.insertBefore(create_button(
                _('Delete'), 'trash', delete_item, _('Delete this Virtual library')), dialog.lastChild.firstChild)
        else:
            dialog.lastChild.insertBefore(
                create_button(_('Import'), 'library', open_import, _('Import virtual libraries from calibre settings')),
                dialog.lastChild.firstChild)
        parent.appendChild(dialog)
        use_icon_cb.addEventListener('change', sync_icon_section_visibility)
        sync_icon_section_visibility()
        setTimeout(def ():
            name_input.focus()
        , 10)
    )
