<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, TaxRate } from '@/types'

interface Props {
  taxRates: PaginatedResponse<TaxRate>
  countries: string[]
  filters: {
    search: string
    country: string
    status: string
  }
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

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

const countryNames: Record<string, string> = {
  US: 'United States',
  GB: 'United Kingdom',
  DE: 'Germany',
  FR: 'France',
  CA: 'Canada',
  AU: 'Australia',
  NL: 'Netherlands',
  SE: 'Sweden',
  JP: 'Japan',
  BR: 'Brazil',
  IT: 'Italy',
  ES: 'Spain',
  IE: 'Ireland',
  NZ: 'New Zealand',
  SG: 'Singapore',
  IN: 'India',
  CH: 'Switzerland',
  AT: 'Austria',
  BE: 'Belgium',
  PT: 'Portugal',
  DK: 'Denmark',
  NO: 'Norway',
  FI: 'Finland',
  PL: 'Poland',
  CZ: 'Czech Republic',
  MX: 'Mexico',
}

const countryFilterItems = [
  { title: 'All Countries', value: 'all' },
  ...props.countries.map(code => ({
    title: `${countryNames[code] ?? code} (${code})`,
    value: code,
  })),
]

const statusFilterItems = [
  { title: 'All Statuses', value: 'all' },
  { title: 'Active', value: 'active' },
  { title: 'Inactive', value: 'inactive' },
]

const tableHeaders = [
  { title: 'Name', key: 'name', sortable: true },
  { title: 'Country', key: 'country_code', sortable: true },
  { title: 'Region', key: 'region_code', sortable: true },
  { title: 'Rate', key: 'rate', sortable: true, align: 'end' as const },
  { title: 'Type', key: 'type', sortable: true },
  { title: 'Priority', key: 'priority', sortable: true, align: 'center' as const },
  { title: 'Status', key: 'is_active', sortable: true, align: 'center' as const },
  { title: 'Actions', key: 'actions', sortable: false, align: 'center' as const },
]

function getCountryName(code: string): string {
  return countryNames[code] ?? code
}

function resolveTypeColor(type: string): StatusColor {
  return type === 'inclusive' ? 'info' : 'warning'
}

function applyFilters(): void {
  router.get('/tax-rates', {
    search: search.value || undefined,
    country: countryFilter.value !== 'all' ? countryFilter.value : undefined,
    status: statusFilter.value !== 'all' ? statusFilter.value : undefined,
  }, {
    preserveState: true,
    replace: true,
  })
}

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

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

watch([countryFilter, statusFilter], () => {
  applyFilters()
})

function toggleActive(taxRate: TaxRate): void {
  router.post(`/tax-rates/${taxRate.id}/toggle-active`, {}, {
    preserveScroll: true,
  })
}

function deleteTaxRate(taxRate: TaxRate): void {
  if (confirm(`Are you sure you want to delete "${taxRate.name}"? This action cannot be undone.`)) {
    router.delete(`/tax-rates/${taxRate.id}`, {
      preserveScroll: true,
    })
  }
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Tax Rates
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage tax rates by country and region
        </div>
      </div>
      <Link href="/tax-rates/create">
        <VBtn color="primary" prepend-icon="tabler-plus">
          Create Tax Rate
        </VBtn>
      </Link>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <VCol cols="12" md="4">
            <VTextField
              v-model="search"
              placeholder="Search by name, country, or region..."
              prepend-inner-icon="tabler-search"
              clearable
            />
          </VCol>
          <VCol cols="12" md="4">
            <VSelect
              v-model="countryFilter"
              :items="countryFilterItems"
              placeholder="Filter by country"
            />
          </VCol>
          <VCol cols="12" md="4">
            <VSelect
              v-model="statusFilter"
              :items="statusFilterItems"
              placeholder="Filter by status"
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Tax Rates Table -->
    <VCard>
      <VDataTable
        :headers="tableHeaders"
        :items="taxRates.data"
        :items-per-page="25"
        hover
        class="text-no-wrap"
      >
        <!-- Name -->
        <template #item.name="{ item }">
          <span class="font-weight-medium">{{ item.name }}</span>
        </template>

        <!-- Country -->
        <template #item.country_code="{ item }">
          <span>{{ getCountryName(item.country_code) }}</span>
          <span class="text-medium-emphasis ms-1">({{ item.country_code }})</span>
        </template>

        <!-- Region -->
        <template #item.region_code="{ item }">
          <span v-if="item.region_code">{{ item.region_code }}</span>
          <span v-else class="text-medium-emphasis">--</span>
        </template>

        <!-- Rate -->
        <template #item.rate="{ item }">
          <span class="font-weight-medium">{{ parseFloat(item.rate).toFixed(2) }}%</span>
        </template>

        <!-- Type -->
        <template #item.type="{ item }">
          <VChip
            :color="resolveTypeColor(item.type)"
            size="small"
            variant="tonal"
            class="text-capitalize"
          >
            {{ item.type }}
          </VChip>
        </template>

        <!-- Priority -->
        <template #item.priority="{ item }">
          <span>{{ item.priority }}</span>
        </template>

        <!-- Status -->
        <template #item.is_active="{ item }">
          <VChip
            :color="item.is_active ? 'success' : 'error'"
            size="small"
          >
            {{ item.is_active ? 'Active' : 'Inactive' }}
          </VChip>
        </template>

        <!-- Actions -->
        <template #item.actions="{ item }">
          <VMenu>
            <template #activator="{ props: menuProps }">
              <VBtn
                icon="tabler-dots-vertical"
                variant="text"
                size="small"
                v-bind="menuProps"
              />
            </template>
            <VList density="compact">
              <Link :href="`/tax-rates/${item.id}/edit`" class="text-decoration-none">
                <VListItem prepend-icon="tabler-edit">
                  <VListItemTitle>Edit</VListItemTitle>
                </VListItem>
              </Link>
              <VListItem
                :prepend-icon="item.is_active ? 'tabler-toggle-right' : 'tabler-toggle-left'"
                @click="toggleActive(item)"
              >
                <VListItemTitle>{{ item.is_active ? 'Deactivate' : 'Activate' }}</VListItemTitle>
              </VListItem>
              <VListItem
                prepend-icon="tabler-trash"
                class="text-error"
                @click="deleteTaxRate(item)"
              >
                <VListItemTitle>Delete</VListItemTitle>
              </VListItem>
            </VList>
          </VMenu>
        </template>

        <!-- No data -->
        <template #no-data>
          <div class="text-center py-8">
            <VIcon icon="tabler-receipt-tax" size="48" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">
              No tax rates found.
            </div>
          </div>
        </template>
      </VDataTable>
    </VCard>
  </div>
</template>
