<template>
  <div class="flex h-full flex-col gap-4 rounded-3xl border border-slate-200 bg-white p-4 text-slate-900 dark:border-white/10 dark:bg-white/5 dark:text-white">
    <div class="flex items-center justify-between gap-2 text-xs uppercase tracking-[0.3em] text-slate-500 dark:text-slate-300">
      <span>Varianten</span>
      <button
        type="button"
        class="rounded-full border border-slate-200 p-1 text-slate-500 transition hover:border-rose-300 hover:text-rose-400 dark:border-white/20 dark:text-white/70 dark:hover:text-rose-300"
        @click="$emit('close')"
        aria-label="Auswahl schließen"
      >
        <font-awesome-icon :icon="['fas', 'xmark']" class="h-4 w-4" />
      </button>
    </div>

    <div class="flex-1 space-y-3 overflow-y-auto pr-1">
      <p v-if="isLoading" class="rounded-2xl border border-slate-200 bg-white px-4 py-3 text-center text-sm text-slate-500 dark:border-white/10 dark:bg-white/5 dark:text-slate-300">
        Stile werden geladen …
      </p>
      <p v-else-if="loadError" class="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-center text-sm text-rose-500 dark:border-rose-400/40 dark:bg-rose-500/10 dark:text-rose-100">
        {{ loadError }}
      </p>
      <template v-else>
        <div class="grid grid-cols-1 gap-3 md:grid-cols-2">
          <button
            v-for="style in styles"
            :key="style.id"
            type="button"
            class="group flex w-full items-center gap-4 rounded-2xl border border-slate-200 bg-white/90 p-3 text-left text-slate-900 transition hover:border-emerald-300 hover:bg-emerald-50/50 dark:border-white/10 dark:bg-white/5 dark:text-white"
            @click="selectStyle(style)"
          >
            <img
              v-if="style.preview_image"
              :src="buildPreviewPath(style.preview_image)"
              loading="lazy"
              class="h-24 w-24 flex-none rounded-2xl object-cover opacity-90 transition group-hover:opacity-100"
              alt="Style preview"
            />
            <div
              v-else
              class="flex h-24 w-24 flex-none items-center justify-center rounded-2xl border border-dashed border-slate-200 text-[0.65rem] uppercase tracking-[0.4em] text-slate-500 dark:border-white/20 dark:text-slate-400"
            >
              AI
            </div>
            <div class="flex flex-col">
              <p class="text-base font-semibold text-slate-900 dark:text-white">{{ style.title }}</p>
              <p class="text-sm text-slate-500 dark:text-slate-200">{{ style.description }}</p>
            </div>
          </button>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import { onMounted, ref, computed } from 'vue';

const styles = ref([]);
const isLoading = ref(true);
const loadError = ref(null);
const aiAvailable = ref(true);

const props = defineProps({
  image_id: {
    type: [Number, String],
    required: true,
  },
  allowAiStyles: {
    type: Boolean,
    default: true,
  },
  gallerySlug: {
    type: String,
    default: 'default',
  },
  aiAvailableOverride: {
    type: Boolean,
    default: null,
  },
});

const emits = defineEmits(['styleSelected', 'close']);

const fetchStyles = async () => {
  isLoading.value = true;
  loadError.value = null;

  try {
    if (!props.allowAiStyles) {
      aiAvailable.value = false;
      loadError.value = 'Stilwechsel ist für diese Galerie deaktiviert.';
      isLoading.value = false;
      return;
    }

    if (props.aiAvailableOverride !== null) {
      aiAvailable.value = props.aiAvailableOverride;
    } else {
      aiAvailable.value = true;
    }

    // Fetch styles only if AI is available
    const stylesResponse = await axios.get('/api/styles', {
      params: { gallery: props.gallerySlug },
    });

    const payload = Array.isArray(stylesResponse.data) ? stylesResponse.data : [];

    styles.value = payload.filter((style) => {
      if (! props.allowAiStyles) {
        return false;
      }

      const aiModel = style.ai_model || style.aiModel || {};
      const provider = aiModel.primary_api_provider || aiModel.api_provider || {};

      if (provider.enabled === false) {
        return false;
      }

      return aiModel && (provider || aiModel);
    });

  } catch (error) {
    console.error('Error fetching styles:', error);
    loadError.value = 'Stile konnten nicht geladen werden.';
  } finally {
    isLoading.value = false;
  }
};

const selectStyle = (style) => {
  emits('styleSelected', style, props.image_id);
};

const buildPreviewPath = (preview) => {
  if (! preview) {
    return '';
  }

  if (preview.startsWith('http://') || preview.startsWith('https://') || preview.startsWith('/')) {
    return preview;
  }

  return `/storage/${preview}`;
};

onMounted(() => {
  fetchStyles();
});
</script>
