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

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

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

interface Props {
  customers: CustomerOption[]
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const recipientType = ref<'customer' | 'prospect'>('customer')

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

const form = useForm({
  user_id: null as number | null,
  prospect_email: '',
  prospect_name: '',
  items: [{ description: '', quantity: 1, unit_price: '' }] as LineItem[],
  tax: '0',
  currency: 'USD',
  notes: '',
  valid_until: '',
})

const subtotal = computed<number>(() => {
  return form.items.reduce((sum: number, item: LineItem) => {
    return sum + ((parseFloat(item.unit_price) || 0) * item.quantity)
  }, 0)
})

const total = computed<number>(() => {
  return subtotal.value + (parseFloat(form.tax) || 0)
})

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

function removeItem(index: number): void {
  if (form.items.length <= 1) return
  form.items.splice(index, 1)
}

function submit(): void {
  // Clear the field we're not using
  if (recipientType.value === 'customer') {
    form.prospect_email = ''
    form.prospect_name = ''
  } else {
    form.user_id = null
  }

  form.post('/quotes', { 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="/quotes" class="text-decoration-none">
            <VBtn icon="tabler-arrow-left" variant="text" size="small" />
          </Link>
          <span class="text-h4 font-weight-bold">Create Quote</span>
        </div>
        <div class="text-body-2 text-medium-emphasis ms-10">
          Create a new quote or estimate for a customer or prospect
        </div>
      </div>
    </div>

    <form @submit.prevent="submit">
      <VRow>
        <!-- Main Content -->
        <VCol cols="12" lg="8">
          <!-- Recipient -->
          <VCard title="Recipient" class="mb-6">
            <VCardText>
              <VBtnToggle
                v-model="recipientType"
                color="primary"
                mandatory
                density="compact"
                class="mb-4"
              >
                <VBtn value="customer">
                  Existing Customer
                </VBtn>
                <VBtn value="prospect">
                  New Prospect
                </VBtn>
              </VBtnToggle>

              <div v-if="recipientType === 'customer'">
                <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"
                />
              </div>

              <div v-else>
                <VRow>
                  <VCol cols="12" md="6">
                    <VTextField
                      v-model="form.prospect_name"
                      label="Name"
                      placeholder="John Doe"
                      :error-messages="form.errors.prospect_name"
                    />
                  </VCol>
                  <VCol cols="12" md="6">
                    <VTextField
                      v-model="form.prospect_email"
                      label="Email"
                      type="email"
                      placeholder="john@example.com"
                      :error-messages="form.errors.prospect_email"
                    />
                  </VCol>
                </VRow>
              </div>
            </VCardText>
          </VCard>

          <!-- Line Items -->
          <VCard title="Line Items" class="mb-6">
            <VCardText>
              <div v-for="(item, index) in form.items" :key="index" class="mb-4">
                <VRow align="center">
                  <VCol cols="12" md="5">
                    <VTextField
                      v-model="item.description"
                      label="Description"
                      placeholder="Service description..."
                      density="compact"
                      :error-messages="(form.errors as Record<string, string>)[`items.${index}.description`]"
                    />
                  </VCol>
                  <VCol cols="4" md="2">
                    <VTextField
                      v-model.number="item.quantity"
                      label="Qty"
                      type="number"
                      min="1"
                      density="compact"
                      :error-messages="(form.errors as Record<string, string>)[`items.${index}.quantity`]"
                    />
                  </VCol>
                  <VCol cols="5" md="3">
                    <VTextField
                      v-model="item.unit_price"
                      label="Unit Price"
                      type="number"
                      step="0.01"
                      min="0"
                      prefix="$"
                      density="compact"
                      :error-messages="(form.errors as Record<string, string>)[`items.${index}.unit_price`]"
                    />
                  </VCol>
                  <VCol cols="2" md="1" class="text-end text-body-2 font-weight-medium">
                    ${{ ((parseFloat(item.unit_price) || 0) * item.quantity).toFixed(2) }}
                  </VCol>
                  <VCol cols="1">
                    <VBtn
                      v-if="form.items.length > 1"
                      icon="tabler-trash"
                      variant="text"
                      size="small"
                      color="error"
                      @click="removeItem(index)"
                    />
                  </VCol>
                </VRow>
                <VDivider v-if="index < form.items.length - 1" class="mt-2" />
              </div>

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

              <div v-if="form.errors.items" class="text-error text-caption mt-2">
                {{ form.errors.items }}
              </div>
            </VCardText>
          </VCard>

          <!-- Notes -->
          <VCard title="Notes" class="mb-6">
            <VCardText>
              <VTextarea
                v-model="form.notes"
                label="Notes (visible to recipient)"
                placeholder="Additional notes or terms..."
                rows="3"
                :error-messages="form.errors.notes"
              />
            </VCardText>
          </VCard>
        </VCol>

        <!-- Sidebar -->
        <VCol cols="12" lg="4">
          <!-- Quote Settings -->
          <VCard title="Settings" class="mb-6">
            <VCardText>
              <VSelect
                v-model="form.currency"
                :items="['USD', 'EUR', 'GBP', 'CAD', 'AUD']"
                label="Currency"
                :error-messages="form.errors.currency"
                class="mb-4"
              />
              <VTextField
                v-model="form.tax"
                label="Tax Amount"
                type="number"
                step="0.01"
                min="0"
                prefix="$"
                :error-messages="form.errors.tax"
                class="mb-4"
              />
              <VTextField
                v-model="form.valid_until"
                label="Valid Until"
                type="date"
                :error-messages="form.errors.valid_until"
              />
            </VCardText>
          </VCard>

          <!-- Summary -->
          <VCard title="Summary" class="mb-6">
            <VCardText>
              <div class="d-flex justify-space-between align-center mb-2">
                <span class="text-body-2 text-medium-emphasis">Subtotal</span>
                <span class="text-body-2 font-weight-medium">${{ subtotal.toFixed(2) }}</span>
              </div>
              <div class="d-flex justify-space-between align-center mb-2">
                <span class="text-body-2 text-medium-emphasis">Tax</span>
                <span class="text-body-2 font-weight-medium">${{ (parseFloat(form.tax) || 0).toFixed(2) }}</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 text-primary">${{ total.toFixed(2) }}</span>
              </div>
            </VCardText>
          </VCard>

          <!-- Actions -->
          <VCard>
            <VCardText>
              <VBtn
                type="submit"
                color="primary"
                block
                :loading="form.processing"
                :disabled="form.processing"
                prepend-icon="tabler-file-description"
                class="mb-3"
              >
                Create Quote
              </VBtn>
              <Link href="/quotes" class="text-decoration-none">
                <VBtn variant="outlined" block>
                  Cancel
                </VBtn>
              </Link>
            </VCardText>
          </VCard>
        </VCol>
      </VRow>
    </form>
  </div>
</template>
