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

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

interface QuoteItem {
  id: number
  user_id: number | null
  prospect_email: string | null
  prospect_name: string | null
  number: string
  status: string
  subtotal: string
  tax: string
  total: string
  currency: string
  valid_until: string | null
  sent_at: string | null
  accepted_at: string | null
  created_at: string
  user: QuoteUser | null
  creator: QuoteUser | null
}

interface Filters {
  search: string
  status: string
}

interface Props {
  quotes: PaginatedResponse<QuoteItem>
  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: 'Draft', value: 'draft' },
  { title: 'Sent', value: 'sent' },
  { title: 'Accepted', value: 'accepted' },
  { title: 'Rejected', value: 'rejected' },
  { title: 'Expired', value: 'expired' },
]

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

function applyFilters(): void {
  router.get('/quotes', {
    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(quoteStatus: string): StatusColor {
  const map: Record<string, StatusColor> = {
    draft: 'secondary',
    sent: 'info',
    accepted: 'success',
    rejected: 'error',
    expired: 'warning',
  }
  return map[quoteStatus] ?? 'secondary'
}

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 getRecipientName(quote: QuoteItem): string {
  return quote.user?.name ?? quote.prospect_name ?? '---'
}

function getRecipientEmail(quote: QuoteItem): string {
  return quote.user?.email ?? quote.prospect_email ?? ''
}
</script>

<template>
  <div>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Quotes
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage quotes and estimates for customers
        </div>
      </div>
      <Link href="/quotes/create">
        <VBtn color="primary" prepend-icon="tabler-plus">
          Create Quote
        </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 quote 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>

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

      <VTable v-else density="comfortable" hover>
        <thead>
          <tr>
            <th>Quote #</th>
            <th>Recipient</th>
            <th class="text-end">
              Total
            </th>
            <th>Status</th>
            <th>Valid Until</th>
            <th>Created</th>
            <th class="text-center">
              Actions
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="quote in quotes.data" :key="quote.id">
            <td class="text-body-2 font-weight-medium">
              {{ quote.number }}
            </td>
            <td>
              <div class="d-flex flex-column">
                <span class="text-body-2 font-weight-medium">{{ getRecipientName(quote) }}</span>
                <span class="text-caption text-medium-emphasis">{{ getRecipientEmail(quote) }}</span>
              </div>
            </td>
            <td class="text-end text-body-2 font-weight-medium">
              ${{ parseFloat(quote.total).toFixed(2) }}
              <span class="text-caption text-medium-emphasis ms-1">{{ quote.currency }}</span>
            </td>
            <td>
              <VChip
                :color="resolveStatusColor(quote.status)"
                size="small"
                class="text-capitalize"
              >
                {{ quote.status }}
              </VChip>
            </td>
            <td class="text-body-2">
              {{ formatDate(quote.valid_until) }}
            </td>
            <td class="text-body-2">
              {{ formatDate(quote.created_at) }}
            </td>
            <td class="text-center">
              <Link :href="`/quotes/${quote.id}`">
                <VBtn variant="text" size="small" color="primary">
                  <VIcon icon="tabler-eye" size="18" />
                </VBtn>
              </Link>
            </td>
          </tr>
        </tbody>
      </VTable>

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

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