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

interface CustomerOption {
  id: number
  name: string
  email: string
  credit_balance: string
}

interface InvoiceOption {
  id: number
  number: string
  user_id: number
  total: string
  status: string
}

interface Props {
  customers: CustomerOption[]
  invoices: InvoiceOption[]
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const customerOptions = computed(() => {
  return props.customers.map((c: CustomerOption) => ({
    title: `${c.name} (${c.email}) — Balance: $${parseFloat(c.credit_balance).toFixed(2)}`,
    value: c.id,
  }))
})

const filteredInvoiceOptions = computed(() => {
  if (!form.user_id) return []
  return props.invoices
    .filter((inv: InvoiceOption) => inv.user_id === form.user_id)
    .map((inv: InvoiceOption) => ({
      title: `${inv.number} — $${parseFloat(inv.total).toFixed(2)} (${inv.status})`,
      value: inv.id,
    }))
})

const reasonTypeOptions = [
  { title: 'Late Fee', value: 'late_fee' },
  { title: 'Adjustment', value: 'adjustment' },
  { title: 'Underpayment', value: 'underpayment' },
]

const form = useForm({
  user_id: null as number | null,
  amount: '' as string,
  reason_type: '' as string,
  reason: '' as string,
  invoice_id: null as number | null,
})

function submit(): void {
  form.post('/debit-notes', { 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="/debit-notes" class="text-decoration-none">
            <VBtn icon="tabler-arrow-left" variant="text" size="small" />
          </Link>
          <span class="text-h4 font-weight-bold">Issue Debit Note</span>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Issue a debit note to deduct from a customer's account balance
        </div>
      </div>
    </div>

    <form @submit.prevent="submit">
      <VRow>
        <!-- Main Content -->
        <VCol cols="12" lg="8">
          <!-- Customer Selection -->
          <VCard title="Customer" class="mb-6">
            <VCardText>
              <VAutocomplete
                v-model="form.user_id"
                :items="customerOptions"
                label="Select Customer"
                placeholder="Search by name or email..."
                :error-messages="form.errors.user_id"
                clearable
                no-data-text="No customers found"
              />
            </VCardText>
          </VCard>

          <!-- Debit Details -->
          <VCard title="Debit Details" class="mb-6">
            <VCardText>
              <VRow>
                <VCol cols="12" md="4">
                  <VTextField
                    v-model="form.amount"
                    type="number"
                    step="0.01"
                    min="0.01"
                    label="Amount"
                    prefix="$"
                    placeholder="0.00"
                    :error-messages="form.errors.amount"
                  />
                </VCol>
                <VCol cols="12" md="4">
                  <VSelect
                    v-model="form.reason_type"
                    :items="reasonTypeOptions"
                    label="Reason Type"
                    :error-messages="form.errors.reason_type"
                  />
                </VCol>
                <VCol cols="12" md="4">
                  <VAutocomplete
                    v-model="form.invoice_id"
                    :items="filteredInvoiceOptions"
                    label="Related Invoice (Optional)"
                    placeholder="Select an invoice..."
                    :error-messages="form.errors.invoice_id"
                    clearable
                    no-data-text="No invoices found for this customer"
                    :disabled="!form.user_id"
                  />
                </VCol>
              </VRow>
              <VTextarea
                v-model="form.reason"
                label="Reason"
                placeholder="Reason for issuing this debit note..."
                rows="3"
                :error-messages="form.errors.reason"
              />
            </VCardText>
          </VCard>
        </VCol>

        <!-- Sidebar -->
        <VCol cols="12" lg="4">
          <!-- 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">Debit Amount</span>
                <span class="text-body-2 font-weight-medium text-error">
                  -${{ form.amount ? parseFloat(form.amount).toFixed(2) : '0.00' }}
                </span>
              </div>
              <VDivider class="my-2" />
              <div class="text-caption text-medium-emphasis">
                This amount will be deducted from the customer's account credit balance (down to $0.00 minimum).
              </div>
            </VCardText>
          </VCard>

          <!-- Actions -->
          <VCard>
            <VCardText>
              <VBtn
                type="submit"
                color="warning"
                block
                :loading="form.processing"
                :disabled="form.processing"
                prepend-icon="tabler-receipt"
                class="mb-3"
              >
                Issue Debit Note
              </VBtn>
              <Link href="/debit-notes" class="text-decoration-none">
                <VBtn
                  variant="outlined"
                  block
                >
                  Cancel
                </VBtn>
              </Link>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </form>
  </div>
</template>
