<template>
  <div class="receipt-detail-view">
    <!-- Loading -->
    <div v-if="loading" class="loading-container">
      <ProgressSpinner />
    </div>

    <template v-else-if="receipt">
      <!-- Header Card -->
      <div class="roa-card">
        <div class="roa-card-header">
          <div>
            <h2 class="roa-card-title">
              <i class="pi pi-receipt"></i>
              Bon #{{ receipt.id }}
            </h2>
            <span :class="['status-badge', getStatusClass(receipt.status)]">
              {{ getStatusLabel(receipt.status) }}
            </span>
          </div>
          <div class="button-group">
            <Button
              label="Inapoi"
              icon="pi pi-arrow-left"
              severity="secondary"
              @click="$router.push('/')"
            />
            <Button
              v-if="receipt.status === 'draft'"
              label="Editeaza"
              icon="pi pi-pencil"
              @click="$router.push(`/receipt/${receipt.id}/edit`)"
            />
            <Button
              v-if="receipt.status === 'draft'"
              label="Trimite spre aprobare"
              icon="pi pi-send"
              severity="success"
              @click="submitReceipt"
              :loading="submitting"
            />
            <Button
              v-if="receipt.status === 'rejected'"
              label="Re-trimite"
              icon="pi pi-refresh"
              severity="warning"
              @click="resubmitReceipt"
              :loading="submitting"
            />
          </div>
        </div>

        <!-- Rejection Reason -->
        <div v-if="receipt.rejection_reason" class="rejection-alert">
          <i class="pi pi-exclamation-triangle"></i>
          <div>
            <strong>Motiv respingere:</strong>
            <p>{{ receipt.rejection_reason }}</p>
            <small>Respins de {{ receipt.reviewed_by }} la {{ formatDateTime(receipt.reviewed_at) }}</small>
          </div>
        </div>
      </div>

      <div class="detail-grid">
        <!-- Receipt Details -->
        <div class="roa-card">
          <h3>
            <i class="pi pi-info-circle"></i>
            Detalii Bon
          </h3>

          <div class="detail-list">
            <div class="detail-item">
              <span class="label">Tip Document</span>
              <span class="value">
                {{ receipt.receipt_type === 'bon_fiscal' ? 'Bon Fiscal' : 'Chitanta' }}
              </span>
            </div>
            <div class="detail-item">
              <span class="label">Directie</span>
              <span class="value">
                {{ receipt.direction === 'cheltuiala' ? 'Cheltuiala' : 'Incasare' }}
              </span>
            </div>
            <div class="detail-item">
              <span class="label">Data</span>
              <span class="value">{{ formatDate(receipt.receipt_date) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">Suma</span>
              <span class="value amount">{{ formatAmount(receipt.amount) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">Furnizor</span>
              <span class="value">{{ receipt.partner_name || '-' }}</span>
            </div>
            <div class="detail-item">
              <span class="label">Tip Cheltuiala</span>
              <span class="value">{{ getExpenseTypeName(receipt.expense_type_code) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">Casa/Banca</span>
              <span class="value">{{ receipt.cash_register_name || '-' }}</span>
            </div>
            <div class="detail-item" v-if="receipt.receipt_number">
              <span class="label">Numar Bon</span>
              <span class="value">{{ receipt.receipt_number }}</span>
            </div>
            <div class="detail-item" v-if="receipt.description">
              <span class="label">Descriere</span>
              <span class="value">{{ receipt.description }}</span>
            </div>
          </div>

          <!-- Detalii Suplimentare (TVA, items, address from OCR) -->
          <template v-if="hasTvaData || receipt.items_count || receipt.vendor_address">
            <Divider />

            <h4 style="margin-bottom: 0.75rem; color: #0284c7;">
              <i class="pi pi-list"></i>
              Detalii Suplimentare
            </h4>

            <div class="detail-list">
              <!-- TVA Breakdown -->
              <div v-if="parsedTvaBreakdown?.length > 0" class="detail-item tva-detail">
                <span class="label">TVA</span>
                <div class="tva-breakdown-display">
                  <div v-for="(entry, idx) in parsedTvaBreakdown" :key="idx" class="tva-line">
                    <span class="tva-code" v-if="entry.code">{{ entry.code }}:</span>
                    <span class="tva-percent">{{ entry.percent }}%</span>
                    <span class="tva-amount">= {{ formatAmount(entry.amount) }}</span>
                  </div>
                  <div v-if="receipt.tva_total && parsedTvaBreakdown.length > 1" class="tva-total-line">
                    <strong>Total TVA: {{ formatAmount(receipt.tva_total) }}</strong>
                  </div>
                </div>
              </div>

              <div class="detail-item" v-if="receipt.items_count">
                <span class="label">Nr. Articole</span>
                <span class="value">{{ receipt.items_count }} articole</span>
              </div>

              <div class="detail-item" v-if="receipt.vendor_address">
                <span class="label">Adresa Furnizor</span>
                <span class="value">{{ receipt.vendor_address }}</span>
              </div>
            </div>
          </template>

          <Divider />

          <div class="detail-list">
            <div class="detail-item">
              <span class="label">Creat de</span>
              <span class="value">{{ receipt.created_by }}</span>
            </div>
            <div class="detail-item">
              <span class="label">Creat la</span>
              <span class="value">{{ formatDateTime(receipt.created_at) }}</span>
            </div>
            <div class="detail-item" v-if="receipt.submitted_at">
              <span class="label">Trimis la</span>
              <span class="value">{{ formatDateTime(receipt.submitted_at) }}</span>
            </div>
            <div class="detail-item" v-if="receipt.reviewed_by">
              <span class="label">Revizuit de</span>
              <span class="value">{{ receipt.reviewed_by }}</span>
            </div>
            <div class="detail-item" v-if="receipt.reviewed_at">
              <span class="label">Revizuit la</span>
              <span class="value">{{ formatDateTime(receipt.reviewed_at) }}</span>
            </div>
          </div>
        </div>

        <!-- Attachments -->
        <div class="roa-card">
          <h3>
            <i class="pi pi-images"></i>
            Atasamente ({{ receipt.attachments?.length || 0 }})
          </h3>

          <div v-if="receipt.attachments?.length" class="attachments-grid">
            <div
              v-for="att in receipt.attachments"
              :key="att.id"
              class="attachment-item"
            >
              <template v-if="att.mime_type?.startsWith('image/')">
                <Image
                  :src="store.getAttachmentUrl(att.id)"
                  :alt="att.filename"
                  preview
                  class="attachment-image"
                />
              </template>
              <template v-else>
                <a
                  :href="store.getAttachmentUrl(att.id)"
                  target="_blank"
                  class="pdf-link"
                >
                  <i class="pi pi-file-pdf"></i>
                  {{ att.filename }}
                </a>
              </template>
            </div>
          </div>

          <div v-else class="empty-state">
            <i class="pi pi-image"></i>
            <p>Niciun atasament</p>
          </div>
        </div>
      </div>

      <!-- Accounting Entries -->
      <div class="roa-card">
        <h3>
          <i class="pi pi-book"></i>
          Note Contabile
        </h3>

        <div v-if="receipt.entries?.length" class="entries-table-container">
          <table class="entries-table">
            <thead>
              <tr>
                <th>Tip</th>
                <th>Cont</th>
                <th>Denumire Cont</th>
                <th style="text-align: right;">Suma</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="entry in receipt.entries" :key="entry.id">
                <td>
                  <Tag
                    :value="entry.entry_type === 'debit' ? 'D' : 'C'"
                    :severity="entry.entry_type === 'debit' ? 'danger' : 'success'"
                  />
                </td>
                <td>{{ entry.account_code }}</td>
                <td>{{ entry.account_name || '-' }}</td>
                <td :class="entry.entry_type" style="text-align: right;">
                  {{ formatAmount(entry.amount) }}
                </td>
              </tr>
            </tbody>
            <tfoot>
              <tr>
                <td colspan="3" style="text-align: right;"><strong>Total Debit:</strong></td>
                <td class="debit" style="text-align: right;">
                  <strong>{{ formatAmount(totalDebit) }}</strong>
                </td>
              </tr>
              <tr>
                <td colspan="3" style="text-align: right;"><strong>Total Credit:</strong></td>
                <td class="credit" style="text-align: right;">
                  <strong>{{ formatAmount(totalCredit) }}</strong>
                </td>
              </tr>
            </tfoot>
          </table>

          <div v-if="!isBalanced" class="balance-warning">
            <i class="pi pi-exclamation-triangle"></i>
            Atentie: Notele contabile nu sunt echilibrate!
          </div>
        </div>

        <div v-else class="empty-state">
          <i class="pi pi-book"></i>
          <p>Notele contabile vor fi generate la trimiterea spre aprobare</p>
        </div>
      </div>
    </template>

    <!-- Not Found -->
    <div v-else class="empty-state">
      <i class="pi pi-exclamation-circle"></i>
      <h3>Bonul nu a fost gasit</h3>
      <Button label="Inapoi la lista" @click="$router.push('/')" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useToast } from 'primevue/usetoast'
import { useReceiptsStore } from '../../stores/receiptsStore'
import { EXPENSE_TYPES } from '../../utils/constants'

const route = useRoute()
const router = useRouter()
const toast = useToast()
const store = useReceiptsStore()

const receipt = ref(null)
const loading = ref(true)
const submitting = ref(false)

const totalDebit = computed(() => {
  if (!receipt.value?.entries) return 0
  return receipt.value.entries
    .filter(e => e.entry_type === 'debit')
    .reduce((sum, e) => sum + parseFloat(e.amount), 0)
})

const totalCredit = computed(() => {
  if (!receipt.value?.entries) return 0
  return receipt.value.entries
    .filter(e => e.entry_type === 'credit')
    .reduce((sum, e) => sum + parseFloat(e.amount), 0)
})

const isBalanced = computed(() => {
  return Math.abs(totalDebit.value - totalCredit.value) < 0.01
})

const parsedTvaBreakdown = computed(() => {
  if (!receipt.value?.tva_breakdown) return []
  try {
    // Handle both string (JSON) and array formats
    return typeof receipt.value.tva_breakdown === 'string'
      ? JSON.parse(receipt.value.tva_breakdown)
      : receipt.value.tva_breakdown
  } catch {
    return []
  }
})

const hasTvaData = computed(() => {
  return parsedTvaBreakdown.value?.length > 0 || receipt.value?.tva_total
})

onMounted(async () => {
  await loadReceipt()
})

const loadReceipt = async () => {
  loading.value = true
  try {
    receipt.value = await store.fetchReceiptById(route.params.id)
  } catch (error) {
    toast.add({
      severity: 'error',
      summary: 'Eroare',
      detail: 'Nu s-a putut incarca bonul',
      life: 5000,
    })
  } finally {
    loading.value = false
  }
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('ro-RO')
}

const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('ro-RO')
}

const formatAmount = (amount) => {
  return new Intl.NumberFormat('ro-RO', {
    style: 'currency',
    currency: 'RON',
  }).format(amount)
}

const getStatusClass = (status) => {
  const classes = {
    draft: 'status-draft',
    pending_review: 'status-pending',
    approved: 'status-approved',
    rejected: 'status-rejected',
    synced: 'status-synced',
  }
  return classes[status] || ''
}

const getStatusLabel = (status) => {
  const labels = {
    draft: 'Ciorna',
    pending_review: 'In asteptare',
    approved: 'Aprobat',
    rejected: 'Respins',
    synced: 'Sincronizat',
  }
  return labels[status] || status
}

const getExpenseTypeName = (code) => {
  return EXPENSE_TYPES[code] || code || '-'
}

const submitReceipt = async () => {
  submitting.value = true
  try {
    const result = await store.submitReceipt(receipt.value.id)
    if (result.success) {
      toast.add({
        severity: 'success',
        summary: 'Succes',
        detail: 'Bonul a fost trimis spre aprobare',
        life: 3000,
      })
      await loadReceipt()
    } else {
      toast.add({
        severity: 'error',
        summary: 'Eroare',
        detail: result.message,
        life: 5000,
      })
    }
  } catch (error) {
    toast.add({
      severity: 'error',
      summary: 'Eroare',
      detail: error.message || 'Nu s-a putut trimite bonul',
      life: 5000,
    })
  } finally {
    submitting.value = false
  }
}

const resubmitReceipt = async () => {
  submitting.value = true
  try {
    const result = await store.resubmitReceipt(receipt.value.id)
    if (result.success) {
      toast.add({
        severity: 'success',
        summary: 'Succes',
        detail: 'Bonul a fost re-trimis spre aprobare',
        life: 3000,
      })
      await loadReceipt()
    } else {
      toast.add({
        severity: 'error',
        summary: 'Eroare',
        detail: result.message,
        life: 5000,
      })
    }
  } catch (error) {
    toast.add({
      severity: 'error',
      summary: 'Eroare',
      detail: error.message || 'Nu s-a putut re-trimite bonul',
      life: 5000,
    })
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
}

@media (max-width: 768px) {
  .detail-grid {
    grid-template-columns: 1fr;
  }
}

.detail-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-item .label {
  color: #666;
  font-size: 0.9rem;
}

.detail-item .value {
  font-weight: 500;
}

.detail-item .value.amount {
  font-size: 1.1rem;
  color: #333;
}

.rejection-alert {
  display: flex;
  gap: 1rem;
  padding: 1rem;
  background: #fff3e0;
  border-radius: 8px;
  margin-top: 1rem;
}

.rejection-alert i {
  font-size: 1.5rem;
  color: #f57c00;
}

.rejection-alert p {
  margin: 0.5rem 0;
}

.rejection-alert small {
  color: #666;
}

.attachments-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1rem;
}

.attachment-item {
  border-radius: 8px;
  overflow: hidden;
}

.attachment-image {
  width: 100%;
  aspect-ratio: 1;
  object-fit: cover;
}

.pdf-link {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2rem;
  background: #f5f5f5;
  border-radius: 8px;
  text-decoration: none;
  color: #333;
}

.pdf-link i {
  font-size: 3rem;
  color: #d32f2f;
  margin-bottom: 0.5rem;
}

.entries-table-container {
  overflow-x: auto;
}

.balance-warning {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 1rem;
  padding: 0.75rem;
  background: #fff3e0;
  border-radius: 8px;
  color: #f57c00;
}

/* TVA Breakdown Display */
.detail-item.tva-detail {
  flex-direction: column;
  align-items: flex-start;
  gap: 0.5rem;
}

.tva-breakdown-display {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  padding: 0.5rem;
  background: #f0f9ff;
  border-radius: 6px;
  width: 100%;
}

.tva-line {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.tva-code {
  font-weight: 600;
  color: #475569;
  min-width: 1.5rem;
}

.tva-percent {
  display: inline-block;
  padding: 0.1rem 0.4rem;
  background: #dbeafe;
  border-radius: 4px;
  font-size: 0.85rem;
  color: #1e40af;
  min-width: 2.5rem;
  text-align: center;
}

.tva-amount {
  font-weight: 500;
  color: #334155;
}

.tva-total-line {
  margin-top: 0.25rem;
  padding-top: 0.25rem;
  border-top: 1px dashed #0284c7;
  color: #0284c7;
}
</style>
