<template>
  <meta-head title="Читаемые пользователи"></meta-head>

  <profile-header :is_leader="is_leader" :user="user"
                  :counts="counts" :limit-leader="limitLeader"
                  :auth-user-active-subscription="authUserActiveSubscription"
                  :package-completed="packageCompleted"
  />
  <profile-menu :user="user" />


  <div v-if="user.is_auth_user || (user.private === false || packageCompleted)" class="mt-12 xl:container xl:mx-auto px-2 md:px-3">
    <div class="cards-block rounded-md bg-indigo-200 shadow-classic p-2 lg:p-5">
      <div class="">
        <search-filter v-model="form.search" class="w-full max-w-3xl mr-4"
                       @reset="reset"
        >
          <div class="flex flex-col space-y-6">
            <div class="flex items-center">
              <input id="user-leader-1" v-model="form.leader"
                     value="1" type="radio"
                     class="h-5 w-5 text-orange border-gray-light focus:ring-transparent focus:ring-offset-transparent"
              >
              <label for="user-leader-1" class="select-none ml-3 text-gray text-xs md:text-base">По лидерам</label>
            </div>
            <div class="flex items-center">
              <input id="user-leader-2" v-model="form.leader"
                     value="0" type="radio"
                     class="h-5 w-5 text-orange border-gray-light focus:ring-transparent focus:ring-offset-transparent"
              >
              <label for="user-leader-2" class="select-none ml-3 text-gray text-xs md:text-base">Не по лидерам</label>
            </div>
          </div>
        </search-filter>
      </div>


      <div v-show="readers.length" class="mt-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 grid gap-2 lg:gap-4 grid-cards">
        <InfinityScroll :node-element="lastNodeLement" :next-cursor="nextCursor"
                        @fromPagination="putFromPagination"
        >
          <div v-for="reader in userLists" :key="reader.id"
               :ref="el => { if (el && reader.id === lastElementID) lastNodeLement = el }" class="group mb-5 user-card relative"
          >
            <div v-if="user.is_auth_user" class="absolute inset-x-0 top-4 z-10 flex justify-center">
              <toggle
                v-if="authUserActiveSubscription"
                :user_id="reader.id"
                :enabled="reader.is_leader"
                :disabled="limitLeader === true && reader.is_leader === false ? true : false"
                textin="Сделать лидером"
                textout="Убрать лидера" @clicked="leader"
              />
            </div>
            <div class="absolute inset-x-0 bottom-4 z-10 flex justify-center">
              <div class="flex flex-col items-center">
                <inertia-link :href="route('profile.user', reader.username)" class="block flex-shrink-0">
                  <user-avatar :user="reader" size="small"
                               class="border border-white shadow-classic h-20 w-20  text-lg"
                  />
                </inertia-link>
                <inertia-link :href="route('profile.user', reader.username)" class="mt-2 block text-white text-sm text-center">
                  <p>{{ reader.name }}</p>
                  <p class="text-xs">
                    {{ reader.username }}
                  </p>
                </inertia-link>
              </div>
            </div>
            <div class="gradient-profile relative overflow-hidden">
              <user-banner class="w-full h-72 bg-indigo-300" :user="reader"
                           size="banner"
              />
            </div>
            <!-- myPaidListSubscribeTo[reader.id] -->
            <div v-if="user.is_auth_user && (reader.private === false ? true : false) " class="transition-opacity sm:opacity-0 group-hover:opacity-100 absolute w-full text-center">
              <button class="leading-none focus:outline-none hover:underline text-sm text-orange-dark" @click="susbscribe(reader.id)">
                Отписаться
              </button>
            </div>
          </div>
        </InfinityScroll>
      </div>
    </div>
    <div v-show="readers.length == 0">
      <p class="mt-4 text-center md:text-2xl text-gray-light">
        Пользователи не найдены
      </p>
    </div>
  </div>
  <div v-else class="mt-12 xl:container xl:mx-auto px-2 md:px-3 text-gray-light text-lg">
    Аккаунт закрыт
  </div>
</template>

<script>
import { ref } from 'vue'
import { Inertia } from '@inertiajs/inertia'
import filter from 'lodash/filter'
import pickBy from 'lodash/pickBy'
import throttle from 'lodash/throttle'
import mapValues from 'lodash/mapValues'

import Layout from '@/Shared/Layout.vue'
import MetaHead from '@/Shared/MetaHead.vue'
import ProfileHeader from '@/Shared/Partials/ProfileHeader.vue'
import ProfileMenu from '@/Shared/Partials/ProfileMenu.vue'
import UserAvatar from '@/Shared/Misc/UserAvatar.vue'
import UserBanner from '@/Shared/Misc/UserBanner.vue'
import Toggle from '@/Shared/Form/Toggle.vue'
import SearchFilter from '@/Shared/Form/SearchFilter.vue'
import InfinityScroll from '@/Shared/Misc/InfinityScroll.vue'


export default {
    components: {
        MetaHead,
        Toggle,
        UserAvatar,
        UserBanner,
        ProfileHeader,
        ProfileMenu,
        SearchFilter,
        InfinityScroll,
    },
    layout: Layout,
    props: {
        nextCursor: String,
        user: Object,
        myPaidListSubscribeTo: Object,
        readers: Array,
        counts: Object,
        filters: Object,
        is_leader: Boolean,
        authUserActiveSubscription: Boolean,
        close_account: Boolean,
        limitLeader: {
            type: Boolean,
            default: false
        },
        packageCompleted: {
            type: Boolean,
            default: false
        },

    },

    setup() {
        const containerRef = ref(null)
        return {
            lastNodeLement: containerRef,
        }
    },

    data() {
        return {
            userLists: [],
            form: {
                search: this.filters.search,
                leader: this.filters.leader,
            },
        }
    },

    computed: {
        lastElementID() {
            return this.userLists[this.userLists.length - 1]?.id
        },
        // limitChoiceLeader() {
        //     return this.userLists.filter(item => item.is_leader === true).length === 2
        // },
    },

    mounted() {
        this.updateRequest()
    },
    watch: {
        readers() {
            this.updateRequest()
        },

        form: {
            deep: true,
            handler: throttle(function () {
                const url = route('profile.readers', this.user.username)
                Inertia.get(url, pickBy(this.form), {
                    preserveState: true,
                    preserveScroll: true,
                })
            }, 300),
        },
    },

    methods: {
        putFromPagination(lists) {
            for (let list of lists) {
                this.userLists.push(list)
            }
        },

        updateRequest() {
            this.userLists = this.readers
        },

        reset() {
            this.form = mapValues(this.form, () => null)
        },

        susbscribe(user_id) {
            Inertia.post(
                route('users.subs', user_id),
                {},
                { preserveScroll: true, preserveState: true }
            )
        },

        leader(user_id) {
            let current_user = filter(this.readers, function (x) {
                return x.id === user_id
            })
            if (current_user) {
                current_user = current_user[0]
                Inertia.post(
                    route('users.leader', user_id),
                    { vote: current_user.is_leader },
                    { preserveScroll: true, preserveState: true }
                )
            }
        },
    },
}
</script>
