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

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

interface DebitNoteItem {
  id: number
  user_id: number
  number: string
  amount: string
  currency: string
  reason_type: string
  status: string
  reason: string | null
  issued_at: string | null
  created_at: string
  user: DebitNoteUser | null
}

interface Filters {
  search: string
  status: string
}

interface Props {
  debitNotes: PaginatedResponse<DebitNoteItem>
  filters: Filters
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const search = ref<string>(props.filters.search)
const status = ref<string>(props.filters.status)

const statusOptions = [
  { title: 'All Statuses', value: '' },
  { title: 'Issued', value: 'issued' },
  { title: 'Draft', value: 'draft' },
  { title: 'Voided', value: 'voided' },
]

let searchTimeout: ReturnType<typeof setTimeout> | null = null

function applyFilters(): void {
  router.get('/debit-notes', {
    search: search.value || undefined,
    status: status.value || undefined,
  }, {
    preserveState: true,
    preserveScroll: true,
  })
}

watch(search, () => {
  if (searchTimeout) clearTimeout(searchTimeout)
  searchTimeout = setTimeout(applyFilters, 300)
})

watch(status, () => {
  applyFilters()
})

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

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

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>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Debit Notes
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage debit notes issued to customers
        </div>
      </div>
      <Link href="/debit-notes/create">
        <VBtn color="primary" prepend-icon="tabler-plus">
          Issue Debit Note
        </VBtn>
      </Link>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <VCol cols="12" md="8">
            <VTextField
              v-model="search"
              prepend-inner-icon="tabler-search"
              placeholder="Search by debit note number, customer name, or email..."
              density="compact"
              clearable
              hide-details
              @click:clear="search = ''"
            />
          </VCol>
          <VCol cols="12" md="4">
            <VSelect
              v-model="status"
              :items="statusOptions"
              density="compact"
              hide-details
              label="Status"
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Debit Notes Table -->
    <VCard>
      <VCardText v-if="debitNotes.data.length === 0" class="text-center py-12">
        <VIcon icon="tabler-file-off" size="48" color="disabled" class="mb-2" />
        <div class="text-medium-emphasis">
          No debit notes found.
        </div>
      </VCardText>

      <VTable v-else density="comfortable" hover>
        <thead>
          <tr>
            <th>Debit Note #</th>
            <th>Customer</th>
            <th class="text-end">
              Amount
            </th>
            <th>Type</th>
            <th>Status</th>
            <th>Issued Date</th>
            <th class="text-center">
              Actions
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="note in debitNotes.data" :key="note.id">
            <td class="text-body-2 font-weight-medium">
              {{ note.number }}
            </td>
            <td>
              <div class="d-flex flex-column">
                <span class="text-body-2 font-weight-medium">{{ note.user?.name ?? 'Unknown' }}</span>
                <span class="text-caption text-medium-emphasis">{{ note.user?.email ?? '' }}</span>
              </div>
            </td>
            <td class="text-end text-body-2 font-weight-medium text-error">
              -{{ formatPrice(note.amount) }}
            </td>
            <td class="text-body-2">
              <VChip size="small" variant="tonal" color="secondary">
                {{ resolveReasonTypeLabel(note.reason_type) }}
              </VChip>
            </td>
            <td>
              <VChip
                :color="resolveStatusColor(note.status)"
                size="small"
                class="text-capitalize"
              >
                {{ note.status }}
              </VChip>
            </td>
            <td class="text-body-2">
              {{ formatDate(note.issued_at) }}
            </td>
            <td class="text-center">
              <Link :href="`/debit-notes/${note.id}`">
                <VBtn variant="text" size="small" color="primary">
                  <VIcon icon="tabler-eye" size="18" />
                </VBtn>
              </Link>
            </td>
          </tr>
        </tbody>
      </VTable>

      <!-- Pagination -->
      <VCardText v-if="debitNotes.last_page > 1" class="d-flex align-center justify-center pt-2">
        <VPagination
          :model-value="debitNotes.data.length > 0 ? Math.ceil((debitNotes.from ?? 1) / 15) : 1"
          :length="debitNotes.last_page"
          :total-visible="7"
          @update:model-value="(page: number) => router.get('/debit-notes', { ...props.filters, page }, { preserveState: true, preserveScroll: true })"
        />
      </VCardText>

      <VCardText v-if="debitNotes.total > 0" class="text-center text-caption text-medium-emphasis">
        Showing {{ debitNotes.from }} to {{ debitNotes.to }} of {{ debitNotes.total }} debit notes
      </VCardText>
    </VCard>
  </div>
</template>
