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

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

interface InvoiceItem {
  id: number
  user_id: number
  number: string
  total: string
  tax: string
  currency: string
  status: string
  gateway: string | null
  due_date: string | null
  paid_at: string | null
  created_at: string
  user: InvoiceUser | null
}

interface Filters {
  search: string
  status: string
}

interface Props {
  invoices: PaginatedResponse<InvoiceItem>
  filters: Filters
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const search = ref<string>(props.filters.search)
const status = ref<string>(props.filters.status)
const resendingId = ref<number | null>(null)

const statusOptions = [
  { title: 'All Statuses', value: '' },
  { title: 'Draft', value: 'draft' },
  { title: 'Paid', value: 'paid' },
  { title: 'Pending', value: 'pending' },
  { title: 'Overdue', value: 'overdue' },
  { title: 'Void', value: 'void' },
]

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

function applyFilters(): void {
  router.get('/invoices', {
    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 resendInvoice(invoice: InvoiceItem): void {
  resendingId.value = invoice.id
  const resendForm = useForm({})
  resendForm.post(`/invoices/${invoice.id}/resend`, {
    preserveScroll: true,
    onFinish: () => { resendingId.value = null },
  })
}

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">
          Invoices
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage all customer invoices
        </div>
      </div>
      <Link href="/invoices/create">
        <VBtn color="primary" prepend-icon="tabler-plus">
          Create Invoice
        </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 invoice 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>

    <!-- Invoices Table -->
    <VCard>
      <VCardText v-if="invoices.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 invoices found.
        </div>
      </VCardText>

      <VTable v-else density="comfortable" hover>
        <thead>
          <tr>
            <th>Invoice #</th>
            <th>Customer</th>
            <th class="text-end">
              Amount
            </th>
            <th>Status</th>
            <th>Due Date</th>
            <th>Paid Date</th>
            <th class="text-center">
              Actions
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="invoice in invoices.data" :key="invoice.id">
            <td class="text-body-2 font-weight-medium">
              {{ invoice.number }}
            </td>
            <td>
              <div class="d-flex flex-column">
                <span class="text-body-2 font-weight-medium">{{ invoice.user?.name ?? 'Unknown' }}</span>
                <span class="text-caption text-medium-emphasis">{{ invoice.user?.email ?? '' }}</span>
              </div>
            </td>
            <td class="text-end text-body-2 font-weight-medium">
              {{ formatPrice(invoice.total) }}
            </td>
            <td>
              <VChip
                :color="resolveInvoiceStatusColor(invoice.status)"
                size="small"
                class="text-capitalize"
              >
                {{ invoice.status }}
              </VChip>
            </td>
            <td class="text-body-2">
              {{ formatDate(invoice.due_date) }}
            </td>
            <td class="text-body-2">
              {{ formatDate(invoice.paid_at) }}
            </td>
            <td class="text-center">
              <div class="d-flex align-center justify-center gap-1">
                <Link :href="`/invoices/${invoice.id}`">
                  <VBtn variant="text" size="small" color="primary">
                    <VIcon icon="tabler-eye" size="18" />
                  </VBtn>
                </Link>
                <Link
                  v-if="invoice.status === 'draft' || invoice.status === 'pending'"
                  :href="`/invoices/${invoice.id}/edit`"
                >
                  <VBtn variant="text" size="small" color="warning">
                    <VIcon icon="tabler-edit" size="18" />
                  </VBtn>
                </Link>
                <VBtn
                  v-if="invoice.status !== 'void'"
                  variant="text"
                  size="small"
                  color="info"
                  :loading="resendingId === invoice.id"
                  @click="resendInvoice(invoice)"
                >
                  <VIcon icon="tabler-mail-forward" size="18" />
                </VBtn>
              </div>
            </td>
          </tr>
        </tbody>
      </VTable>

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

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