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

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
  updated_at: string
  user: QuoteUser | null
  creator: QuoteUser | null
}

interface Props {
  quote: QuoteDetail
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const sendDialog = ref<boolean>(false)
const deleteDialog = ref<boolean>(false)
const sendForm = useForm({})

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

function getRecipientEmail(): string {
  return props.quote.user?.email ?? props.quote.prospect_email ?? ''
}

function submitSend(): void {
  sendForm.post(`/quotes/${props.quote.id}/send`, {
    preserveScroll: true,
    onSuccess: () => { sendDialog.value = false },
  })
}

function submitDelete(): void {
  router.delete(`/quotes/${props.quote.id}`, {
    onSuccess: () => { deleteDialog.value = false },
  })
}
</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="/quotes">
          <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">Quote {{ quote.number }}</span>
            <VChip
              :color="resolveStatusColor(quote.status)"
              size="small"
              class="text-capitalize"
            >
              {{ quote.status }}
            </VChip>
          </div>
          <div class="text-body-2 text-medium-emphasis mt-1">
            {{ getRecipientName() }} &middot; {{ getRecipientEmail() }}
          </div>
        </div>
      </div>

      <div class="d-flex gap-2">
        <VBtn
          v-if="['draft', 'sent'].includes(quote.status)"
          color="primary"
          variant="tonal"
          :disabled="sendForm.processing"
          @click="sendDialog = true"
        >
          <VIcon icon="tabler-send" start />
          Send Quote
        </VBtn>

        <Link v-if="['draft', 'sent'].includes(quote.status)" :href="`/quotes/${quote.id}/edit`">
          <VBtn color="info" variant="tonal">
            <VIcon icon="tabler-edit" start />
            Edit
          </VBtn>
        </Link>

        <VBtn
          color="secondary"
          variant="tonal"
          :href="`/quotes/${quote.id}/download`"
        >
          <VIcon icon="tabler-download" start />
          Download PDF
        </VBtn>

        <VBtn
          v-if="quote.status !== 'accepted'"
          color="error"
          variant="tonal"
          @click="deleteDialog = true"
        >
          <VIcon icon="tabler-trash" start />
          Delete
        </VBtn>
      </div>
    </div>

    <VRow>
      <!-- Quote Details -->
      <VCol cols="12" lg="4">
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-file-description" size="22" />
            <span>Quote Details</span>
          </VCardTitle>
          <VCardText>
            <VList density="compact" class="pa-0">
              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Number</span>
                </template>
                <VListItemTitle class="text-body-2 font-weight-medium">
                  {{ quote.number }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Status</span>
                </template>
                <VListItemTitle>
                  <VChip
                    :color="resolveStatusColor(quote.status)"
                    size="small"
                    class="text-capitalize"
                  >
                    {{ quote.status }}
                  </VChip>
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Currency</span>
                </template>
                <VListItemTitle class="text-body-2 text-uppercase">
                  {{ quote.currency }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Valid Until</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ formatDate(quote.valid_until) }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Sent</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ formatDateTime(quote.sent_at) }}
                </VListItemTitle>
              </VListItem>

              <VListItem v-if="quote.accepted_at">
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Accepted</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ formatDateTime(quote.accepted_at) }}
                </VListItemTitle>
              </VListItem>

              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 120px;">Created</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ formatDate(quote.created_at) }}
                </VListItemTitle>
              </VListItem>
            </VList>
          </VCardText>
        </VCard>

        <!-- Recipient Card -->
        <VCard class="mt-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-user" size="22" />
            <span>Recipient</span>
          </VCardTitle>
          <VCardText>
            <div class="d-flex align-center gap-3">
              <VAvatar color="primary" variant="tonal" size="40">
                <span class="text-body-1 font-weight-semibold">
                  {{ getRecipientName().charAt(0).toUpperCase() }}
                </span>
              </VAvatar>
              <div>
                <div class="text-body-1 font-weight-medium">
                  {{ getRecipientName() }}
                </div>
                <div class="text-body-2 text-medium-emphasis">
                  {{ getRecipientEmail() }}
                </div>
              </div>
            </div>
            <div v-if="quote.user" class="mt-3">
              <Link :href="`/customers/${quote.user.id}`">
                <VBtn variant="tonal" size="small" color="primary" block>
                  View Customer
                </VBtn>
              </Link>
            </div>
          </VCardText>
        </VCard>

        <!-- Creator Card -->
        <VCard v-if="quote.creator" class="mt-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-shield" size="22" />
            <span>Created By</span>
          </VCardTitle>
          <VCardText>
            <div class="text-body-2 font-weight-medium">
              {{ quote.creator.name }}
            </div>
            <div class="text-body-2 text-medium-emphasis">
              {{ quote.creator.email }}
            </div>
          </VCardText>
        </VCard>
      </VCol>

      <!-- Line Items & Notes -->
      <VCol cols="12" lg="8">
        <VCard class="mb-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-list" size="22" />
            <span>Line Items</span>
          </VCardTitle>

          <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 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>
            <tfoot>
              <tr>
                <td colspan="3" class="text-end text-body-2 text-medium-emphasis">
                  Subtotal
                </td>
                <td class="text-end text-body-2 font-weight-medium">
                  ${{ parseFloat(quote.subtotal).toFixed(2) }}
                </td>
              </tr>
              <tr v-if="parseFloat(quote.tax) > 0">
                <td colspan="3" class="text-end text-body-2 text-medium-emphasis">
                  Tax
                </td>
                <td class="text-end text-body-2 font-weight-medium">
                  ${{ parseFloat(quote.tax).toFixed(2) }}
                </td>
              </tr>
              <tr>
                <td colspan="3" class="text-end text-body-1 font-weight-bold">
                  Total ({{ quote.currency }})
                </td>
                <td class="text-end text-body-1 font-weight-bold text-primary">
                  ${{ parseFloat(quote.total).toFixed(2) }}
                </td>
              </tr>
            </tfoot>
          </VTable>
        </VCard>

        <!-- Notes -->
        <VCard v-if="quote.notes">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-notes" size="22" />
            <span>Notes</span>
          </VCardTitle>
          <VCardText>
            <div class="text-body-2" style="white-space: pre-wrap;">
              {{ quote.notes }}
            </div>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- Send Confirmation Dialog -->
    <VDialog v-model="sendDialog" max-width="500" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          Send Quote
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          Send quote <strong>{{ quote.number }}</strong> to <strong>{{ getRecipientEmail() }}</strong>?
          <br>
          The recipient will receive an email with a link to view, accept, or decline this quote.
        </VCardText>
        <VCardActions class="pa-5">
          <VSpacer />
          <VBtn variant="text" :disabled="sendForm.processing" @click="sendDialog = false">
            Cancel
          </VBtn>
          <VBtn
            color="primary"
            variant="flat"
            :loading="sendForm.processing"
            @click="submitSend"
          >
            Send Quote
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>

    <!-- Delete Confirmation Dialog -->
    <VDialog v-model="deleteDialog" max-width="450" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          Delete Quote
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          Are you sure you want to delete quote <strong>{{ quote.number }}</strong>?
          This action cannot be undone.
        </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>
