<template>
  <Modal :active="isOpen" size="md" @close="handleClose" clickOutside="false">
    <div class="p-6">
      <h3 class="text-lg font-semibold text-gray-900 mb-4">Item {{ product?.nama }}</h3>
      
      <div v-if="!success">
        <div class="mb-4">
          <p class="text-gray-600 mb-4">Produk "<strong>{{ product?.nama }}</strong>" berhasil dibuat!</p>
          
          <div class="mb-4">
            <label class="block text-gray-700 mb-2">Pilih Nampan</label>
            <select 
              v-model="selectedNampan" 
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              :disabled="loading"
            >
              <option value="">Brankas</option>
              <option v-for="nampan in nampanList" :key="nampan.id" :value="nampan.id">
                {{ nampan.nama }} ({{ nampan.items_count }} items)
              </option>
            </select>
          </div>
        </div>

        <div class="flex justify-end gap-3">
          <button 
            @click="handleClose" 
            :disabled="loading"
            class="px-4 py-2 text-gray-600 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50"
          >
            Batal
          </button>
          <button 
            @click="createItem" 
            :disabled="loading"
            class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors disabled:bg-blue-400 disabled:cursor-not-allowed flex items-center gap-2"
          >
            <svg v-if="loading" class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            {{ loading ? 'Membuat...' : 'Buat Item' }}
          </button>
        </div>
      </div>

      <!-- Success State -->
      <div v-else>
        <div class="text-center">
          <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <!-- QR CODe HERE -->
          </div>
          
          <h4 class="text-lg font-semibold text-gray-900 mb-2">Item Berhasil Dibuat!</h4>
          <p class="text-gray-600 mb-6">
            Item dari produk "<strong>{{ product?.nama }}</strong>" telah ditambahkan ke {{ selectedNampanName }}.
          </p>

          <div class="flex flex-row justify-between gap-3">
            <button 
              @click="$emit('finish')"
              class="flex-1 px-6 py-2 bg-gray-400 hover:bg-gray-500 text-white rounded-lg transition-colors"
            >
              Selesai
            </button>
            <button 
              @click="$emit('print')"
              class="flex-1 px-6 py-2 bg-C hover:bg-B text-D rounded-lg transition-colors opacity-50 cursor-not-allowed"
              disabled
            >
              Print
            </button>
            <button 
              @click="addNewItem"
              class="flex-1 px-6 py-2 bg-C hover:bg-B text-D rounded-lg transition-colors"
            >
              Tambah Item Baru
            </button>
          </div>
        </div>
      </div>
    </div>
  </Modal>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import axios from 'axios';
import Modal from './Modal.vue';

// Props
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  product: {
    type: Object,
    default: null
  }
});

const emit = defineEmits(['close', 'finish', 'print', 'item-created']);

const selectedNampan = ref('');
const nampanList = ref([]);
const success = ref(false);
const loading = ref(false);

const selectedNampanName = computed(() => {
  if (!selectedNampan.value) return 'Brankas';
  const nampan = nampanList.value.find(n => n.id === selectedNampan.value);
  return nampan ? nampan.nama : 'Brankas';
});

// Methods
const loadNampanList = async () => {
  try {
    const response = await axios.get('/api/nampan');
    nampanList.value = response.data;
  } catch (error) {
    console.error('Error loading nampan list:', error);
  }
};

const createItem = async () => {
  if (!props.product) return;
  
  loading.value = true;
  
  try {
    const payload = {
      id_produk: props.product.id
    };
    
    if (selectedNampan.value) {
      payload.id_nampan = selectedNampan.value;
    }
    
    const response = await axios.post('/api/item', payload);
    
    success.value = true;
    emit('item-created', {
      item: response.data,
      product: props.product,
      nampan: selectedNampanName.value
    });
  } catch (error) {
    console.error('Error creating item:', error);
    alert('Gagal membuat item: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

const addNewItem = () => {
  // Reset state untuk item baru
  success.value = false;
  selectedNampan.value = '';
  
  // Emit event untuk membuat item baru
  emit('item-created', {
    newItem: true,
    product: props.product
  });
};

const handleClose = () => {
  // Reset state
  selectedNampan.value = '';
  success.value = false;
  loading.value = false;
  
  emit('close');
};

// Watchers
watch(() => props.isOpen, (newValue) => {
  if (newValue) {
    selectedNampan.value = '';
    success.value = false;
    loading.value = false;
    
    loadNampanList();
  }
});
</script>