<template>
  <div class="mt-2 p-2 lg:p-4">
    <div class="relative">
      <div class="absolute inset-y-0 left-3 flex items-center z-10">
        <svg class="flex-shrink-0 h-5 w-5 text-gray-light" xmlns="http://www.w3.org/2000/svg"
             viewBox="0 0 24 24" fill="currentColor"
        > <path fill-rule="evenodd" clip-rule="evenodd"
                d="M11 4a7 7 0 100 14 7 7 0 000-14zm-9 7a9 9 0 1118 0 9 9 0 01-18 0z"
        /> <path fill-rule="evenodd" clip-rule="evenodd"
                 d="M15.943 15.943a1 1 0 011.414 0l4.35 4.35a1 1 0 01-1.414 1.414l-4.35-4.35a1 1 0 010-1.414z"
        /> </svg>
      </div>
      <input class=" relative w-full focus:ring-4 focus:ring-offset-1 focus:ring-orange focus:ring-opacity-20 focus:ring-offset-orange focus:border-transparent text-gray border border-indigo-300 bg-indigo-200 rounded-md placeholder-gray-light !pl-10 " placeholder="Поиск музыки"
             type="search"
      />
    </div>
  </div>

  <div data-simplebar class="max-h-72 overflow-auto ">
    <div class="mt-2 divide-y divide-indigo-100">
      <div
        v-for="listsMusic in listsFavoriteMusicsState"
        :ref="el => { if (el && listsMusic.id === lastElementIDGet) loadMore = el }"
        :key="listsMusic.id"
        class="
        hover:bg-indigo-300 hover:bg-opacity-25 p-4 flex items-center space-x-4" @click="toggleAudioLocal(listsMusic)"
      >
        <div class="flex">
          <button class="default">
            <svg class="w-6 h-6">
              <use v-show="!listsMusic.playing" xlink:href="#play"></use>
              <use v-show="listsMusic.playing" xlink:href="#pause"></use>
            </svg>
          </button>
        </div>
        <div class="flex flex-1 text-sm text-gray-light">
          {{ listsMusic.name }}
        </div>
        <music-add-count v-if="$page.props.auth.user" :media_id="listsMusic.id"
                         :liked="listsMusic.liked" @addAudio="likeAudio"
        />
        <div class="text-sm text-gray-light">
          <span v-show="!listsMusic.playing">{{ listsMusic.time }}</span>
          <span v-show="listsMusic.playing">{{ seekState }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import find from 'lodash/find'
import { Inertia } from '@inertiajs/inertia'

import MusicAddCount from '@/Shared/Misc/MusicAddCount.vue'

export default {
    components: {
        MusicAddCount,
    },
    setup() {
        const store = useStore()
        const containerRef = ref(null)
        let observer = null

        const playingGet = computed(() => store.getters['playing'])
        const lastElementIDGet = computed(() => store.getters['lastFavID'])

        const seekState = computed(() => store.state.player.seek)
        const currentSongState = computed(() => store.state.player.currentSong)
        const listsFavoriteMusicsState = computed(
            () => store.state.player.favorite_playlist
        )

        const toggleAudioLocal = (music) => {
            if (playingGet.value || currentSongState.value?.id === music.id) {
                store.dispatch('toggleAudio')
                return
            }
            store.dispatch('skipToIndexByMusic', music)
        }
        onMounted(() => {
            store.dispatch('initFavoritedPlaylist').then(() => {
                createObserver()
            })
        })

        const createObserver = () => {
            if (containerRef.value) {
                const intersectionCallback = (entries) => {
                    entries.forEach((entry) => {
                        if (entry.isIntersecting) {
                            observer.unobserve(entry.target)
                            store.dispatch('paginationFavPlaylist').then((exist) => {
                                if (exist) {
                                    observer?.disconnect()
                                    createObserver()
                                }
                            })
                        }
                    })
                }
                observer = new IntersectionObserver(intersectionCallback, {})
                observer.observe(containerRef.value)
            }
        }

        onUnmounted(() => {
            observer?.disconnect()
        })

        const likeAudio = (media_id) => {
            Inertia.post(
                route('feed.audio.like', media_id),
                {},
                {
                    preserveScroll: true,
                    preserveState: true,
                }
            )
            let media = find(
                listsFavoriteMusicsState.value,
                (item) => item.id === media_id
            )
            if (media) {
                media.liked = !media.liked
            }
        }

        return {
            loadMore: containerRef,
            toggleAudioLocal,
            listsFavoriteMusicsState,
            seekState,
            lastElementIDGet,
            likeAudio,
        }
    },
}
</script>
