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

interface OrderUser {
  id: number
  name: string
  email: string
  status: string
}

interface OrderPlan {
  id: number
  name: string
  service_type: string
  price: string
  billing_cycle: string
}

interface OrderInvoice {
  id: number
  number: string
  total: string
  status: string
}

interface OrderService {
  id: number
  hostname: string | null
  status: string
  ipv4_address: string | null
}

interface OrderDetail {
  id: number
  user_id: number
  plan_id: number
  invoice_id: number | null
  service_id: number | null
  order_number: string
  status: string
  total: string
  currency: string
  payment_gateway: string | null
  configuration: Record<string, string> | null
  admin_notes: string | null
  completed_at: string | null
  cancelled_at: string | null
  created_at: string
  updated_at: string
  user: OrderUser | null
  plan: OrderPlan | null
  invoice: OrderInvoice | null
  service: OrderService | null
}

interface Props {
  order: OrderDetail
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const confirmDialog = ref<boolean>(false)
const confirmAction = ref<'process' | 'complete' | 'cancel'>('process')
const confirmTitle = ref<string>('')
const confirmMessage = ref<string>('')
const confirmColor = ref<string>('info')

const processForm = useForm({})
const completeForm = useForm({})
const cancelForm = useForm({})

const notesForm = useForm({
  admin_notes: props.order.admin_notes ?? '',
})

const isProcessing = computed<boolean>(() =>
  processForm.processing || completeForm.processing || cancelForm.processing,
)

function openConfirmDialog(action: 'process' | 'complete' | 'cancel'): void {
  confirmAction.value = action

  if (action === 'process') {
    confirmTitle.value = 'Process Order'
    confirmMessage.value = `Are you sure you want to mark order ${props.order.order_number} as processing?`
    confirmColor.value = 'info'
  }
  else if (action === 'complete') {
    confirmTitle.value = 'Complete Order'
    confirmMessage.value = `Are you sure you want to mark order ${props.order.order_number} as completed?`
    confirmColor.value = 'success'
  }
  else {
    confirmTitle.value = 'Cancel Order'
    confirmMessage.value = `Are you sure you want to cancel order ${props.order.order_number}? This action cannot be undone.`
    confirmColor.value = 'error'
  }

  confirmDialog.value = true
}

function executeAction(): void {
  const action = confirmAction.value

  if (action === 'process') {
    processForm.post(`/orders/${props.order.id}/process`, {
      preserveScroll: true,
      onSuccess: () => { confirmDialog.value = false },
    })
  }
  else if (action === 'complete') {
    completeForm.post(`/orders/${props.order.id}/complete`, {
      preserveScroll: true,
      onSuccess: () => { confirmDialog.value = false },
    })
  }
  else {
    cancelForm.post(`/orders/${props.order.id}/cancel`, {
      preserveScroll: true,
      onSuccess: () => { confirmDialog.value = false },
    })
  }
}

function saveNotes(): void {
  notesForm.put(`/orders/${props.order.id}/notes`, {
    preserveScroll: true,
  })
}

function resolveOrderStatusColor(statusVal: string): StatusColor {
  const map: Record<string, StatusColor> = {
    pending: 'warning',
    processing: 'info',
    completed: 'success',
    cancelled: 'error',
    failed: 'error',
  }
  return map[statusVal] ?? '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 formatDateTime(dateStr: string | null): string {
  if (!dateStr) return '---'
  const date = new Date(dateStr)
  return date.toLocaleString('en-US', {
    month: 'short',
    day: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function formatServiceType(type: string): string {
  const map: Record<string, string> = {
    vps: 'VPS',
    dedicated: 'Dedicated',
    web_hosting: 'Web Hosting',
    hosting: 'Web Hosting',
    game: 'Game Hosting',
    game_server: 'Game Hosting',
  }
  return map[type] ?? type
}

function configurationEntries(): Array<{ key: string; value: string }> {
  if (!props.order.configuration) return []
  return Object.entries(props.order.configuration).map(([key, value]) => ({
    key: key.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()),
    value: String(value),
  }))
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div class="d-flex align-center gap-4">
        <Link href="/orders">
          <VBtn variant="text" icon="tabler-arrow-left" size="small" />
        </Link>
        <div>
          <div class="d-flex align-center gap-2">
            <span class="text-h4 font-weight-bold">Order {{ order.order_number }}</span>
            <VChip
              :color="resolveOrderStatusColor(order.status)"
              size="small"
              class="text-capitalize"
            >
              {{ order.status }}
            </VChip>
          </div>
          <div class="text-body-2 text-medium-emphasis mt-1">
            {{ order.user?.name ?? 'Unknown Customer' }} &middot; {{ order.user?.email ?? '' }}
          </div>
        </div>
      </div>

      <div class="d-flex gap-2">
        <VBtn
          v-if="order.status === 'pending'"
          color="info"
          variant="tonal"
          :disabled="isProcessing"
          @click="openConfirmDialog('process')"
        >
          <VIcon icon="tabler-player-play" start />
          Process
        </VBtn>

        <VBtn
          v-if="order.status === 'processing'"
          color="success"
          variant="tonal"
          :disabled="isProcessing"
          @click="openConfirmDialog('complete')"
        >
          <VIcon icon="tabler-check" start />
          Complete
        </VBtn>

        <VBtn
          v-if="order.status === 'pending' || order.status === 'processing'"
          color="error"
          variant="tonal"
          :disabled="isProcessing"
          @click="openConfirmDialog('cancel')"
        >
          <VIcon icon="tabler-x" start />
          Cancel
        </VBtn>
      </div>
    </div>

    <VRow>
      <!-- Order Details -->
      <VCol cols="12" lg="6">
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-shopping-cart" size="22" />
            <span>Order Details</span>
          </VCardTitle>

          <VCardText>
            <VList density="compact" class="pa-0">
              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 140px;">Order Number</span>
                </template>
                <VListItemTitle class="text-body-2 font-weight-medium">
                  {{ order.order_number }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 140px;">Total</span>
                </template>
                <VListItemTitle class="text-body-2 font-weight-medium">
                  {{ formatPrice(order.total) }}
                  <span class="text-uppercase text-medium-emphasis ms-1">{{ order.currency }}</span>
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 140px;">Gateway</span>
                </template>
                <VListItemTitle class="text-body-2 text-capitalize">
                  {{ order.payment_gateway ?? 'N/A' }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 140px;">Created</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ formatDateTime(order.created_at) }}
                </VListItemTitle>
              </VListItem>

              <VListItem v-if="order.completed_at">
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 140px;">Completed</span>
                </template>
                <VListItemTitle class="text-body-2 text-success">
                  {{ formatDateTime(order.completed_at) }}
                </VListItemTitle>
              </VListItem>

              <VListItem v-if="order.cancelled_at">
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 140px;">Cancelled</span>
                </template>
                <VListItemTitle class="text-body-2 text-error">
                  {{ formatDateTime(order.cancelled_at) }}
                </VListItemTitle>
              </VListItem>
            </VList>
          </VCardText>
        </VCard>

        <!-- Customer Card -->
        <VCard class="mt-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-user" size="22" />
            <span>Customer</span>
          </VCardTitle>

          <VCardText v-if="order.user">
            <div class="d-flex align-center gap-3">
              <VAvatar color="primary" variant="tonal" size="40">
                <span class="text-body-1 font-weight-semibold">
                  {{ order.user.name.charAt(0).toUpperCase() }}
                </span>
              </VAvatar>
              <div>
                <div class="text-body-1 font-weight-medium">
                  {{ order.user.name }}
                </div>
                <div class="text-body-2 text-medium-emphasis">
                  {{ order.user.email }}
                </div>
              </div>
              <VSpacer />
              <Link :href="`/customers/${order.user.id}`">
                <VBtn variant="tonal" size="small" color="primary">
                  View Customer
                </VBtn>
              </Link>
            </div>
          </VCardText>
        </VCard>

        <!-- Related Resources -->
        <VCard v-if="order.invoice || order.service" class="mt-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-link" size="22" />
            <span>Related Resources</span>
          </VCardTitle>

          <VCardText>
            <VList density="compact" class="pa-0">
              <VListItem v-if="order.invoice">
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 140px;">Invoice</span>
                </template>
                <VListItemTitle>
                  <Link :href="`/invoices/${order.invoice.id}`" class="text-body-2 font-weight-medium text-primary text-decoration-none">
                    {{ order.invoice.number }}
                  </Link>
                </VListItemTitle>
              </VListItem>

              <VListItem v-if="order.service">
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 140px;">Service</span>
                </template>
                <VListItemTitle>
                  <Link :href="`/services/${order.service.id}`" class="text-body-2 font-weight-medium text-primary text-decoration-none">
                    Service #{{ order.service.id }}
                  </Link>
                </VListItemTitle>
              </VListItem>
            </VList>
          </VCardText>
        </VCard>
      </VCol>

      <!-- Plan & Configuration -->
      <VCol cols="12" lg="6">
        <!-- Plan Info -->
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-package" size="22" />
            <span>Plan</span>
          </VCardTitle>

          <VCardText v-if="order.plan">
            <VList density="compact" class="pa-0">
              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 140px;">Name</span>
                </template>
                <VListItemTitle class="text-body-2 font-weight-medium">
                  {{ order.plan.name }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 140px;">Service Type</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ formatServiceType(order.plan.service_type) }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 140px;">Price</span>
                </template>
                <VListItemTitle class="text-body-2 font-weight-medium">
                  {{ formatPrice(order.plan.price, order.plan.billing_cycle) }}
                </VListItemTitle>
              </VListItem>
            </VList>
          </VCardText>

          <VCardText v-else class="text-center py-6">
            <div class="text-medium-emphasis">
              Plan information unavailable.
            </div>
          </VCardText>
        </VCard>

        <!-- Configuration -->
        <VCard class="mt-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-settings" size="22" />
            <span>Configuration</span>
          </VCardTitle>

          <VCardText v-if="configurationEntries().length > 0">
            <VList density="compact" class="pa-0">
              <VListItem v-for="entry in configurationEntries()" :key="entry.key">
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 140px;">{{ entry.key }}</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ entry.value }}
                </VListItemTitle>
              </VListItem>
            </VList>
          </VCardText>

          <VCardText v-else class="text-center py-6">
            <VIcon icon="tabler-inbox" size="36" color="disabled" class="mb-2" />
            <div class="text-medium-emphasis">
              No configuration data.
            </div>
          </VCardText>
        </VCard>

        <!-- Admin Notes -->
        <VCard class="mt-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-notes" size="22" />
            <span>Admin Notes</span>
          </VCardTitle>

          <VCardText>
            <VTextarea
              v-model="notesForm.admin_notes"
              placeholder="Add internal notes about this order..."
              rows="4"
              :error-messages="notesForm.errors.admin_notes"
              counter="1000"
              maxlength="1000"
            />

            <div class="d-flex justify-end mt-3">
              <VBtn
                color="primary"
                variant="tonal"
                :loading="notesForm.processing"
                :disabled="notesForm.processing"
                @click="saveNotes"
              >
                <VIcon icon="tabler-device-floppy" start />
                Save Notes
              </VBtn>
            </div>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- Confirmation Dialog -->
    <VDialog v-model="confirmDialog" max-width="500" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          {{ confirmTitle }}
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          {{ confirmMessage }}
        </VCardText>
        <VCardActions class="pa-5">
          <VSpacer />
          <VBtn variant="text" :disabled="isProcessing" @click="confirmDialog = false">
            Cancel
          </VBtn>
          <VBtn
            :color="confirmColor"
            variant="flat"
            :loading="isProcessing"
            @click="executeAction"
          >
            Confirm
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>
