<!-- components/MediaLibraryTab.vue -->
<template>
  <div class="media-library-tab">
    <!-- Fixed Toolbar -->
    <div class="toolbar-section">
      <VRow class="px-6 py-3" align="center" no-gutters>
        <!-- Search -->
        <VCol cols="12" md="4">
          <VTextField
            v-model="filters.search"
            placeholder="Search media..."
            prepend-inner-icon="bx-search"
            density="comfortable"
            variant="outlined"
            hide-details
            clearable
            class="picker-toolbar-input"
            @update:model-value="debounceSearch"
          />
        </VCol>

        <!-- Filter by Type -->
        <VCol cols="6" md="3" class="pl-md-2">
          <VSelect
            v-model="filters.type"
            :items="typeOptions"
            item-title="label"
            item-value="value"
            density="comfortable"
            variant="outlined"
            hide-details
            class="picker-toolbar-input"
            @update:model-value="handleFilterChange"
          />
        </VCol>

        <!-- Filter by Category -->
        <VCol v-if="!props.mediaCategory" cols="6" md="3" class="pl-md-2">
          <VSelect
            v-model="filters.mediaCategory"
            :items="categoryOptions"
            item-title="label"
            item-value="value"
            density="comfortable"
            variant="outlined"
            hide-details
            class="picker-toolbar-input"
            @update:model-value="handleFilterChange"
          />
        </VCol>

        <!-- Selection Info -->
        <VCol cols="12" md="2" class="text-right pl-2">
          <VChip
            v-if="selectedMedia.length > 0"
            color="primary"
            variant="flat"
            prepend-icon="bx-check-circle"
          >
            {{ selectedMedia.length }} selected
            <VBtn
              icon
              size="x-small"
              variant="text"
              class="ml-2"
              @click="$emit('clear-selection')"
            >
              <VIcon size="16">bx-x</VIcon>
            </VBtn>
          </VChip>
        </VCol>
      </VRow>

      <VDivider class="mt-3" />
    </div>

    <!-- Scrollable Content Area -->
    <div class="media-content-scroll">
      <!-- Professional Loading State -->
      <div v-if="loading" class="media-grid-container px-6 py-4">
        <VRow>
          <VCol
            v-for="n in 8"
            :key="n"
            cols="6"
            sm="4"
            md="3"
          >
            <div class="skeleton-card">
              <div class="skeleton-img"></div>
              <div class="skeleton-text-content">
                <div class="skeleton-line w-75"></div>
              </div>
            </div>
          </VCol>
        </VRow>
      </div>

      <!-- Empty State -->
      <div
        v-else-if="filteredMedia.length === 0"
        class="empty-state-container mx-6 mt-6"
      >
        <div class="empty-state-icon-wrapper">
          <VIcon size="56" color="primary">bx-image-add</VIcon>
        </div>
        <h3 class="empty-state-title">No media files found</h3>
        <p class="empty-state-subtitle">
          {{
            filters.search
              ? "Try a different search term"
              : "No media available in the library"
          }}
        </p>
      </div>

      <!-- Media Grid -->
      <div v-else class="media-grid-container px-6 py-4">
        <VRow>
          <VCol
            v-for="item in filteredMedia"
            :key="item.id"
            cols="6"
            sm="4"
            md="3"
          >
            <MediaPickerCard
              :item="item"
              :selected="isSelected(item)"
              :multiple="multiple"
              @select="handleSelection(item)"
            />
          </VCol>
        </VRow>
      </div>
    </div>

    <!-- Fixed Pagination -->
    <div v-if="pagination.lastPage > 1" class="pagination-section">
      <VDivider />
      <div class="px-6 py-3">
        <VPagination
          v-model="pagination.page"
          :length="pagination.lastPage"
          :total-visible="5"
          size="small"
          @update:model-value="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { storeToRefs } from "pinia";
import { useMediaStore } from "@/stores/mediaStoreDirect";
import { useToast } from "primevue/usetoast";
import MediaPickerCard from "@/components/MediaPickerCard.vue";

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

const emit = defineEmits(["update:selected", "clear-selection"]);

const mediaStore = useMediaStore();
const { media, loading, pagination } = storeToRefs(mediaStore);
const { fetchMedia, setFilter } = mediaStore;
const toast = useToast();

const filters = ref({
  search: "",
  type: props.filterType,
  mediaCategory: props.mediaCategory,
});

const typeOptions = [
  { label: "All Media", value: "all" },
  { label: "Images Only", value: "image" },
  { label: "Videos Only", value: "video" },
];

const categoryOptions = [
  { label: "All Categories", value: null },
  { label: "Teacher", value: "teacher" },
  { label: "Logo", value: "logo" },
  { label: "Program", value: "program" },
  { label: "Page", value: "pages" },
  { label: "Home Banner", value: "home_banner" },
];

const filteredMedia = computed(() => {
  let filtered = [...media.value];

  if (filters.value.search) {
    const searchTerm = filters.value.search.toLowerCase();
    filtered = filtered.filter((item) =>
      item.filename?.toLowerCase().includes(searchTerm),
    );
  }

  if (filters.value.type !== "all") {
    filtered = filtered.filter((item) => {
      if (filters.value.type === "image") {
        return (
          item.type?.startsWith("image") ||
          item.type === "image" ||
          item.filename?.toLowerCase().endsWith(".svg")
        );
      } else if (filters.value.type === "video") {
        return item.type?.startsWith("video") || item.type === "video";
      }
      return true;
    });
  }

  return filtered;
});

const isSelected = (item) => {
  return props.selectedMedia.some((m) => m.id === item.id);
};

const handleSelection = (item) => {
  const currentSelection = [...props.selectedMedia];
  const index = currentSelection.findIndex((m) => m.id === item.id);

  if (index !== -1) {
    currentSelection.splice(index, 1);
  } else {
    if (!props.multiple) {
      emit("update:selected", [item]);
      return;
    } else {
      if (props.maxSelection && currentSelection.length >= props.maxSelection) {
        toast.add({
          severity: "warning",
          summary: "Selection Limit",
          detail: `You can only select up to ${props.maxSelection} files`,
          life: 3000,
        });
        return;
      }
      currentSelection.push(item);
    }
  }

  emit("update:selected", currentSelection);
};

const handlePageChange = (page) => {
  fetchMedia(page);
};

let searchTimeout = null;
const debounceSearch = () => {
  clearTimeout(searchTimeout);
  searchTimeout = setTimeout(() => {
    fetchMedia(1);
  }, 500);
};

const handleFilterChange = () => {
  setFilter("type", filters.value.type);
  setFilter("mediaCategory", filters.value.mediaCategory);
};

// Watch for mediaCategory prop changes
watch(
  () => props.mediaCategory,
  (newVal) => {
    if (newVal !== null) {
      filters.value.mediaCategory = newVal;
      setFilter("mediaCategory", newVal);
    }
  },
  { immediate: true },
);

onMounted(() => {
  if (media.value.length === 0) {
    fetchMedia();
  }
});
</script>

<style scoped>
.media-library-tab {
  display: flex;
  flex-direction: column;
  width: 100%;
  background-color: rgb(var(--v-theme-surface));
  height: 100%;
}

.toolbar-section {
  flex-shrink: 0;
  background-color: rgb(var(--v-theme-surface));
  border-bottom: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
  z-index: 10;
}

:deep(.picker-toolbar-input .v-field) {
  border-radius: 10px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

.media-content-scroll {
  width: 100%;
  padding-top: 8px;
}

.media-grid-container {
  width: 100%;
}

.pagination-section {
  flex-shrink: 0;
  background-color: rgb(var(--v-theme-surface));
  border-top: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
}

/* Empty State */
.empty-state-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4rem 2rem;
  text-align: center;
  background: rgb(var(--v-theme-surface));
  border-radius: 16px;
  border: 1px dashed rgba(var(--v-border-color), var(--v-border-opacity));
}

.empty-state-icon-wrapper {
  width: 80px;
  height: 80px;
  background: rgba(var(--v-theme-primary), 0.1);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 1.25rem;
}

.empty-state-title {
  font-size: 1.25rem;
  font-weight: 700;
  color: rgb(var(--v-theme-on-surface));
  margin: 0 0 0.5rem 0;
}

.empty-state-subtitle {
  color: rgba(var(--v-theme-on-surface), 0.7);
  font-size: 0.95rem;
  margin: 0;
}

/* Skeleton Loading */
.skeleton-card {
  background: rgb(var(--v-theme-surface));
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
  height: 100%;
}

.skeleton-img {
  width: 100%;
  aspect-ratio: 1;
  background: rgba(var(--v-theme-on-surface), 0.12);
  animation: pulse 1.5s infinite;
}

.skeleton-text-content {
  padding: 12px;
}

.skeleton-line {
  height: 12px;
  background: rgba(var(--v-theme-on-surface), 0.12);
  border-radius: 6px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

/* Hide VRow's internal scrollbar if any */
:deep(.v-row) {
  overflow: visible;
}
</style>
