<!-- components/MediaCard.vue -->
<template>
  <VCard
    class="media-card"
    :class="{ selected: selected }"
    @click="$emit('click')"
  >
    <!-- Selection Checkbox -->

    <!-- Media Thumbnail -->
    <div class="media-thumbnail">
      <!-- Image -->
      <img
        v-if="
          item.type?.startsWith('image/') ||
          item.type === 'image' ||
          item.file_type === 'image'
        "
        :src="item.publicUrl || item.url"
        :alt="item.originalName || item.filename"
        @error="handleImageError"
      />

      <!-- Video -->
      <div
        v-else-if="
          item.type?.startsWith('video/') ||
          item.type === 'video' ||
          item.file_type === 'video'
        "
        class="video-thumbnail"
      >
        <img
          v-if="item.thumbnail_url"
          :src="item.thumbnail_url"
          :alt="item.originalName || item.filename"
          @error="handleImageError"
        />
        <div v-else class="video-placeholder">
          <VIcon size="48" color="white">bx-video</VIcon>
        </div>
        <div class="video-overlay">
          <VIcon size="40" color="white">bx-play-circle</VIcon>
        </div>
        <VChip
          v-if="item.duration"
          class="duration-chip"
          size="x-small"
          color="black"
        >
          {{ formatDuration(item.duration) }}
        </VChip>
      </div>

      <!-- File Type Badge -->
      <VChip
        class="type-badge"
        size="x-small"
        variant="elevated"
        :color="
          item.type?.startsWith('image/') || item.type === 'image'
            ? 'success'
            : 'info'
        "
      >
        {{ getFileTypeLabel(item.type) }}
      </VChip>
    </div>

    <!-- Media Info -->
    <VCardText class="pa-3">
      <div class="filename text-body-2 font-weight-medium mb-1">
        {{ truncate(item.filename || item.originalName || item.fileName, 30) }}
      </div>
      <div class="d-flex justify-space-between align-center">
        <span class="text-caption text-medium-emphasis">
          {{ item.file_size || item.size || formatFileSize(item.file_size) }}
        </span>
        <span class="text-caption text-medium-emphasis">
          {{ formatDate(item.created_at || item.createdAt) }}
        </span>
      </div>
    </VCardText>

    <!-- Action Buttons -->
    <VCardActions class="pa-2 actions-overlay">
      <VBtn
        icon
        size="small"
        color="info"
        variant="flat"
        @click.stop="$emit('click')"
      >
        <VIcon>bx-show</VIcon>
        <VTooltip activator="parent" location="top">Preview</VTooltip>
      </VBtn>

      <VBtn
        icon
        size="small"
        color="error"
        variant="flat"
        @click.stop="showConfirm = true"
      >
        <VIcon>bx-trash</VIcon>
        <VTooltip activator="parent" location="top">Delete</VTooltip>
      </VBtn>

      <VSpacer />
    </VCardActions>
    <!-- Delete Confirmation -->
    <ConfirmationDialog
      v-model:visible="showConfirm"
      title="Delete Media"
      message="Are you sure you want to delete this item? This action cannot be undone."
      confirm-color="error"
      @confirm="confirmDeletion"
    />
  </VCard>
</template>

<script setup>
import { ref } from "vue";
import ConfirmationDialog from "@/components/ConfirmationDialog.vue";
import { useMediaStore } from "@/stores/mediaStoreDirect";

const props = defineProps({
  item: {
    type: Object,
    required: true,
  },
  selected: {
    type: Boolean,
    default: false,
  },
});

defineEmits(["click", "select", "edit", "delete"]);

const showConfirm = ref(false);
const mediaStore = useMediaStore();

const truncate = (str, length) => {
  if (!str) return "";
  return str.length > length ? str.substring(0, length) + "..." : str;
};

const formatFileSize = (bytes) => {
  if (!bytes) return "0 B";
  if (bytes < 1024) return bytes + " B";
  if (bytes < 1048576) return (bytes / 1024).toFixed(1) + " KB";
  if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + " MB";
  return (bytes / 1073741824).toFixed(1) + " GB";
};

const formatDate = (date) => {
  if (!date) return "";
  const d = new Date(date);
  return d.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
};

const formatDuration = (seconds) => {
  if (!seconds) return "0:00";
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins}:${secs.toString().padStart(2, "0")}`;
};

const getFileTypeLabel = (mimeType) => {
  if (!mimeType) return "FILE";

  // Handle both "image/jpeg" and "image" formats
  if (mimeType.startsWith("image/")) {
    return mimeType.split("/")[1].toUpperCase();
  } else if (mimeType === "image") {
    return "IMAGE";
  } else if (mimeType.startsWith("video/")) {
    return "VIDEO";
  } else if (mimeType === "video") {
    return "VIDEO";
  }
  return "FILE";
};

const handleImageError = (e) => {
  e.target.src = "/placeholder-image.png"; // Add your placeholder image
};
// Confirm and delete
const confirmDeletion = async () => {
  try {
    await mediaStore.deleteMedia(props.item.id);
    // Toast is now handled by the store
  } catch (err) {
    // Error toast is handled by the store
    console.error("Delete error:", err);
  } finally {
    showConfirm.value = false;
  }
};
</script>

<style scoped>
.media-card {
  position: relative;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid rgba(var(--v-theme-on-surface), 0.12);
  border-radius: 12px;
  overflow: hidden;
  background: rgb(var(--v-theme-surface));
}

.media-card:hover {
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
  transform: translateY(-4px);
  border-color: rgba(var(--v-theme-on-surface), 0.2);
}

.media-card.selected {
  border-color: rgb(var(--v-theme-primary));
  box-shadow: 0 0 0 4px rgba(var(--v-theme-primary), 0.1);
}

.selection-checkbox {
  position: absolute;
  top: 8px;
  left: 8px;
  z-index: 2;
  background: rgba(var(--v-theme-surface), 0.9);
  border-radius: 4px;
  padding: 2px;
}

.media-thumbnail {
  position: relative;
  aspect-ratio: 1;
  overflow: hidden;
  background: rgba(var(--v-theme-on-surface), 0.05);
}

.media-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.media-card:hover .media-thumbnail img {
  transform: scale(1.05);
}

.video-thumbnail {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.video-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0.8;
  transition: opacity 0.2s;
}

.media-card:hover .video-overlay {
  opacity: 1;
}

.duration-chip {
  position: absolute;
  bottom: 8px;
  right: 8px;
  font-weight: 600;
}

.type-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  text-transform: uppercase;
  font-weight: 600;
}

.filename {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.actions-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(var(--v-theme-surface), 0.85);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  border-top: 1px solid rgba(var(--v-theme-on-surface), 0.1);
  opacity: 0;
  transition: all 0.3s ease;
  padding: 8px 12px !important;
  transform: translateY(100%);
}

.media-card:hover .actions-overlay {
  opacity: 1;
  transform: translateY(0);
}
</style>
