<template>
  <div v-if="isOpen"
    class="text-D pt-serif-regular-italic fixed inset-0 bg-black/75 flex items-center justify-center z-[9999]">
    <div class="bg-white w-[1224px] h-[528px] rounded-md shadow-lg relative overflow-hidden">
      <div class="bg-yellow-500 h-8 w-full">
        <div class="bg-D h-6 w-full"></div>
      </div>

      <div class="p-6 text-sm flex flex-col h-full relative">
        <div class="relative flex items-center justify-between top-0 pb-1 mb-2">
          <div class="flex flex-col gap-2 -mt-5">
            <p class="flex items-center gap-2">
              <i class="fab fa-instagram text-pink-600 text-xl"></i> tokomas_Jakartacitayam
            </p>
            <p class="flex items-center gap-2">
              <i class="fab fa-tiktok text-black text-xl"></i> tokomas_Jakartacitayam
            </p>
            <p class="flex items-center gap-2">
              <i class="fab fa-whatsapp text-green-500 text-xl"></i> 08158851178
            </p>
            <p class=" text-sm">{{ transaksi.kode_transaksi || 'N/A' }}</p>
          </div>

          <div class="absolute inset-x-0 top-[-48px] flex flex-col items-center">
            <img :src="logo" alt="Logo" class="h-40" />
          </div>

          <div class="grid grid-cols-[130px_1fr] gap-y-1 text-xs items-center -mt-5 relative z-10">
            <div class="text-right font-semibold pr-3">Tanggal :</div>
            <p class="text-left pl-2">{{ formatDate(transaksi.created_at) }}</p>

            <div class="text-right font-semibold pr-3">Nama :</div>
            <p class="text-left pl-2">{{ transaksi.nama_pembeli || '-' }}</p>

            <div class="text-right font-semibold pr-3">Alamat :</div>
            <p class="text-left pl-2">{{ transaksi.alamat || '-' }}</p>

            <div class="text-right font-semibold pr-3">No.Hp :</div>
            <p class="text-left pl-2">{{ transaksi.no_hp || '-' }}</p>
          </div>
        </div>

        <div class="flex mb-1 gap-179">
          <div class="flex gap-4">
            <img :src="logo_bca" alt="Logo_bca" class="h-5" />
            <img :src="logo_bri" alt="Logo_bri" class="h-5" />
            <img :src="logo_bni" alt="Logo_bni" class="h-5" />
          </div>
          <div class="flex gap-4">
            <img :src="logo_mastercard" alt="Logo_mastercard" class="h-5" />
            <img :src="logo_visa" alt="Logo_visa" class="h-5" />
            <img :src="logo_mandiri" alt="Logo_mandiri" class="h-5" />
          </div>
        </div>

        <table class="w-full border-D text-sm table-fixed border-b">
          <thead>
            <tr class="border-b border-t border-D">
              <th class="w-[40px] border-r text-lg border-D">Jml</th>
              <th class="w-[360px] py-2 text-lg border-r border-D">Item</th>
              <th class="w-[70px] border-r text-lg border-D">Posisi</th>
              <th class="w-[40px] border-r text-lg border-D">Berat</th>
              <th class="w-[40px] border-r text-lg border-D">Kadar</th>
              <th class="w-[240px] text-lg">Harga</th>
            </tr>
          </thead>

          <tbody>
            <tr v-for="(item, index) in itemsWithMinimal" :key="index" class="text-center">
              <td class="border-r border-D">
                <span v-if="item.harga_deal && item.harga_deal > 0">1</span>
              </td>
              <td class="flex items-center gap-2 p-2 border-r border-D">
                <template v-if="item.produk?.foto?.[0]?.url">
                  <img :src="item.produk.foto[0].url" class="w-12 h-12 object-cover rounded" />
                </template>
                <template v-else-if="item.produk?.nama">
                  <div class="w-12 h-12 bg-gray-200 rounded flex items-center justify-center">
                    <span class="text-xs text-gray-500">IMG</span>
                  </div>
                </template>
                <template v-else>
                  <div class="w-12 h-12"></div>
                </template>
                <span class="text-left">{{ item.produk?.nama || '' }}</span>
              </td>
              <td class="border-r border-D">
                <span v-if="item.produk?.nama">{{ item.posisi_asal || 'Brankas' }}</span>
              </td>
              <td class="border-r border-D">
                <span v-if="item.produk?.berat">{{ formatNumber(item.produk.berat) }}g</span>
              </td>
              <td class="border-r border-D">
                <span v-if="item.produk?.kadar">{{ item.produk.kadar }}k</span>
              </td>
              <td>
                <span v-if="item.harga_deal && item.harga_deal > 0">
                  Rp{{ formatNumber(item.harga_deal) }}
                </span>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- Bagian bawah -->
        <div class="flex text-sm mt-2">
          <!-- PERHATIAN -->
          <div class="w-[40%] p-2 text-left">
            <p class="font-semibold">PERHATIAN</p>
            <ol class="list-decimal ml-4 text-xs space-y-1">
              <li>Berat barang telah ditimbang dan disaksikan oleh pembeli.</li>
              <li>Barang yang dikembalikan menurut harga pasaran dan dipotong ongkos bikin, barang rusak
                lain harga.</li>
              <li>Barang yang sudah dibeli berarti sudah diperiksa dan disetujui.</li>
              <li class="text-red-500">Surat ini harap dibawa pada saat menjual kembali.</li>
            </ol>
          </div>

          <!-- SALES -->
          <div class="w-[20%] p-2 flex flex-col items-center justify-center">
            <p><strong>Hormat Kami</strong></p>
            <div class="mt-16 text-sm text-center">
              <p class="font-semibold">{{ transaksi.nama_sales || '-' }}</p>
            </div>
          </div>

          <!-- ONGKOS & TOTAL -->
          <div class="ml-auto w-[25%] p-2 flex flex-col justify-between">
            <div class="space-y-4">
              <!-- Ongkos bikin -->
              <div class="flex items-start justify-between">
                <div class="flex flex-col">
                  <p class="font-semibold">Ongkos bikin</p>
                  <p class="text-red-500 text-xs">diluar harga jual</p>
                </div>
                <div class="flex items-center w-40">
                  <p>Rp</p>
                  <p class="px-2 text-left text-sm w-full">
                    {{ (transaksi.ongkos_bikin || 0).toLocaleString() }},-
                  </p>
                </div>
              </div>

              <!-- Total -->
              <div class="flex items-center justify-between -mt-4">
                <p class="font-semibold">Total Harga</p>
                <div class="flex items-center w-40">
                  <p>Rp</p>
                  <p class="px-3 pl-2 py-1 text-left text-sm w-full">
                    {{ (transaksi.total_harga || 0).toLocaleString() }},-
                  </p>
                </div>
              </div>
            </div>

            <!-- Tombol -->
            <div class="flex justify-end gap-2 mt-4">
              <button @click="$emit('close')" class="bg-gray-400 text-white px-6 py-2 rounded">
                Tutup
              </button>
              <button @click="handlePrint" class="bg-blue-500 text-white px-6 py-2 rounded">
                Print
              </button>
            </div>
          </div>
        </div>
      </div>

      <p class="absolute p-8 bottom-0 left-0 w-full text-left text-xs bg-D text-white py-1">
        Terima kasih sudah berbelanja dengan kami
      </p>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import logo from '@/../images/logo.png'
import logo_bca from '@/../images/logo_bca.png'
import logo_bri from '@/../images/logo_bri.png'
import logo_bni from '@/../images/logo_bni.png'
import logo_mastercard from '@/../images/logo_mastercard.png'
import logo_visa from '@/../images/logo_visa.png'
import logo_mandiri from '@/../images/logo_mandiri.png'

const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false,
  },
  transaksi: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['close'])

// Format tanggal sesuai dengan format yang ada
const formatDate = (dateString) => {
  if (!dateString) return '-'

  const days = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu']
  const months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']

  const date = new Date(dateString)
  const dayName = days[date.getDay()]
  const day = String(date.getDate()).padStart(2, '0')
  const month = months[date.getMonth()]
  const year = date.getFullYear()

  return `${dayName}/${day}-${month}-${year}`
}

// Menambahkan minimal 2 baris untuk tampilan yang konsisten
const itemsWithMinimal = computed(() => {
  console.log('Transaksi data in StrukView:', props.transaksi)

  // Coba berbagai kemungkinan nama field
  const items = props.transaksi.itemTransaksi ||
                props.transaksi.items ||
                props.transaksi.item_transaksi ||
                []

  console.log('Items found:', items)

  const arr = [...items]

  // Pastikan minimal ada 2 baris untuk tampilan yang rapi
  while (arr.length < 2) {
    arr.push({ produk: {}, harga_deal: 0, posisi_asal: '' })
  }

  return arr
})

// Fungsi print (bisa dikembangkan lebih lanjut)
const handlePrint = () => {
  window.print()
}

// Format number helper
const formatNumber = (number) => {
  if (!number) return 0
  return parseFloat(number).toLocaleString('id-ID')
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=PT+Serif:ital,wght@0,400;0,700;1,400;1,700&display=swap');

.pt-serif-regular-italic {
  font-family: "PT Serif", serif;
  font-weight: 400;
}

/* Print styles */
@media print {
  .fixed {
    position: static !important;
  }

  .bg-black\/75 {
    background: none !important;
  }

  button {
    display: none !important;
  }
}
</style>
