<script setup lang="ts">
import { ref, computed } from 'vue'
import { api } from '@/api/client'
import { useCart } from '@/composables/useCart'
import { useNostr } from '@/composables/useNostr'
import type { CreateOrderRequest, CreateOrderResponse, ApiError } from '@shared/types'
import GlassInput from '@/components/ui/GlassInput.vue'
import GlassButton from '@/components/ui/GlassButton.vue'
import SatsDisplay from '@/components/ui/SatsDisplay.vue'
import NostrIdentity from '@/components/checkout/NostrIdentity.vue'

const { items, totalSats, clearCart } = useCart()
const { pubkey } = useNostr()

const name = ref('')
const line1 = ref('')
const line2 = ref('')
const city = ref('')
const state = ref('')
const postalCode = ref('')
const country = ref('')
const email = ref('')
const note = ref('')
const isSubmitting = ref(false)
const errorMessage = ref('')

const canSubmit = computed(() => name.value && line1.value && city.value && postalCode.value && country.value && items.value.length > 0)

async function handleCheckout() {
  if (!canSubmit.value) return
  isSubmitting.value = true
  errorMessage.value = ''

  const order: CreateOrderRequest = {
    items: items.value.map((i) => ({ productId: i.productId, size: i.size, quantity: i.quantity })),
    shippingAddress: { name: name.value, line1: line1.value, line2: line2.value || undefined, city: city.value, state: state.value || undefined, postalCode: postalCode.value, country: country.value },
    email: email.value || undefined,
    nostrPubkey: pubkey.value || undefined,
    note: note.value || undefined,
  }

  try {
    const res = await api.post('/api/orders', order)
    if (res.ok) {
      const data = await api.json<CreateOrderResponse>(res)
      clearCart()
      window.location.href = data.invoiceUrl
    } else {
      const err = await api.json<ApiError>(res)
      errorMessage.value = err.error.message
    }
  } catch {
    errorMessage.value = 'Failed to create order. Please try again.'
  } finally {
    isSubmitting.value = false
  }
}
</script>

<template>
  <div class="checkout-page">
    <h1>Checkout</h1>
    <div v-if="items.length === 0" class="empty"><p>Your cart is empty.</p><router-link to="/" class="btn btn-ghost">Continue Shopping</router-link></div>
    <form v-else @submit.prevent="handleCheckout" class="checkout-layout">
      <div class="checkout-form">
        <section class="form-section glass-card">
          <h3>Shipping Address</h3>
          <div class="field"><label>Full Name</label><GlassInput v-model="name" placeholder="Name" is-required /></div>
          <div class="field"><label>Address Line 1</label><GlassInput v-model="line1" placeholder="Street address" is-required /></div>
          <div class="field"><label>Address Line 2</label><GlassInput v-model="line2" placeholder="Apartment, unit, etc. (optional)" /></div>
          <div class="field-row">
            <div class="field"><label>City</label><GlassInput v-model="city" placeholder="City" is-required /></div>
            <div class="field"><label>State/Province</label><GlassInput v-model="state" placeholder="State (optional)" /></div>
          </div>
          <div class="field-row">
            <div class="field"><label>Postal Code</label><GlassInput v-model="postalCode" placeholder="Postal code" is-required /></div>
            <div class="field"><label>Country</label><GlassInput v-model="country" placeholder="Country" is-required /></div>
          </div>
        </section>
        <section class="form-section glass-card">
          <h3>Contact (optional)</h3>
          <p class="hint">Provide email and/or Nostr for order updates. Neither is required.</p>
          <div class="field"><label>Email</label><GlassInput v-model="email" type="email" placeholder="For shipping updates (optional)" /></div>
          <NostrIdentity />
        </section>
        <section class="form-section glass-card">
          <h3>Note (optional)</h3>
          <div class="field"><textarea v-model="note" class="glass-input note-input" placeholder="Any special instructions..." rows="3" /></div>
        </section>
      </div>
      <div class="checkout-summary glass-card">
        <h3>Order Summary</h3>
        <div v-for="item in items" :key="`${item.productId}-${item.size}`" class="summary-item">
          <span>{{ item.name }} ({{ item.size }}) x{{ item.quantity }}</span>
          <SatsDisplay :sats="item.priceSats * item.quantity" />
        </div>
        <div class="summary-total"><span>Total</span><SatsDisplay :sats="totalSats" /></div>
        <div v-if="errorMessage" class="error-msg">{{ errorMessage }}</div>
        <GlassButton type="submit" :is-disabled="!canSubmit || isSubmitting" class="pay-btn">{{ isSubmitting ? 'Creating order...' : 'Pay with Bitcoin' }}</GlassButton>
        <p class="payment-note">You will be redirected to BTCPay Server to complete payment.</p>
      </div>
    </form>
  </div>
</template>

<style scoped>
h1 { font-size: 1.75rem; font-weight: 700; margin-bottom: 1.5rem; }
.empty { text-align: center; padding: 3rem 0; }
.empty p { color: var(--text-muted); margin-bottom: 1rem; }
.checkout-layout { display: grid; grid-template-columns: 1fr 360px; gap: 2rem; align-items: start; }
@media (max-width: 768px) { .checkout-layout { grid-template-columns: 1fr; } }
.checkout-form { display: flex; flex-direction: column; gap: 1.5rem; }
.form-section h3 { font-size: 1rem; font-weight: 600; margin-bottom: 1rem; }
.hint { font-size: 0.8125rem; color: var(--text-muted); margin: -0.5rem 0 1rem; }
.field { margin-bottom: 0.75rem; }
.field label { display: block; font-size: 0.8125rem; font-weight: 500; color: var(--text-secondary); margin-bottom: 0.375rem; }
.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; }
.note-input { resize: vertical; min-height: 80px; font-family: inherit; }
.checkout-summary { position: sticky; top: 80px; }
.checkout-summary h3 { font-size: 1rem; font-weight: 600; margin-bottom: 1rem; }
.summary-item { display: flex; justify-content: space-between; font-size: 0.8125rem; padding: 0.375rem 0; color: var(--text-secondary); }
.summary-total { display: flex; justify-content: space-between; border-top: 1px solid var(--glass-border); margin-top: 0.75rem; padding-top: 0.75rem; font-weight: 600; }
.error-msg { margin-top: 1rem; padding: 0.5rem 0.75rem; background: rgba(239, 68, 68, 0.1); border-radius: var(--radius-sm); color: var(--error); font-size: 0.8125rem; }
.pay-btn { width: 100%; margin-top: 1.25rem; }
.payment-note { font-size: 0.75rem; color: var(--text-muted); text-align: center; margin-top: 0.75rem; }
</style>
