<!-- components/MediaPickerModal.vue -->
<template>
  <ReusableDialog
    v-model="isVisible"
    title="Select Media"
    :max-width="800"
    :loading="false"
    fullscreen-on-mobile
  >
    <VCardText class="pa-0">
      <div class="media-picker-container">
        <!-- Tab Buttons with proper spacing -->
        <div class="tabs-wrapper">
          <VTabs v-model="activeTab" class="v-tabs-pill" color="primary">
            <VTab value="library" class="px-4">
              <VIcon size="20" start icon="bx-folder-open" />
              Media Library
              <VChip
                v-if="localSelectedMedia.length > 0"
                size="small"
                color="primary"
                variant="flat"
                class="ml-2"
              >
                {{ localSelectedMedia.length }}
              </VChip>
            </VTab>

            <VTab v-if="canShowUploadTab" value="upload" class="px-4">
              <VIcon size="20" start icon="bx-upload" />
              Upload New
            </VTab>
          </VTabs>
        </div>

        <VDivider />

        <!-- Tab Content - Use v-show instead of v-if for better performance -->
        <div class="tab-content-wrapper">
          <!-- Media Library Tab -->
          <MediaLibraryTab
            v-show="activeTab === 'library'"
            :multiple="multiple"
            :max-selection="maxSelection"
            :filter-type="filterType"
            :selected-media="localSelectedMedia"
            :is-visible="activeTab === 'library'"
            :media-category="mediaCategory"
            @update:selected="localSelectedMedia = $event"
            @clear-selection="clearLocalSelection"
          />

          <!-- Upload Tab -->
          <MediaUploadTab
            v-show="activeTab === 'upload'"
            :media-category="mediaCategory"
            @upload-success="handleUploadSuccess"
          />
        </div>
      </div>
    </VCardText>

    <!-- Actions -->
    <template #actions>
      <VSpacer />
      <VBtn variant="text" @click="closeModal"> Cancel </VBtn>
      <ActionButton
        v-if="activeTab === 'library'"
        :label="
          multiple
            ? `Insert ${localSelectedMedia.length} File(s)`
            : 'Insert File'
        "
        icon="bx-check"
        color="primary"
        :disabled="localSelectedMedia.length === 0"
        @click="confirmSelection"
      />
    </template>
  </ReusableDialog>
</template>

<script setup>
import ActionButton from "@/components/ActionButton.vue";
import MediaLibraryTab from "@/components/MediaLibraryTab.vue";
import MediaUploadTab from "@/components/MediaUploadTab.vue";
import ReusableDialog from "@/components/ReusableDialog.vue";
import { useAuthStore } from "@/stores/authStore";
import { storeToRefs } from "pinia";
import { useToast } from "primevue/usetoast";
import { computed, nextTick, ref, watch } from "vue";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
  maxSelection: {
    type: Number,
    default: null,
  },
  filterType: {
    type: String,
    default: "all",
  },
  preselected: {
    type: Array,
    default: () => [],
  },
  mediaCategory: {
    type: String,
    default: null,
  },
});

const emit = defineEmits(["update:modelValue", "select"]);
const toast = useToast();
const authStore = useAuthStore();
const { user } = storeToRefs(authStore);

const isSuperAdmin = computed(() => user.value?.data?.role === "super_admin");
const canShowUploadTab = computed(() => {
  const category = props.mediaCategory || "";

  // Categories that only super admin can upload to.
  // Franchisees may pick from existing assets but cannot add new ones.
  if (
    category === "home_banner" ||
    category.startsWith("programlogo-") ||
    category.startsWith("activitylogo-")
  ) {
    return isSuperAdmin.value;
  }

  return true;
});

const activeTab = ref("library");
const localSelectedMedia = ref([]);

const isVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

watch(isVisible, (newVal) => {
  if (newVal) {
    activeTab.value = "library";

    // Use nextTick for smooth rendering
    nextTick(() => {
      if (props.preselected.length > 0) {
        localSelectedMedia.value = [...props.preselected];
      } else {
        localSelectedMedia.value = [];
      }
    });
  }
});

const clearLocalSelection = () => {
  localSelectedMedia.value = [];
};

const confirmSelection = () => {
  if (localSelectedMedia.value.length > 0) {
    emit(
      "select",
      props.multiple ? localSelectedMedia.value : localSelectedMedia.value[0],
    );
    closeModal();
  }
};

const handleUploadSuccess = () => {
  activeTab.value = "library";
};

const closeModal = () => {
  isVisible.value = false;
  setTimeout(() => {
    localSelectedMedia.value = [];
    activeTab.value = "library";
  }, 300);
};
</script>

<style scoped>
.media-picker-container {
  display: flex;
  flex-direction: column;
}

/* Tab wrapper with proper spacing */
.tabs-wrapper {
  flex-shrink: 0;
  padding: 16px 24px 12px 24px;
  background-color: rgb(var(--v-theme-surface));
}

/* Tab content wrapper - optimized for smooth scrolling */
.tab-content-wrapper {
  display: flex;
  flex-direction: column;
  position: relative;
  /* Enable GPU acceleration for smooth scrolling */
  transform: translateZ(0);
  will-change: transform;
}

/* Tab pill styling */
:deep(.v-tabs-pill .v-tab) {
  border-radius: 8px;
  text-transform: none;
  font-weight: 500;
  letter-spacing: normal;
}

:deep(.v-tabs-pill .v-tab--selected) {
  background-color: rgba(var(--v-theme-primary), 0.1);
}
</style>
