<script lang="ts" setup>
import { useForm, router } from '@inertiajs/vue3'
import { ref } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'

interface Currency {
  id: number
  code: string
  symbol: string
  name: string
  decimal_places: number
  exchange_rate: string
  is_base: boolean
  is_enabled: boolean
  last_synced_at: string | null
}

interface Props {
  currencies: Currency[]
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const showCreateDialog = ref<boolean>(false)
const showEditDialog = ref<boolean>(false)
const deleteDialog = ref<boolean>(false)
const currencyToDelete = ref<Currency | null>(null)
const syncing = ref<boolean>(false)

const createForm = useForm({
  code: '',
  symbol: '',
  name: '',
  decimal_places: 2,
  exchange_rate: '1.000000',
  is_base: false,
  is_enabled: true,
})

const editForm = useForm({
  id: 0,
  symbol: '',
  name: '',
  decimal_places: 2,
  exchange_rate: '1.000000',
  is_base: false,
  is_enabled: true,
})

function submitCreate(): void {
  createForm.post('/currencies', {
    preserveScroll: true,
    onSuccess: () => {
      showCreateDialog.value = false
      createForm.reset()
    },
  })
}

function openEdit(currency: Currency): void {
  editForm.id = currency.id
  editForm.symbol = currency.symbol
  editForm.name = currency.name
  editForm.decimal_places = currency.decimal_places
  editForm.exchange_rate = currency.exchange_rate
  editForm.is_base = currency.is_base
  editForm.is_enabled = currency.is_enabled
  showEditDialog.value = true
}

function submitEdit(): void {
  editForm.put(`/currencies/${editForm.id}`, {
    preserveScroll: true,
    onSuccess: () => {
      showEditDialog.value = false
    },
  })
}

function confirmDelete(currency: Currency): void {
  currencyToDelete.value = currency
  deleteDialog.value = true
}

function submitDelete(): void {
  if (!currencyToDelete.value) return
  router.delete(`/currencies/${currencyToDelete.value.id}`, {
    preserveScroll: true,
    onSuccess: () => {
      deleteDialog.value = false
      currencyToDelete.value = null
    },
  })
}

function syncRates(): void {
  syncing.value = true
  router.post('/currencies/sync-rates', {}, {
    preserveScroll: true,
    onFinish: () => {
      syncing.value = false
    },
  })
}

function formatDate(dateStr: string | null): string {
  if (!dateStr) return 'Never'
  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>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Currencies
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage currencies and exchange rates
        </div>
      </div>
      <div class="d-flex gap-2">
        <VBtn
          color="secondary"
          variant="tonal"
          :loading="syncing"
          prepend-icon="tabler-refresh"
          @click="syncRates"
        >
          Sync Rates
        </VBtn>
        <VBtn
          color="primary"
          prepend-icon="tabler-plus"
          @click="showCreateDialog = true"
        >
          Add Currency
        </VBtn>
      </div>
    </div>

    <!-- Currencies Table -->
    <VCard>
      <VCardText v-if="props.currencies.length === 0" class="text-center py-12">
        <VIcon icon="tabler-currency-dollar-off" size="48" color="disabled" class="mb-2" />
        <div class="text-medium-emphasis">
          No currencies configured. Add your first currency.
        </div>
      </VCardText>

      <VTable v-else density="comfortable" hover>
        <thead>
          <tr>
            <th>Code</th>
            <th>Symbol</th>
            <th>Name</th>
            <th class="text-center">
              Decimals
            </th>
            <th class="text-end">
              Exchange Rate
            </th>
            <th class="text-center">
              Base
            </th>
            <th class="text-center">
              Enabled
            </th>
            <th>Last Synced</th>
            <th class="text-center">
              Actions
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="currency in props.currencies" :key="currency.id">
            <td class="text-body-2 font-weight-medium">
              {{ currency.code }}
            </td>
            <td class="text-body-2">
              {{ currency.symbol }}
            </td>
            <td class="text-body-2">
              {{ currency.name }}
            </td>
            <td class="text-center text-body-2">
              {{ currency.decimal_places }}
            </td>
            <td class="text-end text-body-2 font-weight-medium">
              {{ parseFloat(currency.exchange_rate).toFixed(6) }}
            </td>
            <td class="text-center">
              <VChip
                v-if="currency.is_base"
                size="small"
                color="primary"
              >
                Base
              </VChip>
            </td>
            <td class="text-center">
              <VIcon
                :icon="currency.is_enabled ? 'tabler-check' : 'tabler-x'"
                :color="currency.is_enabled ? 'success' : 'error'"
                size="20"
              />
            </td>
            <td class="text-body-2">
              {{ formatDate(currency.last_synced_at) }}
            </td>
            <td class="text-center">
              <VBtn
                variant="text"
                size="small"
                color="primary"
                icon="tabler-edit"
                @click="openEdit(currency)"
              />
              <VBtn
                v-if="!currency.is_base"
                variant="text"
                size="small"
                color="error"
                icon="tabler-trash"
                @click="confirmDelete(currency)"
              />
            </td>
          </tr>
        </tbody>
      </VTable>
    </VCard>

    <!-- Create Dialog -->
    <VDialog v-model="showCreateDialog" max-width="550" persistent>
      <VCard title="Add Currency">
        <VCardText>
          <VRow>
            <VCol cols="6">
              <VTextField
                v-model="createForm.code"
                label="Currency Code"
                placeholder="USD"
                hint="3-letter ISO code"
                persistent-hint
                :error-messages="createForm.errors.code"
              />
            </VCol>
            <VCol cols="6">
              <VTextField
                v-model="createForm.symbol"
                label="Symbol"
                placeholder="$"
                :error-messages="createForm.errors.symbol"
              />
            </VCol>
            <VCol cols="12">
              <VTextField
                v-model="createForm.name"
                label="Name"
                placeholder="US Dollar"
                :error-messages="createForm.errors.name"
              />
            </VCol>
            <VCol cols="6">
              <VTextField
                v-model.number="createForm.decimal_places"
                label="Decimal Places"
                type="number"
                min="0"
                max="4"
                :error-messages="createForm.errors.decimal_places"
              />
            </VCol>
            <VCol cols="6">
              <VTextField
                v-model="createForm.exchange_rate"
                label="Exchange Rate"
                type="number"
                step="0.000001"
                :error-messages="createForm.errors.exchange_rate"
              />
            </VCol>
            <VCol cols="6">
              <VSwitch
                v-model="createForm.is_base"
                label="Base Currency"
                color="primary"
              />
            </VCol>
            <VCol cols="6">
              <VSwitch
                v-model="createForm.is_enabled"
                label="Enabled"
                color="success"
              />
            </VCol>
          </VRow>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn variant="text" :disabled="createForm.processing" @click="showCreateDialog = false">
            Cancel
          </VBtn>
          <VBtn color="primary" :loading="createForm.processing" @click="submitCreate">
            Create
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>

    <!-- Edit Dialog -->
    <VDialog v-model="showEditDialog" max-width="550" persistent>
      <VCard title="Edit Currency">
        <VCardText>
          <VRow>
            <VCol cols="6">
              <VTextField
                v-model="editForm.symbol"
                label="Symbol"
                :error-messages="editForm.errors.symbol"
              />
            </VCol>
            <VCol cols="6">
              <VTextField
                v-model="editForm.name"
                label="Name"
                :error-messages="editForm.errors.name"
              />
            </VCol>
            <VCol cols="6">
              <VTextField
                v-model.number="editForm.decimal_places"
                label="Decimal Places"
                type="number"
                min="0"
                max="4"
                :error-messages="editForm.errors.decimal_places"
              />
            </VCol>
            <VCol cols="6">
              <VTextField
                v-model="editForm.exchange_rate"
                label="Exchange Rate"
                type="number"
                step="0.000001"
                :error-messages="editForm.errors.exchange_rate"
              />
            </VCol>
            <VCol cols="6">
              <VSwitch
                v-model="editForm.is_base"
                label="Base Currency"
                color="primary"
              />
            </VCol>
            <VCol cols="6">
              <VSwitch
                v-model="editForm.is_enabled"
                label="Enabled"
                color="success"
              />
            </VCol>
          </VRow>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn variant="text" :disabled="editForm.processing" @click="showEditDialog = false">
            Cancel
          </VBtn>
          <VBtn color="primary" :loading="editForm.processing" @click="submitEdit">
            Update
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>

    <!-- Delete Confirmation -->
    <VDialog v-model="deleteDialog" max-width="450" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          Delete Currency
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          Are you sure you want to delete <strong>{{ currencyToDelete?.code }}</strong> ({{ currencyToDelete?.name }})?
        </VCardText>
        <VCardActions class="pa-5">
          <VSpacer />
          <VBtn variant="text" @click="deleteDialog = false">
            Cancel
          </VBtn>
          <VBtn color="error" variant="flat" @click="submitDelete">
            Delete
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>
