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

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

interface InvoiceLineItem {
  id: number
  description: string
  amount: string
  quantity: number
}

interface InvoiceDetail {
  id: number
  user_id: number
  number: string
  total: string
  tax: string
  currency: string
  status: string
  gateway: string | null
  notes: string | null
  due_date: string | null
  created_at: string
  user: InvoiceUser | null
  items: InvoiceLineItem[]
}

interface LineItemForm {
  description: string
  quantity: number
  unit_price: string
}

interface Props {
  invoice: InvoiceDetail
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

function formatDateForInput(dateStr: string | null): string {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toISOString().split('T')[0]
}

function itemsToFormItems(items: InvoiceLineItem[]): LineItemForm[] {
  return items.map((item: InvoiceLineItem) => ({
    description: item.description,
    quantity: item.quantity,
    unit_price: item.amount,
  }))
}

const form = useForm({
  items: itemsToFormItems(props.invoice.items),
  due_date: formatDateForInput(props.invoice.due_date),
  notes: props.invoice.notes ?? '',
})

function addLineItem(): void {
  form.items.push({ description: '', quantity: 1, unit_price: '' })
}

function removeLineItem(index: number): void {
  if (form.items.length > 1) {
    form.items.splice(index, 1)
  }
}

function lineTotal(item: LineItemForm): number {
  return (parseFloat(item.unit_price) || 0) * (item.quantity || 0)
}

const subtotal = computed<number>(() => {
  return form.items.reduce((sum: number, item: LineItemForm) => sum + lineTotal(item), 0)
})

function submit(): void {
  form.put(`/invoices/${props.invoice.id}`, {
    preserveScroll: true,
  })
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="d-flex align-center gap-2 mb-1">
          <Link :href="`/invoices/${invoice.id}`" class="text-decoration-none">
            <VBtn icon="tabler-arrow-left" variant="text" size="small" />
          </Link>
          <span class="text-h4 font-weight-bold">Edit Invoice {{ invoice.number }}</span>
          <VChip
            :color="resolveInvoiceStatusColor(invoice.status)"
            size="small"
            class="text-capitalize"
          >
            {{ invoice.status }}
          </VChip>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          {{ invoice.user?.name ?? 'Unknown Customer' }} &middot; {{ invoice.user?.email ?? '' }}
        </div>
      </div>
    </div>

    <form @submit.prevent="submit">
      <VRow>
        <!-- Main Content -->
        <VCol cols="12" lg="8">
          <!-- Line Items -->
          <VCard title="Line Items" class="mb-6">
            <VCardText>
              <!-- Items Header -->
              <VRow class="mb-2 d-none d-md-flex">
                <VCol cols="12" md="5">
                  <span class="text-body-2 font-weight-medium text-medium-emphasis">Description</span>
                </VCol>
                <VCol cols="12" md="2">
                  <span class="text-body-2 font-weight-medium text-medium-emphasis">Qty</span>
                </VCol>
                <VCol cols="12" md="3">
                  <span class="text-body-2 font-weight-medium text-medium-emphasis">Unit Price</span>
                </VCol>
                <VCol cols="12" md="2">
                  <span class="text-body-2 font-weight-medium text-medium-emphasis">Total</span>
                </VCol>
              </VRow>

              <VDivider class="mb-4 d-none d-md-flex" />

              <!-- Item Rows -->
              <div
                v-for="(item, index) in form.items"
                :key="index"
                class="mb-3"
              >
                <VRow align="center">
                  <VCol cols="12" md="5">
                    <VTextField
                      v-model="item.description"
                      placeholder="Item description"
                      density="compact"
                      :error-messages="form.errors[`items.${index}.description`]"
                    />
                  </VCol>
                  <VCol cols="6" md="2">
                    <VTextField
                      v-model.number="item.quantity"
                      type="number"
                      min="1"
                      placeholder="1"
                      density="compact"
                      :error-messages="form.errors[`items.${index}.quantity`]"
                    />
                  </VCol>
                  <VCol cols="6" md="3">
                    <VTextField
                      v-model="item.unit_price"
                      type="number"
                      step="0.01"
                      min="0"
                      placeholder="0.00"
                      density="compact"
                      prefix="$"
                      :error-messages="form.errors[`items.${index}.unit_price`]"
                    />
                  </VCol>
                  <VCol cols="10" md="1" class="text-body-2 font-weight-medium">
                    {{ formatPrice(lineTotal(item)) }}
                  </VCol>
                  <VCol cols="2" md="1">
                    <VBtn
                      icon="tabler-trash"
                      color="error"
                      variant="text"
                      size="small"
                      :disabled="form.items.length <= 1"
                      @click="removeLineItem(index)"
                    />
                  </VCol>
                </VRow>
              </div>

              <div v-if="form.errors.items" class="text-error text-body-2 mb-3">
                {{ form.errors.items }}
              </div>

              <VBtn
                variant="tonal"
                color="primary"
                prepend-icon="tabler-plus"
                size="small"
                @click="addLineItem"
              >
                Add Line Item
              </VBtn>

              <!-- Totals -->
              <VDivider class="my-4" />
              <div class="d-flex flex-column align-end ga-2">
                <div class="d-flex align-center ga-6" style="min-width: 200px;">
                  <span class="text-body-1 font-weight-bold">Total</span>
                  <VSpacer />
                  <span class="text-body-1 font-weight-bold">{{ formatPrice(subtotal) }}</span>
                </div>
              </div>
            </VCardText>
          </VCard>

          <!-- Notes -->
          <VCard title="Notes" class="mb-6">
            <VCardText>
              <VTextarea
                v-model="form.notes"
                label="Invoice Notes"
                placeholder="Optional notes to include on the invoice..."
                rows="3"
                :error-messages="form.errors.notes"
              />
            </VCardText>
          </VCard>
        </VCol>

        <!-- Sidebar -->
        <VCol cols="12" lg="4">
          <!-- Invoice Info -->
          <VCard title="Invoice Info" class="mb-6">
            <VCardText>
              <div class="d-flex justify-space-between align-center mb-3">
                <span class="text-body-2 text-medium-emphasis">Invoice #</span>
                <span class="text-body-2 font-weight-medium">{{ invoice.number }}</span>
              </div>
              <div class="d-flex justify-space-between align-center mb-3">
                <span class="text-body-2 text-medium-emphasis">Status</span>
                <VChip
                  :color="resolveInvoiceStatusColor(invoice.status)"
                  size="small"
                  class="text-capitalize"
                >
                  {{ invoice.status }}
                </VChip>
              </div>
              <div class="d-flex justify-space-between align-center mb-3">
                <span class="text-body-2 text-medium-emphasis">Customer</span>
                <span class="text-body-2 font-weight-medium">{{ invoice.user?.name ?? 'Unknown' }}</span>
              </div>
              <div class="d-flex justify-space-between align-center">
                <span class="text-body-2 text-medium-emphasis">Gateway</span>
                <span class="text-body-2 text-capitalize">{{ invoice.gateway ?? 'Manual' }}</span>
              </div>
            </VCardText>
          </VCard>

          <!-- Due Date -->
          <VCard title="Due Date" class="mb-6">
            <VCardText>
              <VTextField
                v-model="form.due_date"
                label="Due Date"
                type="date"
                :error-messages="form.errors.due_date"
              />
            </VCardText>
          </VCard>

          <!-- Summary -->
          <VCard title="Summary" class="mb-6">
            <VCardText>
              <div class="d-flex justify-space-between align-center mb-3">
                <span class="text-body-2 text-medium-emphasis">Line Items</span>
                <span class="text-body-2 font-weight-medium">{{ form.items.length }}</span>
              </div>
              <VDivider class="my-2" />
              <div class="d-flex justify-space-between align-center">
                <span class="text-body-1 font-weight-bold">Total</span>
                <span class="text-body-1 font-weight-bold">{{ formatPrice(subtotal) }}</span>
              </div>
            </VCardText>
          </VCard>

          <!-- Actions -->
          <VCard>
            <VCardText>
              <VBtn
                type="submit"
                color="primary"
                block
                :loading="form.processing"
                :disabled="form.processing"
                prepend-icon="tabler-check"
                class="mb-3"
              >
                Update Invoice
              </VBtn>
              <Link :href="`/invoices/${invoice.id}`" class="text-decoration-none">
                <VBtn
                  variant="outlined"
                  block
                >
                  Cancel
                </VBtn>
              </Link>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </form>
  </div>
</template>
