<template>
  <div class="public-booking-container">
    <div class="public-booking-card card">
      <h2>Book a Space</h2>
      <p class="subtitle">Reserve a meeting room or workspace without an account</p>

      <!-- Step 1: Select Property -->
      <div v-if="step === 'property'">
        <div v-if="loadingProperties" class="loading-inline">Loading properties...</div>
        <div v-else-if="properties.length === 0" class="empty-msg">No public properties available.</div>
        <div v-else class="property-list">
          <div
            v-for="prop in properties"
            :key="prop.id"
            class="selectable-card"
            @click="selectProperty(prop)"
          >
            <h4>{{ prop.name }}</h4>
            <p v-if="prop.description" class="card-desc">{{ prop.description }}</p>
            <p v-if="prop.address" class="card-meta">{{ prop.address }}</p>
            <span class="card-count">{{ prop.space_count || 0 }} spaces</span>
          </div>
        </div>
      </div>

      <!-- Step 2: Select Space -->
      <div v-else-if="step === 'space'">
        <button class="btn-back" @click="step = 'property'">Back to properties</button>
        <h3 class="step-title">{{ selectedProperty?.name }} - Choose a Space</h3>
        <div v-if="loadingSpaces" class="loading-inline">Loading spaces...</div>
        <div v-else-if="spaces.length === 0" class="empty-msg">No spaces available.</div>
        <div v-else class="space-list">
          <div
            v-for="sp in spaces"
            :key="sp.id"
            class="selectable-card"
            @click="selectSpace(sp)"
          >
            <h4>{{ sp.name }}</h4>
            <div class="card-meta-row">
              <span>{{ formatType(sp.type) }}</span>
              <span>Capacity: {{ sp.capacity }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Step 3: Booking Form -->
      <div v-else-if="step === 'form'">
        <button class="btn-back" @click="step = 'space'">Back to spaces</button>
        <h3 class="step-title">Book {{ selectedSpace?.name }}</h3>

        <form @submit.prevent="handleSubmit" class="booking-form">
          <div class="form-group">
            <label for="guest_name">Your Name *</label>
            <input id="guest_name" v-model="form.guest_name" type="text" required placeholder="John Doe" />
          </div>

          <div class="form-group">
            <label for="guest_email">Your Email *</label>
            <input id="guest_email" v-model="form.guest_email" type="email" required placeholder="john@example.com" />
          </div>

          <div class="form-group">
            <label for="guest_organization">Organization (optional)</label>
            <input id="guest_organization" v-model="form.guest_organization" type="text" placeholder="Company name" />
          </div>

          <div class="form-group">
            <label for="title">Booking Title *</label>
            <input id="title" v-model="form.title" type="text" required placeholder="Team meeting" />
          </div>

          <div class="form-group">
            <label for="description">Description (optional)</label>
            <textarea id="description" v-model="form.description" rows="2" placeholder="Additional details..."></textarea>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="date">Date *</label>
              <input id="date" v-model="form.date" type="date" required :min="minDate" />
            </div>
            <div class="form-group">
              <label for="start_time">Start Time *</label>
              <input id="start_time" v-model="form.start_time" type="time" required />
            </div>
            <div class="form-group">
              <label for="end_time">End Time *</label>
              <input id="end_time" v-model="form.end_time" type="time" required />
            </div>
          </div>

          <div v-if="error" class="error">{{ error }}</div>

          <button type="submit" class="btn btn-primary btn-block" :disabled="submitting">
            {{ submitting ? 'Submitting...' : 'Submit Booking Request' }}
          </button>
        </form>
      </div>

      <!-- Step 4: Success -->
      <div v-else-if="step === 'success'" class="success-state">
        <div class="success-icon">&#10003;</div>
        <h3>Booking Request Sent!</h3>
        <p>Your booking request has been submitted. You will receive updates at <strong>{{ form.guest_email }}</strong>.</p>
        <button class="btn btn-primary" @click="resetForm">Book Another</button>
      </div>

      <p class="login-hint">
        Already have an account? <router-link to="/login">Sign in</router-link>
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { publicApi, handleApiError } from '@/services/api'
import type { Property, Space } from '@/types'

const route = useRoute()

const step = ref<'property' | 'space' | 'form' | 'success'>('property')
const loadingProperties = ref(false)
const loadingSpaces = ref(false)
const submitting = ref(false)
const error = ref('')
const properties = ref<Property[]>([])
const spaces = ref<Space[]>([])
const selectedProperty = ref<Property | null>(null)
const selectedSpace = ref<Space | null>(null)

const form = ref({
  guest_name: '',
  guest_email: '',
  guest_organization: '',
  title: '',
  description: '',
  date: '',
  start_time: '',
  end_time: ''
})

const minDate = computed(() => new Date().toISOString().split('T')[0])

const formatType = (type: string): string => {
  const map: Record<string, string> = {
    desk: 'Desk', meeting_room: 'Meeting Room', conference_room: 'Conference Room',
    sala: 'Sala', birou: 'Birou'
  }
  return map[type] || type
}

const loadProperties = async () => {
  loadingProperties.value = true
  try {
    properties.value = await publicApi.getProperties()
    // If propertyId in route, auto-select
    const pid = route.params.propertyId
    if (pid) {
      const prop = properties.value.find(p => p.id === Number(pid))
      if (prop) {
        selectProperty(prop)
      }
    }
  } catch (err) {
    error.value = handleApiError(err)
  } finally {
    loadingProperties.value = false
  }
}

const selectProperty = async (prop: Property) => {
  selectedProperty.value = prop
  step.value = 'space'
  loadingSpaces.value = true
  try {
    spaces.value = await publicApi.getPropertySpaces(prop.id)
  } catch (err) {
    error.value = handleApiError(err)
  } finally {
    loadingSpaces.value = false
  }
}

const selectSpace = (sp: Space) => {
  selectedSpace.value = sp
  step.value = 'form'
  error.value = ''
}

const handleSubmit = async () => {
  error.value = ''
  if (!selectedSpace.value) return

  if (form.value.start_time >= form.value.end_time) {
    error.value = 'End time must be after start time'
    return
  }

  submitting.value = true
  try {
    await publicApi.createBooking({
      space_id: selectedSpace.value.id,
      start_datetime: `${form.value.date}T${form.value.start_time}:00`,
      end_datetime: `${form.value.date}T${form.value.end_time}:00`,
      title: form.value.title,
      description: form.value.description || undefined,
      guest_name: form.value.guest_name,
      guest_email: form.value.guest_email,
      guest_organization: form.value.guest_organization || undefined
    })
    step.value = 'success'
  } catch (err) {
    error.value = handleApiError(err)
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  step.value = 'property'
  selectedProperty.value = null
  selectedSpace.value = null
  form.value = {
    guest_name: '',
    guest_email: '',
    guest_organization: '',
    title: '',
    description: '',
    date: '',
    start_time: '',
    end_time: ''
  }
  error.value = ''
}

onMounted(() => {
  loadProperties()
})
</script>

<style scoped>
.public-booking-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  padding: 2rem 1rem;
  background: var(--color-bg-primary);
}

.public-booking-card {
  width: 100%;
  max-width: 560px;
}

h2 {
  text-align: center;
  margin-bottom: 0.25rem;
  color: var(--color-text-primary);
}

.subtitle {
  text-align: center;
  color: var(--color-text-secondary);
  margin-bottom: 1.5rem;
}

.step-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
  margin-bottom: 16px;
}

.btn-back {
  background: none;
  border: none;
  color: var(--color-accent);
  font-size: 14px;
  cursor: pointer;
  padding: 0;
  margin-bottom: 12px;
  font-weight: 500;
}

.btn-back:hover {
  text-decoration: underline;
}

.loading-inline {
  text-align: center;
  padding: 24px;
  color: var(--color-text-secondary);
}

.empty-msg {
  text-align: center;
  padding: 24px;
  color: var(--color-text-muted);
}

.property-list, .space-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.selectable-card {
  padding: 16px;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all var(--transition-fast);
  background: var(--color-bg-secondary);
}

.selectable-card:hover {
  border-color: var(--color-accent);
  box-shadow: var(--shadow-sm);
}

.selectable-card h4 {
  margin: 0 0 4px;
  font-size: 16px;
  color: var(--color-text-primary);
}

.card-desc {
  font-size: 14px;
  color: var(--color-text-secondary);
  margin: 0 0 4px;
}

.card-meta {
  font-size: 13px;
  color: var(--color-text-muted);
  margin: 0 0 4px;
}

.card-meta-row {
  display: flex;
  gap: 16px;
  font-size: 13px;
  color: var(--color-text-secondary);
}

.card-count {
  font-size: 12px;
  font-weight: 500;
  color: var(--color-accent);
}

.booking-form {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 12px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.form-group label {
  font-weight: 500;
  font-size: 14px;
  color: var(--color-text-primary);
}

.form-group input,
.form-group textarea,
.form-group select {
  padding: 8px 12px;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-sm);
  font-size: 14px;
  background: var(--color-surface);
  color: var(--color-text-primary);
  font-family: inherit;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: var(--color-accent);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-accent) 15%, transparent);
}

.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 10px 20px;
  border: none;
  border-radius: var(--radius-sm);
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all var(--transition-fast);
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: var(--color-accent);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: var(--color-accent-hover);
}

.btn-block {
  width: 100%;
  margin-top: 0.5rem;
}

.error {
  padding: 10px 14px;
  background: color-mix(in srgb, var(--color-danger) 10%, transparent);
  border-left: 3px solid var(--color-danger);
  border-radius: var(--radius-sm);
  color: var(--color-danger);
  font-size: 14px;
}

.success-state {
  text-align: center;
  padding: 24px 0;
}

.success-icon {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: color-mix(in srgb, var(--color-success) 15%, transparent);
  color: var(--color-success);
  font-size: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 16px;
}

.success-state h3 {
  color: var(--color-success);
  margin-bottom: 8px;
}

.success-state p {
  color: var(--color-text-secondary);
  margin-bottom: 20px;
}

.login-hint {
  text-align: center;
  margin-top: 1.5rem;
  padding-top: 1rem;
  border-top: 1px solid var(--color-border);
  color: var(--color-text-secondary);
  font-size: 14px;
}

.login-hint a {
  color: var(--color-accent);
  text-decoration: none;
}

.login-hint a:hover {
  text-decoration: underline;
}

@media (max-width: 640px) {
  .form-row {
    grid-template-columns: 1fr;
  }
}
</style>
