<template>
  <UiConfirm
    v-model="isDeleteStep"
    :title="$t('playlist.delete_playlist')"
    :confirm-text="$t('playlist.delete')"
    :loading="loadingAll"
    transparent-backdrop
    @confirm="onDeleteClick"
  >
    <i18n-t
      keypath="playlist.confirm_delete"
      tag="p"
      scope="global"
      class="playlist-edit__confirm"
    >
      <strong>{{ selectedPlaylist?.name }}</strong>
    </i18n-t>
    <p class="playlist-edit__confirm-note">
      {{ $t('playlist.confirm_delete_note', { videos: $t('plural.videos', selectedPlaylist?.videosCount ?? 0) }) }}
    </p>
  </UiConfirm>

  <!--  Edit-->
  <transition mode="out-in">
    <UiPopup
      v-if="isPlaylistEditOpen && currentStep === PlaylistStep.Edit"
      v-model="isPlaylistEditOpen"
      :back="!!onBack"
      class="playlist-edit"
      sheet
      transparent-backdrop
      @back="goBack"
      @close="closePlaylistEditAll"
    >
      <template #title>{{ $t('playlist.edit_playlist') }}</template>

      <div
        :class="{'_loading': loadingAll}"
        class="playlist-edit__form"
      >
        <UiInput
          v-model="inputValue"
          :placeholder="$t('playlist_name')"
          @enter="onSaveClick"
        />
        <PlaylistVisibility v-model="typeValue"/>
      </div>

      <template #footer>
        <div class="playlist-edit__footer">
          <button
            class="playlist-edit__delete"
            type="button"
            @click="openPlaylistEdit(PlaylistStep.Delete, true, selectedPlaylist)"
          >
            <UiIcon
              name="trash-bin"
              size="16"
            />
            {{ $t('delete') }}
          </button>
          <div class="playlist-edit__actions">
            <UiBtn
              :disabled="loadingAll"
              size="l"
              theme="muted"
              @click="goBack"
            >{{ $t('cancel') }}
            </UiBtn>
            <UiBtn
              :disabled="loadingAll || !inputValue.trim()"
              size="l"
              theme="primary"
              @click="onSaveClick"
            >{{ $t('save') }}
            </UiBtn>
          </div>
        </div>
      </template>
      <!--  Edit-->

    </UiPopup>
  </transition>
</template>

<script setup lang="ts">
import { PlaylistStep, PlaylistType, AsyncData } from '../../runtime';
import type { IPlaylistData } from '../../types';

const props = defineProps<{
  loadingPlaylists: boolean
  loadingRefresh: boolean
  loadingPlaylistDelete: boolean
}>();

const emit = defineEmits<{
  (eventName: 'delete-playlist', eventValue: { id: string, name?: string }): void
  (eventName: 'save-edit', eventValue: {
    id: string
    playlistName: string
    playlistType: PlaylistType
  }): void
}>();

const inputValue = ref('');
const typeValue = ref<PlaylistType>(PlaylistType.Public);

const {
  isPlaylistEditOpen,
  closePlaylistEdit,
  closePlaylistEditAll,
  currentStep,
  selectedPlaylist,
  openPlaylistEdit,
  onBack,
} = usePlaylistEdit();

/** Возврат к попапу, откуда пришли (список плейлистов), либо просто закрытие. */
function goBack() {
  const back = onBack.value;
  closePlaylistEditAll();
  back?.();
}

const isDeleteStep = computed({
  get: () => isPlaylistEditOpen.value && currentStep.value === PlaylistStep.Delete,
  set: (val: boolean) => {
    if (!val) closePlaylistEdit();
  },
});
const { show } = useSnackbar();

const route = useRoute();
const id = computed(() => selectedPlaylist.value?.id ?? (route.params[ 'playlistId' ] ? String(route.params[ 'playlistId' ]) : undefined));

const playlistsData = useState<IPlaylistData>(`data-${AsyncData.PlaylistById}-${id.value}`);

// Сначала закрываем попап, потом сообщаем об удалении: снекбар с undo показывает владелец
// запроса (PlaylistMain), и всплыть он должен уже в макете, а не в закрывающемся диалоге.
function onDeleteClick() {
  const playlistId = id.value || '';
  const name = selectedPlaylist.value?.name;

  goBack();
  emit('delete-playlist', { id: playlistId, name });
}

async function onSaveClick() {
  try {
    emit('save-edit', {
      id: id.value || '',
      playlistName: inputValue.value,
      playlistType: typeValue.value,
    });

    if (playlistsData.value) {
      playlistsData.value.name = inputValue.value ? inputValue.value : playlistsData.value.name;
      playlistsData.value.playlistType = typeValue.value;
    }
    goBack();
    show('changes_soon');
  } catch {
    console.log('error save');
  }
}

watch(
  () => [isPlaylistEditOpen.value, currentStep.value, selectedPlaylist.value],
  ([open, step]) => {
    if (!open || step !== PlaylistStep.Edit) return;

    inputValue.value = selectedPlaylist.value?.name || '';
    typeValue.value = selectedPlaylist.value?.playlistType ?? PlaylistType.Public;
  },
  { immediate: true }
);

const loadingAll = computed(() => props.loadingRefresh || props.loadingPlaylists || props.loadingPlaylistDelete);
</script>

<style lang="scss">
.playlist-edit__confirm {
  @include font-sm;

  line-height: 1.5;
}

.playlist-edit__confirm strong {
  font-weight: 600;
  color: $playlist-edit-confirm-highlight;
}

.playlist-edit__confirm-note {
  @include font-sm;

  margin-top: 12px;
  line-height: 1.5;
  color: $playlist-edit-confirm-note;
}

.playlist-edit .ui-popup__content {
  padding: 0;
}

.playlist-edit .ui-popup__footer {
  padding-inline: 24px;
}

.playlist-edit__form {
  display: grid;
  row-gap: 16px;
  padding: 20px 24px;
}

.playlist-edit__form .ui-input {
  --input-bg: #{$playlist-input-bg};
}

.playlist-edit__form .ui-input__input {
  @include from-br(sm) {
    padding-block: 12px;
  }
}

.playlist-edit__footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  column-gap: 12px;
}

.playlist-edit__actions {
  display: flex;
  column-gap: 12px;
}

.playlist-edit__delete {
  @include font-sm;

  display: flex;
  align-items: center;
  column-gap: 8px;
  font-weight: 500;
  color: $playlist-edit-delete-text;

  @include hover(color) {
    color: $playlist-edit-delete-text--hover;
  }
}

</style>
