{% extends "base.html" %}

{% block content %}
    <div class="flex flex-col h-screen">
        {% include "default_header.html" %}
        <main class="flex flex-grow flex-row items-start justify-between bg-white px-4 sm:px-6 lg:px-8 overflow-y-auto">
            <div class="flex items-center justify-center bg-white px-4 py-0 sm:px-6 lg:px-8 h-full">
                {% if query != "" %}
                <a href="/search?q={{ query }}&p={{ page }}">
                    <svg width="24px" height="24px" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path fill="#EF4444" d="M224 480h640a32 32 0 1 1 0 64H224a32 32 0 0 1 0-64z"/><path fill="#EF4444" d="m237.248 512 265.408 265.344a32 32 0 0 1-45.312 45.312l-288-288a32 32 0 0 1 0-45.312l288-288a32 32 0 1 1 45.312 45.312L237.248 512z"/></svg>
                </a>
                {% endif %}
            </div>
            {% if media_exists %}
            <div id="media-main" class="w-full flex h-full max-h-full overflow-y-auto">
                <div class="flex-1">
                    {% if media.is_image %}
                        <img class="w-full h-full object-cover rounded-md focus:outline-none" src="{{ media.location_url }}" style="aspect-ratio:16/9;object-fit:contain;" />
                    {% else %}
                        <video id="media-player" preload="auto" autoplay="autoplay" loop="loop"
                                controls
                                class="w-full h-full object-cover rounded-md focus:outline-none"
                                src="{{ media.location_url }}"
                                style="aspect-ratio:16/9;object-fit:contain;"
                        ></video>
                    {% endif %}
                </div>
                <div class="w-96 p-4 bg-gray-100 rounded-md ml-4 flex flex-col justify-between overflow-y-auto">
                    <div class="h-fit">
                        <h2 class="text-2xl font-bold mb-2">File Info</h2>
                        <ul>
                            <li class="mb-2">
                                <strong>Id:</strong>
                                <span class="break-all"> {{ media.id }}</span>
                            </li>
                            <li class="mb-2">
                                <strong>Location:</strong>
                                <span class="break-all"> <a onclick="invoke('show_media_in_file_manager', { media_id: '{{ media.id }}' })" style="text-decoration: underline; color: blue; cursor: pointer;">{{ media.location }}</a></span>
                            </li>
                            <li class="mb-2">
                                <strong>Size:</strong>
                                <span class="break-all"> {{ media.human_size }}</span>
                            </li>
                            <li class="mb-2">
                                <strong>Type:</strong>
                                <span class="break-all"> {{ media.content_type }}</span>
                            </li>
                            <li class="mb-2">
                                <strong>Date:</strong>
                                <span class="break-all"> {{ media.created_at }}</span>
                            </li>
                        </ul>
                        <h2 class="text-2xl font-bold mb-2">Tags</h2>
                        <div class="mt-4">
                            <div class="rounded-md shadow-sm">
                                <div>
                                    <label class="sr-only" for="tag-search">
                                        Search Tags
                                    </label>
                                    <div class="mx-auto w-full" id="tag-search"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <ul id="tags-list" class="overflow-y-auto flex-grow mt-4">
                        {% for tag in media.tags %}
                        <li id="li-{{ tag.name }}" class="rounded px-2 py-1 mb-2 flex justify-between items-center"
                            style="background-color: {{ tag.bg_color }}; color: {{ tag.fg_color }};"
                        >
                            <a href="/search?q={{ tag.name }}&p=1">#{{ tag.name }}</a>
                            <span class="cursor-pointer hover:text-red-500" onclick="removeTagFromMedia('{{ tag.name }}', '{{ media.id }}')">X</span>
                        </li>
                        {% endfor %}
                    </ul>
                    <div class="mt-4 h-fit">
                        <button class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-red-600 text-white hover:bg-red-700 h-10 px-4 py-2 w-full"
                                onclick="deleteMedia('{{ media.id }}')" >
                            Delete media
                        </button>
                    </div>
                </div>
            </div>
            {% endif %}
            <div></div>
        </main>
        <footer class="w-full flex items-center justify-center bg-white h-14">
            <div class="text-center"><a class="text-gray-600" href="/media/random?seed={{ random_media_id }}">Charting digital depths, from Alferaki to Faina</a></div>
        </footer>
        {% include "search_autocomplete.html" %}
        <script>
            async function addTagToMedia(tag, mediaId, path) {
                const response = await invoke('add_tag_to_media', { media_id: mediaId, tags: tag, path });
                const tagsList = document.querySelector('#tags-list');
                for (const tag of response) {
                    const newLi = `
                        <li id="li-${tag.name}" class="rounded px-2 py-1 mb-2 flex justify-between items-center"
                            style="background-color: ${tag.bg_color}; color: ${tag.fg_color};"
                        >
                            <a href="/search?q=${tag.name}&p=1">#${tag.name}</a>
                            <span class="cursor-pointer hover:text-red-500" onclick="removeTagFromMedia('${tag.name}', '${mediaId}')">X</span>
                        </li>
                    `;
                    tagsList.insertAdjacentHTML('afterbegin', newLi);
                }
            }

            async function removeTagFromMedia(tag, mediaId) {
                await invoke('remove_tag_from_media', { media_id: mediaId, tags: tag });
                document.querySelector(`#li-${tag}`).remove();
            }

            async function deleteMedia(mediaId) {
                if (await invoke('delete_media', { media_id: mediaId })) {
                    window.location.href = '/search?q={{ query }}&p={{ page }}';
                }
            }

            window.addEventListener('DOMContentLoaded', () => {
                const video = document.getElementById('media-player');
                video.focus();
                // Attempt to play the video automatically
                video.play().catch(error => console.error("Auto-play was prevented by the browser."));
            });

            autocomplete({
                container: '#tag-search',
                getSources({ query }) {
                    return [
                        {
                            sourceId: 'tag-search',
                            getItems() {
                                return invoke("autocomplete_tags", { query: query })
                                    .then((data) => {
                                        return data.map((item) => {
                                            return {
                                                ...item,
                                                suggestion: item.suggestion,
                                                _highlightResult: {
                                                    highlighted_suggestion: {
                                                        value: item.highlighted_suggestion
                                                            .replace(/<mark>/g, '__aa-highlight__')
                                                            .replace(/<\/mark>/g, '__/aa-highlight__')
                                                    },
                                                },
                                            };
                                        });
                                    });
                            },
                            onSelect({ item }) {
                                const tagSearchInput = document.querySelector('#tag-search .aa-Input');
                                const tagSearchClearButton = document.querySelector('#tag-search .aa-ClearButton');
                                const urlParams = new URLSearchParams(window.location.search);
                                const path = urlParams.get('path');
                                addTagToMedia(tagSearchInput.value, '{{ media.id }}', path);
                                tagSearchClearButton.click();
                                tagSearchInput.focus();
                                requestAnimationFrame(() => {
                                    tagSearchInput.focus();
                                });
                                setTimeout(() => {
                                    tagSearchInput.focus();
                                }, 0);
                            },
                            getItemInputValue: ({ item }) => item.suggestion,
                            templates: {
                                item({ item, components, html }) {
                                    return html`<div className="aa-ItemWrapper">
                                  <div className="aa-ItemContent">
                                    <div className="aa-ItemContentBody">
                                      <div className="aa-ItemContentTitle">
                                        ${components.Highlight({ hit: item, attribute: 'highlighted_suggestion' })}
                                      </div>
                                    </div>
                                  </div>
                                </div>`
                                },
                            },
                        },
                    ];
                },
                onSubmit({ state }) {
                    if (state.query) {
                        const tagSearchInput = document.querySelector('#tag-search .aa-Input');
                        const tagSearchClearButton = document.querySelector('#tag-search .aa-ClearButton');
                        const urlParams = new URLSearchParams(window.location.search);
                        const path = urlParams.get('path');
                        addTagToMedia(tagSearchInput.value, '{{ media.id }}', path);
                        tagSearchClearButton.click();
                        tagSearchInput.focus();
                        requestAnimationFrame(() => {
                            tagSearchInput.focus();
                        });
                        setTimeout(() => {
                            tagSearchInput.focus();
                        }, 0);
                    }
                },
            });
        </script>
    </div>
{% endblock %}
