<script lang="ts" setup>
import { Link, useForm } from '@inertiajs/vue3'
import { ref } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { formatPrice } from '@/utils/resolvers'
import type { StatusColor } from '@/types'

interface DebitNoteUser {
  id: number
  name: string
  email: string
  credit_balance: string
}

interface DebitNoteInvoice {
  id: number
  number: string
  total: string
  status: string
}

interface DebitNoteCreator {
  id: number
  name: string
  email: string
}

interface DebitNoteDetail {
  id: number
  user_id: number
  number: string
  amount: string
  currency: string
  reason_type: string
  reason: string | null
  status: string
  issued_at: string | null
  created_at: string
  updated_at: string
  user: DebitNoteUser | null
  invoice: DebitNoteInvoice | null
  creator: DebitNoteCreator | null
}

interface Props {
  debitNote: DebitNoteDetail
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const voidDialog = ref<boolean>(false)
const voidForm = useForm({})

function resolveStatusColor(status: string): StatusColor {
  const map: Record<string, StatusColor> = {
    issued: 'warning',
    draft: 'info',
    voided: 'error',
  }
  return map[status] ?? 'secondary'
}

function resolveReasonTypeLabel(reasonType: string): string {
  const map: Record<string, string> = {
    late_fee: 'Late Fee',
    adjustment: 'Adjustment',
    underpayment: 'Underpayment',
  }
  return map[reasonType] ?? reasonType
}

function submitVoid(): void {
  voidForm.post(`/debit-notes/${props.debitNote.id}/void`, {
    preserveScroll: true,
    onSuccess: () => { voidDialog.value = false },
  })
}

function formatDate(dateStr: string | null): string {
  if (!dateStr) return '---'
  const date = new Date(dateStr)
  return date.toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' })
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div class="d-flex align-center gap-4">
        <Link href="/debit-notes">
          <VBtn variant="text" icon="tabler-arrow-left" size="small" />
        </Link>
        <div>
          <div class="d-flex align-center gap-2">
            <span class="text-h4 font-weight-bold">Debit Note {{ debitNote.number }}</span>
            <VChip
              :color="resolveStatusColor(debitNote.status)"
              size="small"
              class="text-capitalize"
            >
              {{ debitNote.status }}
            </VChip>
          </div>
          <div class="text-body-2 text-medium-emphasis mt-1">
            {{ debitNote.user?.name ?? 'Unknown Customer' }} &middot; {{ debitNote.user?.email ?? '' }}
          </div>
        </div>
      </div>

      <div class="d-flex gap-2">
        <VBtn
          color="info"
          variant="tonal"
          :href="`/debit-notes/${debitNote.id}/download`"
        >
          <VIcon icon="tabler-download" start />
          Download PDF
        </VBtn>

        <VBtn
          v-if="debitNote.status !== 'voided'"
          color="error"
          variant="tonal"
          :disabled="voidForm.processing"
          @click="voidDialog = true"
        >
          <VIcon icon="tabler-ban" start />
          Void Debit Note
        </VBtn>
      </div>
    </div>

    <VRow>
      <!-- Debit Note Info -->
      <VCol cols="12" lg="4">
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-receipt" size="22" />
            <span>Debit Note Details</span>
          </VCardTitle>

          <VCardText>
            <VList density="compact" class="pa-0">
              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Number</span>
                </template>
                <VListItemTitle class="text-body-2 font-weight-medium">
                  {{ debitNote.number }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Amount</span>
                </template>
                <VListItemTitle class="text-body-2 font-weight-medium text-error">
                  -{{ formatPrice(debitNote.amount) }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Currency</span>
                </template>
                <VListItemTitle class="text-body-2 text-uppercase">
                  {{ debitNote.currency }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Reason Type</span>
                </template>
                <VListItemTitle>
                  <VChip size="small" variant="tonal" color="secondary">
                    {{ resolveReasonTypeLabel(debitNote.reason_type) }}
                  </VChip>
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Status</span>
                </template>
                <VListItemTitle>
                  <VChip
                    :color="resolveStatusColor(debitNote.status)"
                    size="small"
                    class="text-capitalize"
                  >
                    {{ debitNote.status }}
                  </VChip>
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Issued</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ formatDate(debitNote.issued_at) }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Created</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ formatDate(debitNote.created_at) }}
                </VListItemTitle>
              </VListItem>
            </VList>
          </VCardText>
        </VCard>

        <!-- Reason Card -->
        <VCard v-if="debitNote.reason" class="mt-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-notes" size="22" />
            <span>Reason</span>
          </VCardTitle>
          <VCardText>
            <div class="text-body-2">
              {{ debitNote.reason }}
            </div>
          </VCardText>
        </VCard>

        <!-- Customer Card -->
        <VCard class="mt-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-user" size="22" />
            <span>Customer</span>
          </VCardTitle>

          <VCardText v-if="debitNote.user">
            <div class="d-flex align-center gap-3">
              <VAvatar color="primary" variant="tonal" size="40">
                <span class="text-body-1 font-weight-semibold">
                  {{ debitNote.user.name.charAt(0).toUpperCase() }}
                </span>
              </VAvatar>
              <div>
                <div class="text-body-1 font-weight-medium">
                  {{ debitNote.user.name }}
                </div>
                <div class="text-body-2 text-medium-emphasis">
                  {{ debitNote.user.email }}
                </div>
              </div>
            </div>
            <div class="mt-3 d-flex justify-space-between align-center">
              <span class="text-body-2 text-medium-emphasis">Current Balance</span>
              <span class="text-body-2 font-weight-medium">
                ${{ parseFloat(debitNote.user.credit_balance).toFixed(2) }}
              </span>
            </div>
            <div class="mt-3">
              <Link :href="`/customers/${debitNote.user.id}`">
                <VBtn variant="tonal" size="small" color="primary" block>
                  View Customer
                </VBtn>
              </Link>
            </div>
          </VCardText>
        </VCard>

        <!-- Creator Card -->
        <VCard v-if="debitNote.creator" class="mt-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-shield" size="22" />
            <span>Issued By</span>
          </VCardTitle>
          <VCardText>
            <div class="text-body-2 font-weight-medium">
              {{ debitNote.creator.name }}
            </div>
            <div class="text-body-2 text-medium-emphasis">
              {{ debitNote.creator.email }}
            </div>
          </VCardText>
        </VCard>
      </VCol>

      <!-- Related Data -->
      <VCol cols="12" lg="8">
        <!-- Related Invoice -->
        <VCard v-if="debitNote.invoice">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-file-invoice" size="22" />
            <span>Related Invoice</span>
          </VCardTitle>
          <VCardText>
            <div class="d-flex align-center justify-space-between">
              <div>
                <div class="text-body-1 font-weight-medium">
                  {{ debitNote.invoice.number }}
                </div>
                <div class="text-body-2 text-medium-emphasis">
                  Total: {{ formatPrice(debitNote.invoice.total) }} &middot; Status: {{ debitNote.invoice.status }}
                </div>
              </div>
              <Link :href="`/invoices/${debitNote.invoice.id}`">
                <VBtn variant="tonal" size="small" color="primary">
                  View Invoice
                </VBtn>
              </Link>
            </div>
          </VCardText>
        </VCard>

        <!-- Info Box when no invoice -->
        <VCard v-else>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-info-circle" size="22" />
            <span>Debit Note Information</span>
          </VCardTitle>
          <VCardText>
            <VAlert type="info" variant="tonal" class="mb-0">
              <p class="text-body-2 mb-1">
                This debit note debits <strong>{{ formatPrice(debitNote.amount) }}</strong> from the customer's account credit balance.
              </p>
              <p class="text-body-2 mb-0">
                The deduction is capped at the customer's available balance (cannot go below $0.00).
              </p>
            </VAlert>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- Void Confirmation Dialog -->
    <VDialog v-model="voidDialog" max-width="500" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          Void Debit Note
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          Are you sure you want to void debit note <strong>{{ debitNote.number }}</strong>?
          This will restore <strong>{{ formatPrice(debitNote.amount) }}</strong> to the customer's balance.
        </VCardText>
        <VCardActions class="pa-5">
          <VSpacer />
          <VBtn variant="text" :disabled="voidForm.processing" @click="voidDialog = false">
            Cancel
          </VBtn>
          <VBtn
            color="error"
            variant="flat"
            :loading="voidForm.processing"
            @click="submitVoid"
          >
            Void Debit Note
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>
