<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 CreditNoteUser {
  id: number
  name: string
  email: string
  credit_balance: string
}

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

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

interface AccountCreditEntry {
  id: number
  amount: string
  type: string
  description: string | null
  created_at: string
}

interface CreditNoteDetail {
  id: number
  user_id: number
  number: string
  amount: string
  currency: string
  reason: string | null
  status: string
  issued_at: string | null
  created_at: string
  updated_at: string
  user: CreditNoteUser | null
  invoice: CreditNoteInvoice | null
  creator: CreditNoteCreator | null
  account_credits: AccountCreditEntry[]
}

interface Props {
  creditNote: CreditNoteDetail
}

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: 'success',
    draft: 'info',
    voided: 'error',
  }
  return map[status] ?? 'secondary'
}

function submitVoid(): void {
  voidForm.post(`/credit-notes/${props.creditNote.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' })
}

function formatDateTime(dateStr: string | null): string {
  if (!dateStr) return '---'
  const date = new Date(dateStr)
  return date.toLocaleString('en-US', {
    month: 'short',
    day: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}
</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="/credit-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">Credit Note {{ creditNote.number }}</span>
            <VChip
              :color="resolveStatusColor(creditNote.status)"
              size="small"
              class="text-capitalize"
            >
              {{ creditNote.status }}
            </VChip>
          </div>
          <div class="text-body-2 text-medium-emphasis mt-1">
            {{ creditNote.user?.name ?? 'Unknown Customer' }} &middot; {{ creditNote.user?.email ?? '' }}
          </div>
        </div>
      </div>

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

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

    <VRow>
      <!-- Credit Note Info -->
      <VCol cols="12" lg="4">
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-credit-card" size="22" />
            <span>Credit 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">
                  {{ creditNote.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-success">
                  +{{ formatPrice(creditNote.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">
                  {{ creditNote.currency }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Status</span>
                </template>
                <VListItemTitle>
                  <VChip
                    :color="resolveStatusColor(creditNote.status)"
                    size="small"
                    class="text-capitalize"
                  >
                    {{ creditNote.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(creditNote.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(creditNote.created_at) }}
                </VListItemTitle>
              </VListItem>
            </VList>
          </VCardText>
        </VCard>

        <!-- Reason Card -->
        <VCard v-if="creditNote.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">
              {{ creditNote.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="creditNote.user">
            <div class="d-flex align-center gap-3">
              <VAvatar color="primary" variant="tonal" size="40">
                <span class="text-body-1 font-weight-semibold">
                  {{ creditNote.user.name.charAt(0).toUpperCase() }}
                </span>
              </VAvatar>
              <div>
                <div class="text-body-1 font-weight-medium">
                  {{ creditNote.user.name }}
                </div>
                <div class="text-body-2 text-medium-emphasis">
                  {{ creditNote.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(creditNote.user.credit_balance).toFixed(2) }}
              </span>
            </div>
            <div class="mt-3">
              <Link :href="`/customers/${creditNote.user.id}`">
                <VBtn variant="tonal" size="small" color="primary" block>
                  View Customer
                </VBtn>
              </Link>
            </div>
          </VCardText>
        </VCard>

        <!-- Creator Card -->
        <VCard v-if="creditNote.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">
              {{ creditNote.creator.name }}
            </div>
            <div class="text-body-2 text-medium-emphasis">
              {{ creditNote.creator.email }}
            </div>
          </VCardText>
        </VCard>
      </VCol>

      <!-- Related Data -->
      <VCol cols="12" lg="8">
        <!-- Related Invoice -->
        <VCard v-if="creditNote.invoice" class="mb-4">
          <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">
                  {{ creditNote.invoice.number }}
                </div>
                <div class="text-body-2 text-medium-emphasis">
                  Total: {{ formatPrice(creditNote.invoice.total) }} &middot; Status: {{ creditNote.invoice.status }}
                </div>
              </div>
              <Link :href="`/invoices/${creditNote.invoice.id}`">
                <VBtn variant="tonal" size="small" color="primary">
                  View Invoice
                </VBtn>
              </Link>
            </div>
          </VCardText>
        </VCard>

        <!-- Account Credit Entries -->
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-history" size="22" />
            <span>Credit Entries</span>
            <VSpacer />
            <VChip size="small" color="secondary" variant="tonal">
              {{ creditNote.account_credits.length }}
            </VChip>
          </VCardTitle>

          <VCardText v-if="creditNote.account_credits.length === 0" class="text-center py-8">
            <VIcon icon="tabler-inbox" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">
              No credit entries recorded.
            </div>
          </VCardText>

          <VTable v-else density="comfortable" hover>
            <thead>
              <tr>
                <th>Type</th>
                <th>Description</th>
                <th class="text-end">
                  Amount
                </th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="entry in creditNote.account_credits" :key="entry.id">
                <td class="text-body-2 text-capitalize">
                  {{ entry.type.replace('_', ' ') }}
                </td>
                <td class="text-body-2">
                  {{ entry.description ?? '---' }}
                </td>
                <td class="text-end text-body-2 font-weight-medium" :class="parseFloat(entry.amount) >= 0 ? 'text-success' : 'text-error'">
                  {{ parseFloat(entry.amount) >= 0 ? '+' : '' }}{{ formatPrice(entry.amount) }}
                </td>
                <td class="text-body-2">
                  {{ formatDateTime(entry.created_at) }}
                </td>
              </tr>
            </tbody>
          </VTable>
        </VCard>
      </VCol>
    </VRow>

    <!-- Void Confirmation Dialog -->
    <VDialog v-model="voidDialog" max-width="500" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          Void Credit Note
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          Are you sure you want to void credit note <strong>{{ creditNote.number }}</strong>?
          This will reverse the credit of <strong>{{ formatPrice(creditNote.amount) }}</strong> from 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 Credit Note
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>
