import { markRaw } from 'vue'

import { insertIf } from '@inside-library/helpers/Arrays'
import { http } from '@inside-library/helpers/Http'
import { formatHref, routeExists } from '@inside-library/helpers/Langs'
import { Link } from 'inside-collection/components'
import InsideRouterLink from '@inside-links/components/lib/InsideRouterLink'
import refreshListingMixin from '@inside-listings/mixins/refresh-listing-mixin'

export default {
  mixins: [refreshListingMixin],
  computed: {
    actions() {
      return [
        {
          id: 'link',
          icon: 'eye-on',
          label: this.$_tr('actions.link'),
          callback: async (fields, vm) => {
            const method = vm.$_getRedirectionMethod(
              fields.content_type || fields.type
            )

            const fallbackMethod = vm.$_getRedirectionMethod(
              fields.content_type,
              'fallback'
            )

            const redirectionParams = {
              data: fields,
              params: vm.$_getRedirectionParams(
                fields.content_type || fields.type
              )
            }

            if (method) {
              let redirection = method(redirectionParams)

              if (redirection instanceof Promise) {
                redirection.then(res => {
                  redirection = res

                  if (routeExists({ router: vm.$router, to: redirection })) {
                    const url = vm.$router.resolve(
                      formatHref(redirection, vm.$_currentLang)
                    ).href

                    window.open(url, '_blank')
                  }
                })
              } else {
                if (routeExists({ router: vm.$router, to: redirection })) {
                  const url = vm.$router.resolve(
                    formatHref(redirection, vm.$_currentLang)
                  ).href

                  window.open(url, '_blank')
                }
              }
            } else {
              const fallbackRedirection = fallbackMethod
                ? fallbackMethod(redirectionParams)
                : `/${vm.getCheckedData(fields, ['slug', 0])}`

              vm.$router.push(fallbackRedirection)
            }
          }
        },
        {
          id: 'edit',
          icon: 'edit',
          tag: markRaw(Link),
          label: this.$_tr('actions.edit'),
          hideIf: (data, vm) => {
            const canUpdate = vm.getCheckedData(data, [
              'admin',
              'permission',
              'update'
            ])
            return !canUpdate
          },
          data: ({ content_type: content, uuid }) => ({
            href: {
              name: 'Edition',
              params: { content, uuid }
            },
            target: '_blank',
            inline: false
          })
        },
        {
          id: 'duplication',
          icon: 'duplicate',
          label: this.$_tr('actions.duplicate'),
          hideIf: data => {
            return data.content_type === 'procedures'
          },
          callback: async (data, vm) => {
            const action = async () => {
              const newWin = window.open('', '_blank')
              newWin.opener = null

              const metaTitle =
                vm.$store.getters.getInsideSettings('general.meta_title')

              newWin.document.write(`
                  <html>
                    <head>
                      <title>${metaTitle}</title>
                      <style>
                        body {
                          font-family:'Lato',sans-serif;
                          text-align:center; height: 100%;
                          display: flex;
                          flex-direction: column;
                          justify-content: center;

                          .loading-page-title {
                            margin: 0;
                          }
                        }

                        .spinner {
                          width: 24px;
                          height: 24px;
                          border: 3px solid #ccc;
                          border-top-color: #333;
                          border-radius: 50%;
                          animation: spin 1s linear infinite;
                          margin: 1rem auto;
                        }

                        @keyframes spin {
                          to { transform: rotate(360deg); }
                        }
                      </style>
                    </head>
                    <body>
                      <h3 class="loading-page-title">${
                        vm.$_currentLang === 'fr'
                          ? 'Duplication en cours...'
                          : 'Duplication in progress.'
                      }</h3>

                      <p>${
                        vm.$_currentLang === 'fr'
                          ? 'Merci de patienter quelques instants.'
                          : 'Please wait a few moments.'
                      }</p>

                      <div class="spinner" />
                    </body>
                  </html>
                `)

              document.title = metaTitle

              try {
                const res = await http.post('bclh/duplicate', {
                  content_type: data.content_type,
                  uuid: data.uuid
                })

                newWin.location.href = `/edit/${res.content_type}/${res.uuid}`
                document.title = metaTitle

                this.$_refresh(this.listingId)
              } catch (err) {
                newWin.close()

                throw new Error(err)
              }
            }

            const content = {
              item: {
                body: vm.$_tr('customs.DASHBOARD.DUPLICATE.text'),
                actionTitle: vm.$_tr('customs.DASHBOARD.DUPLICATE.button')
              },
              content: 'action'
            }

            vm.triggerModal('action', 'static', content, {
              layout: 'center',
              action,
              transition: 'fadeIn'
            })
          }
        }
      ]
    },
    massActions() {
      return [
        {
          id: 'export',
          icon: 'export',
          callback: async (data, vm) => {
            const { brands, countries, status, contentType } = vm.$route.query

            const selectedUuids = data.selection.items
              .map(item => item.uuid)
              .join(',')

            try {
              const filters = {
                ...(brands && {
                  brands
                }),
                ...(countries && {
                  countries
                }),
                ...(status && {
                  status
                }),
                ...(contentType && {
                  type: Array.isArray(contentType)
                    ? contentType.join(',')
                    : contentType
                }),
                ...(selectedUuids && {
                  'uuid:in': selectedUuids
                })
              }

              const { success } = await http.get('bclh/sop/export', {
                filters: {
                  ...this.requestFilters,
                  ...filters
                }
              })

              if (success) {
                vm.$_triggerSuccessToast({
                  title: vm.$_tr(
                    'customs.DASHBOARD.LISTING.export.success.title'
                  ),
                  text: vm.$_tr('customs.DASHBOARD.LISTING.export.success.text')
                })
              } else {
                vm.$_triggerErrorToast({
                  title: vm.$_tr('customs.DASHBOARD.LISTING.export.error.title')
                })
              }
            } catch (err) {
              throw new Error(err)
            }
          }
        },
        ...insertIf(this.selectedItems.length, {
          id: 'multipleEdition',
          icon: 'edit',
          tag: markRaw(Link),
          label: this.$_tr('actions.bulkEdit'),
          data: () => ({
            inline: false,
            href: formatHref(
              {
                name: 'BulkEdition',
                query: {
                  folder: this.fetchedData?.uuid,
                  uuids: this.selectedItems.map(item => item.uuid)
                }
              },
              this.$_currentLang
            )
          })
        })
      ]
    }
  }
}
