<template>
  <div class="space-y-8">
    <!-- Standalone Upload Area -->
    <div class="bg-card/40 border border-border/50 rounded-3xl p-8 backdrop-blur-md">
      <div class="flex flex-col md:flex-row items-center justify-between gap-6">
        <div class="flex items-center gap-4">
          <div class="w-12 h-12 bg-primary/10 rounded-2xl flex items-center justify-center text-primary">
            <ImagePlus class="w-6 h-6" />
          </div>
          <div>
            <h3 class="text-lg font-bold">{{ t("admin.portfolio.uploadTitle") }}</h3>
            <p class="text-xs text-muted-foreground">{{ t("admin.portfolio.uploadDesc") }}</p>
          </div>
        </div>
        <div class="flex flex-col sm:flex-row gap-3 w-full md:w-auto">
          <input 
            type="text" 
            v-model="newCaption" 
            :placeholder="t('admin.fields.caption')" 
            class="flex-1 md:w-64 bg-background/50 border border-border/50 rounded-xl px-4 py-2.5 text-sm outline-none focus:ring-2 ring-primary/20" 
          />
          <label class="cursor-pointer">
            <div class="bg-primary hover:bg-primary/90 text-primary-foreground px-6 py-2.5 rounded-xl text-sm font-bold shadow-glow transition-all flex items-center justify-center gap-2">
              <Upload class="w-4 h-4" /> {{ t("admin.actions.upload") }}
            </div>
            <input type="file" class="hidden" accept="image/*" @change="handleStandaloneUpload" />
          </label>
        </div>
      </div>
    </div>

    <!-- Items Grid -->
    <div v-if="portfolioItems.length === 0" class="flex flex-col items-center justify-center py-20 bg-card/40 border border-border/50 rounded-3xl opacity-50">
      <ImageIcon class="w-12 h-12 text-muted-foreground/20 mb-4" />
      <p class="text-sm text-muted-foreground">{{ t("admin.fields.noPortfolio") }}</p>
    </div>

    <div v-else class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6">
      <div v-for="pi in portfolioItems" :key="pi.id" 
           class="group relative bg-card/40 border border-border/50 rounded-3xl overflow-hidden hover:border-primary/30 transition-all shadow-lg flex flex-col h-full"
           :class="{ 'opacity-60 grayscale-[0.5]': !pi.is_public }">
        
        <!-- Image Area -->
        <div class="relative aspect-square overflow-hidden">
          <img :src="`${resourcesBaseUrl}/${pi.file_path}`" class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" />
          
          <!-- Quick Status Overlay -->
          <div class="absolute top-3 left-3 flex gap-2">
             <div v-if="!pi.is_public" class="bg-rose-500/80 backdrop-blur-md text-[9px] font-black uppercase text-white px-2 py-1 rounded-md shadow-lg flex items-center gap-1">
                <EyeOff class="w-2.5 h-2.5" /> {{ t('admin.labels.hidden') }}
             </div>
             <div class="bg-background/80 backdrop-blur-md text-[9px] font-black uppercase text-foreground/70 px-2 py-1 rounded-md shadow-lg border border-border/50">
                {{ pi.material_name || 'Showcase' }}
             </div>
          </div>

          <!-- Hover Controls -->
          <div class="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-all flex items-center justify-center gap-3">
             <button @click="toggleVisibility(pi)" class="w-10 h-10 rounded-full flex items-center justify-center transition-all border shadow-lg"
                     :class="pi.is_public ? 'bg-amber-500/20 hover:bg-amber-500 text-white border-amber-500/30' : 'bg-emerald-500/20 hover:bg-emerald-500 text-white border-emerald-500/30'">
                <component :is="pi.is_public ? EyeOff : Eye" class="w-5 h-5" />
             </button>
             <button @click="$emit('delete', pi.id)" class="w-10 h-10 bg-rose-500/20 hover:bg-rose-500 text-white rounded-full flex items-center justify-center transition-all border border-rose-500/30 shadow-lg">
               <Trash2 class="w-5 h-5" />
             </button>
          </div>
        </div>

        <!-- Meta Area -->
        <div class="p-4 flex-1 flex flex-col gap-3">
           <div class="flex-1">
              <div v-if="editingId === pi.id" class="space-y-2">
                 <textarea v-model="editCaption" class="w-full bg-background/50 border border-primary/30 rounded-xl px-3 py-2 text-xs outline-none focus:ring-2 ring-primary/10 resize-none h-16" />
                 <div class="flex gap-2">
                    <button @click="saveCaption(pi)" class="flex-1 bg-primary text-primary-foreground py-1.5 rounded-lg text-[10px] font-bold shadow-glow">{{ t('admin.actions.save') }}</button>
                    <button @click="editingId = null" class="px-3 bg-muted hover:bg-muted/80 py-1.5 rounded-lg text-[10px] font-bold">{{ t('admin.actions.cancel') }}</button>
                 </div>
              </div>
              <div v-else @click="startEdit(pi)" class="cursor-pointer group/text flex items-start justify-between gap-2">
                 <p class="text-xs text-muted-foreground leading-relaxed line-clamp-3 italic">
                    {{ pi.caption || t('admin.portfolio.noCaption') }}
                 </p>
                 <Edit3 class="w-3 h-3 text-muted-foreground/0 group-hover/text:text-primary transition-all mt-1" />
              </div>
           </div>
           
           <div v-if="pi.order_id" class="pt-3 border-t border-border/50 flex justify-between items-center">
              <span class="text-[9px] font-bold uppercase text-muted-foreground/50 tracking-tighter">Order #{{ pi.order_id }}</span>
              <span v-if="pi.first_name" class="text-[9px] font-medium text-muted-foreground/60">{{ pi.first_name }} {{ pi.last_name }}</span>
           </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { 
  Image as ImageIcon, Trash2, Eye, EyeOff, Edit3, 
  Plus, ImagePlus, Upload, Check, X 
} from "lucide-vue-next";
import { adminUpdatePhotoStatus, adminUploadPortfolioPhoto } from "@/lib/api";
import { toast } from "vue-sonner";

const { t } = useI18n();

const props = defineProps<{
  portfolioItems: any[];
  resourcesBaseUrl: string;
}>();

const emit = defineEmits(['delete', 'refresh']);

const newCaption = ref("");
const editingId = ref<number | null>(null);
const editCaption = ref("");

const handleStandaloneUpload = async (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0];
  if (!file) return;

  const toastId = toast.loading(t("admin.portfolio.uploading"));
  try {
    const fd = new FormData();
    fd.append("file", file);
    fd.append("caption", newCaption.value);
    fd.append("is_public", "true");
    
    await adminUploadPortfolioPhoto(fd);
    toast.success(t("admin.portfolio.uploadSuccess"), { id: toastId });
    newCaption.value = "";
    emit('refresh');
  } catch (err: any) {
    toast.error(err.message, { id: toastId });
  }
};

const toggleVisibility = async (item: any) => {
  try {
    await adminUpdatePhotoStatus(item.id, { 
      is_public: !item.is_public,
      caption: item.caption 
    });
    toast.success(t("admin.portfolio.statusUpdated"));
    emit('refresh');
  } catch (err: any) {
    toast.error(err.message);
  }
};

const startEdit = (item: any) => {
  editingId.value = item.id;
  editCaption.value = item.caption || "";
};

const saveCaption = async (item: any) => {
  try {
    await adminUpdatePhotoStatus(item.id, { 
      is_public: item.is_public,
      caption: editCaption.value 
    });
    toast.success(t("admin.portfolio.captionUpdated"));
    editingId.value = null;
    emit('refresh');
  } catch (err: any) {
    toast.error(err.message);
  }
};
</script>
