<script lang="ts" setup>
import { useForm, usePage } from '@inertiajs/vue3'
import { computed, ref } from 'vue'
import MarketingLayout from '@/Layouts/MarketingLayout.vue'
import type { StatusColor } from '@/types'

defineOptions({ layout: MarketingLayout })

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

interface QuoteLineItem {
  description: string
  quantity: number
  unit_price: string | number
}

interface QuoteDetail {
  id: number
  user_id: number | null
  prospect_email: string | null
  prospect_name: string | null
  number: string
  status: string
  items: QuoteLineItem[]
  subtotal: string
  tax: string
  total: string
  currency: string
  notes: string | null
  valid_until: string | null
  accepted_at: string | null
  sent_at: string | null
  created_at: string
  creator: QuoteUser | null
}

interface Props {
  quote: QuoteDetail
  isExpired: boolean
}

const props = defineProps<Props>()
const page = usePage()

// Get signed URL parameters for form submissions
const currentUrl = computed<string>(() => {
  return typeof window !== 'undefined' ? window.location.href : ''
})

const signatureParam = computed<string>(() => {
  if (typeof window === 'undefined') return ''
  const url = new URL(window.location.href)
  return url.search
})

const acceptForm = useForm({})
const rejectForm = useForm({})
const showRejectDialog = ref<boolean>(false)

function resolveStatusColor(status: string): StatusColor {
  const map: Record<string, StatusColor> = {
    draft: 'secondary',
    sent: 'info',
    accepted: 'success',
    rejected: 'error',
    expired: 'warning',
  }
  return map[status] ?? 'secondary'
}

function formatDate(dateStr: string | null): string {
  if (!dateStr) return '---'
  const date = new Date(dateStr)
  return date.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })
}

function submitAccept(): void {
  acceptForm.post(`/quotes/${props.quote.id}/accept${signatureParam.value}`, {
    preserveScroll: true,
  })
}

function submitReject(): void {
  rejectForm.post(`/quotes/${props.quote.id}/reject${signatureParam.value}`, {
    preserveScroll: true,
    onSuccess: () => { showRejectDialog.value = false },
  })
}

// Flash messages
const flash = computed(() => (page.props as Record<string, unknown>).flash as Record<string, string> | undefined)
</script>

<template>
  <div class="py-8">
    <VContainer>
      <!-- Flash messages -->
      <VAlert
        v-if="flash?.success"
        type="success"
        variant="tonal"
        closable
        class="mb-6"
      >
        {{ flash.success }}
      </VAlert>
      <VAlert
        v-if="flash?.error"
        type="error"
        variant="tonal"
        closable
        class="mb-6"
      >
        {{ flash.error }}
      </VAlert>

      <div class="text-center mb-8">
        <div class="text-h3 font-weight-bold mb-2">
          Quote {{ props.quote.number }}
        </div>
        <div class="text-body-1 text-medium-emphasis">
          from EZSCALE Cloud Infrastructure
        </div>
        <VChip
          :color="resolveStatusColor(props.quote.status)"
          size="small"
          class="text-capitalize mt-2"
        >
          {{ props.quote.status }}
        </VChip>
      </div>

      <VCard max-width="800" class="mx-auto">
        <!-- Quote Meta -->
        <VCardText class="pa-6">
          <VRow>
            <VCol cols="12" md="6">
              <div class="text-body-2 text-medium-emphasis mb-1">
                Date
              </div>
              <div class="text-body-1 font-weight-medium">
                {{ formatDate(props.quote.created_at) }}
              </div>
            </VCol>
            <VCol cols="12" md="6" class="text-md-end">
              <div class="text-body-2 text-medium-emphasis mb-1">
                Valid Until
              </div>
              <div class="text-body-1 font-weight-medium" :class="{ 'text-error': props.isExpired }">
                {{ formatDate(props.quote.valid_until) }}
                <span v-if="props.isExpired" class="text-caption text-error">(Expired)</span>
              </div>
            </VCol>
          </VRow>
        </VCardText>

        <VDivider />

        <!-- Line Items -->
        <VTable density="comfortable">
          <thead>
            <tr>
              <th>Description</th>
              <th class="text-center">
                Qty
              </th>
              <th class="text-end">
                Unit Price
              </th>
              <th class="text-end">
                Total
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in props.quote.items" :key="index">
              <td class="text-body-2">
                {{ item.description }}
              </td>
              <td class="text-center text-body-2">
                {{ item.quantity }}
              </td>
              <td class="text-end text-body-2">
                ${{ parseFloat(String(item.unit_price)).toFixed(2) }}
              </td>
              <td class="text-end text-body-2 font-weight-medium">
                ${{ (parseFloat(String(item.unit_price)) * item.quantity).toFixed(2) }}
              </td>
            </tr>
          </tbody>
        </VTable>

        <VDivider />

        <!-- Totals -->
        <VCardText class="pa-6">
          <div class="d-flex flex-column align-end">
            <div class="d-flex justify-space-between mb-1" style="width: 280px;">
              <span class="text-body-2 text-medium-emphasis">Subtotal</span>
              <span class="text-body-2 font-weight-medium">${{ parseFloat(props.quote.subtotal).toFixed(2) }}</span>
            </div>
            <div v-if="parseFloat(props.quote.tax) > 0" class="d-flex justify-space-between mb-1" style="width: 280px;">
              <span class="text-body-2 text-medium-emphasis">Tax</span>
              <span class="text-body-2 font-weight-medium">${{ parseFloat(props.quote.tax).toFixed(2) }}</span>
            </div>
            <VDivider class="my-2" style="width: 280px;" />
            <div class="d-flex justify-space-between" style="width: 280px;">
              <span class="text-body-1 font-weight-bold">Total ({{ props.quote.currency }})</span>
              <span class="text-h5 font-weight-bold text-primary">${{ parseFloat(props.quote.total).toFixed(2) }}</span>
            </div>
          </div>
        </VCardText>

        <!-- Notes -->
        <template v-if="props.quote.notes">
          <VDivider />
          <VCardText class="pa-6">
            <div class="text-body-2 text-medium-emphasis mb-1">
              Notes
            </div>
            <div class="text-body-2" style="white-space: pre-wrap;">
              {{ props.quote.notes }}
            </div>
          </VCardText>
        </template>

        <!-- Accept/Reject Actions -->
        <template v-if="props.quote.status === 'sent' && !props.isExpired">
          <VDivider />
          <VCardText class="pa-6 text-center">
            <div class="text-body-2 text-medium-emphasis mb-4">
              Would you like to proceed with this quote?
            </div>
            <div class="d-flex gap-3 justify-center">
              <VBtn
                color="success"
                size="large"
                :loading="acceptForm.processing"
                :disabled="rejectForm.processing"
                prepend-icon="tabler-check"
                @click="submitAccept"
              >
                Accept Quote
              </VBtn>
              <VBtn
                color="error"
                variant="outlined"
                size="large"
                :disabled="acceptForm.processing"
                @click="showRejectDialog = true"
              >
                Decline
              </VBtn>
            </div>
          </VCardText>
        </template>

        <!-- Accepted Banner -->
        <template v-if="props.quote.status === 'accepted'">
          <VDivider />
          <VCardText class="pa-6 text-center">
            <VIcon icon="tabler-circle-check" color="success" size="48" class="mb-2" />
            <div class="text-h6 text-success">
              Quote Accepted
            </div>
            <div class="text-body-2 text-medium-emphasis">
              {{ formatDate(props.quote.accepted_at) }}
            </div>
          </VCardText>
        </template>

        <!-- Rejected Banner -->
        <template v-if="props.quote.status === 'rejected'">
          <VDivider />
          <VCardText class="pa-6 text-center">
            <VIcon icon="tabler-circle-x" color="error" size="48" class="mb-2" />
            <div class="text-h6 text-error">
              Quote Declined
            </div>
          </VCardText>
        </template>

        <!-- Expired Banner -->
        <template v-if="props.isExpired && props.quote.status === 'sent'">
          <VDivider />
          <VCardText class="pa-6 text-center">
            <VIcon icon="tabler-clock-off" color="warning" size="48" class="mb-2" />
            <div class="text-h6 text-warning">
              This quote has expired
            </div>
            <div class="text-body-2 text-medium-emphasis">
              Please contact us if you would like a new quote.
            </div>
          </VCardText>
        </template>
      </VCard>

      <!-- Reject Confirmation Dialog -->
      <VDialog v-model="showRejectDialog" max-width="450" persistent>
        <VCard>
          <VCardTitle class="text-h5 pa-5">
            Decline Quote
          </VCardTitle>
          <VCardText class="px-5 pb-2">
            Are you sure you want to decline quote <strong>{{ props.quote.number }}</strong>?
          </VCardText>
          <VCardActions class="pa-5">
            <VSpacer />
            <VBtn variant="text" :disabled="rejectForm.processing" @click="showRejectDialog = false">
              Cancel
            </VBtn>
            <VBtn
              color="error"
              variant="flat"
              :loading="rejectForm.processing"
              @click="submitReject"
            >
              Decline Quote
            </VBtn>
          </VCardActions>
        </VCard>
      </VDialog>
    </VContainer>
  </div>
</template>
