<template>
  <div class="admin">
    <Breadcrumb :items="breadcrumbItems" />
    <div class="page-header">
      <div>
        <h2>Space Management</h2>
        <p v-if="authStore.isManager && propertyStore.currentProperty" class="property-context">
          Property: <strong>{{ propertyStore.currentProperty.name }}</strong>
        </p>
      </div>
      <button class="btn btn-primary" @click="openCreateModal">
        <Plus :size="16" />
        New Space
      </button>
    </div>

    <!-- Stats Pills -->
    <div class="stats-pills">
      <span class="stat-pill stat-pill-primary">
        <span class="stat-pill-number">{{ spaces.length }}</span>
        <span class="stat-pill-label">Total Spaces</span>
      </span>
      <span class="stat-pill stat-pill-success">
        <span class="stat-pill-number">{{ activeCount }}</span>
        <span class="stat-pill-label">Active</span>
      </span>
      <span class="stat-pill stat-pill-danger">
        <span class="stat-pill-number">{{ inactiveCount }}</span>
        <span class="stat-pill-label">Inactive</span>
      </span>
    </div>

    <!-- Loading State -->
    <div v-if="loadingSpaces" class="loading-state">
      <div class="spinner"></div>
      <p>Loading spaces...</p>
    </div>

    <!-- Empty State -->
    <div v-else-if="spaces.length === 0" class="empty-state">
      <Building2 :size="48" class="empty-icon" />
      <p>No spaces created yet</p>
      <button class="btn btn-primary" @click="openCreateModal">Create your first space</button>
    </div>

    <!-- Space Cards Grid -->
    <div v-else class="space-cards">
      <div v-for="space in spaces" :key="space.id" class="space-card">
        <div class="space-card-header">
          <div class="space-card-title">
            <h3>{{ space.name }}</h3>
            <span :class="['badge', space.is_active ? 'badge-active' : 'badge-inactive']">
              {{ space.is_active ? 'Active' : 'Inactive' }}
            </span>
          </div>
          <div class="space-card-actions">
            <button
              class="icon-btn"
              title="Edit space"
              @click="startEdit(space)"
              :disabled="loading"
            >
              <Pencil :size="16" />
            </button>
            <button
              :class="['icon-btn', space.is_active ? 'icon-btn-warning' : 'icon-btn-success']"
              :title="space.is_active ? 'Deactivate' : 'Activate'"
              @click="toggleStatus(space)"
              :disabled="loading"
            >
              <Power :size="16" />
            </button>
          </div>
        </div>
        <div class="space-card-meta">
          <span class="meta-badge meta-type">{{ space.type === 'sala' ? 'Sala' : 'Birou' }}</span>
          <span class="meta-item">
            <UsersIcon :size="14" />
            {{ space.capacity }}
          </span>
          <span v-if="space.property_name" class="meta-badge meta-property" :title="'Property: ' + space.property_name">
            <Landmark :size="11" />
            {{ space.property_name }}
          </span>
        </div>
        <p v-if="space.description" class="space-card-desc">{{ space.description }}</p>
      </div>
    </div>

    <!-- Create/Edit Space Modal -->
    <div v-if="showModal" class="modal" @click.self="closeModal">
      <div class="modal-content">
        <h3>{{ editingSpace ? 'Edit Space' : 'Create New Space' }}</h3>
        <form @submit.prevent="handleSubmit" class="space-form">
          <div class="form-group">
            <label for="name">Name *</label>
            <input
              id="name"
              v-model="formData.name"
              type="text"
              required
              placeholder="Conference Room A"
            />
          </div>

          <div class="form-group">
            <label for="property">Property *</label>
            <select id="property" v-model.number="formData.property_id" required>
              <option v-for="prop in availableProperties" :key="prop.id" :value="prop.id">
                {{ prop.name }}
              </option>
            </select>
          </div>

          <div class="form-group">
            <label for="type">Type *</label>
            <select id="type" v-model="formData.type" required>
              <option value="sala">Sala</option>
              <option value="birou">Birou</option>
            </select>
          </div>

          <div class="form-group">
            <label for="capacity">Capacity *</label>
            <input
              id="capacity"
              v-model.number="formData.capacity"
              type="number"
              required
              min="1"
              placeholder="10"
            />
          </div>

          <div class="form-group">
            <label for="description">Description</label>
            <textarea
              id="description"
              v-model="formData.description"
              rows="3"
              placeholder="Optional description..."
            ></textarea>
          </div>

          <!-- Per-Space Scheduling Settings -->
          <div class="form-section-header">
            <h4>Per-Space Scheduling Settings</h4>
            <p class="help-text">Leave blank to use global defaults</p>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="working_hours_start">Working Hours Start (hour)</label>
              <input
                id="working_hours_start"
                v-model.number="formData.working_hours_start"
                type="number"
                min="0"
                max="23"
                placeholder="e.g., 8 (leave blank for global)"
              />
            </div>

            <div class="form-group">
              <label for="working_hours_end">Working Hours End (hour)</label>
              <input
                id="working_hours_end"
                v-model.number="formData.working_hours_end"
                type="number"
                min="0"
                max="23"
                placeholder="e.g., 20 (leave blank for global)"
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="min_duration_minutes">Min Duration (minutes)</label>
              <input
                id="min_duration_minutes"
                v-model.number="formData.min_duration_minutes"
                type="number"
                min="15"
                step="15"
                placeholder="e.g., 30 (leave blank for global)"
              />
            </div>

            <div class="form-group">
              <label for="max_duration_minutes">Max Duration (minutes)</label>
              <input
                id="max_duration_minutes"
                v-model.number="formData.max_duration_minutes"
                type="number"
                min="15"
                step="15"
                placeholder="e.g., 480 (leave blank for global)"
              />
            </div>
          </div>

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

          <div class="form-actions">
            <button type="submit" class="btn btn-primary" :disabled="loading">
              {{ editingSpace ? 'Update' : 'Create' }}
            </button>
            <button type="button" class="btn btn-secondary" @click="closeModal">
              Cancel
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { spacesApi, propertiesApi, handleApiError } from '@/services/api'
import { useAuthStore } from '@/stores/auth'
import { usePropertyStore } from '@/stores/property'
import Breadcrumb from '@/components/Breadcrumb.vue'
import { Building2, Plus, Pencil, Power, Users as UsersIcon, Landmark } from 'lucide-vue-next'
import type { Space, Property } from '@/types'

const authStore = useAuthStore()
const propertyStore = usePropertyStore()

const breadcrumbItems = [
  { label: 'Dashboard', to: '/dashboard' },
  { label: 'Admin' }
]

const spaces = ref<Space[]>([])
const availableProperties = ref<Property[]>([])
const loadingSpaces = ref(false)
const activeCount = computed(() => spaces.value.filter(s => s.is_active).length)
const inactiveCount = computed(() => spaces.value.filter(s => !s.is_active).length)
const loading = ref(false)
const error = ref('')
const success = ref('')
const editingSpace = ref<Space | null>(null)
const showModal = ref(false)

const formData = ref({
  name: '',
  type: 'sala',
  capacity: 1,
  description: '',
  property_id: null as number | null,
  working_hours_start: null as number | null,
  working_hours_end: null as number | null,
  min_duration_minutes: null as number | null,
  max_duration_minutes: null as number | null
})

const loadProperties = async () => {
  try {
    if (authStore.isSuperadmin) {
      availableProperties.value = await propertiesApi.listAll()
    } else {
      availableProperties.value = await propertiesApi.list()
    }
  } catch {}
}

const loadSpaces = async () => {
  loadingSpaces.value = true
  error.value = ''
  try {
    spaces.value = await spacesApi.list()
  } catch (err) {
    error.value = handleApiError(err)
  } finally {
    loadingSpaces.value = false
  }
}

const handleSubmit = async () => {
  loading.value = true
  error.value = ''
  success.value = ''

  try {
    if (editingSpace.value) {
      await spacesApi.update(editingSpace.value.id, formData.value)
      success.value = 'Space updated successfully!'
    } else {
      await spacesApi.create(formData.value)
      success.value = 'Space created successfully!'
    }

    await loadSpaces()
    closeModal()

    // Clear success message after 3 seconds
    setTimeout(() => {
      success.value = ''
    }, 3000)
  } catch (err) {
    error.value = handleApiError(err)
  } finally {
    loading.value = false
  }
}

const openCreateModal = () => {
  resetForm()
  // Auto-select current property context or first available
  if (propertyStore.currentPropertyId) {
    formData.value.property_id = propertyStore.currentPropertyId
  } else if (availableProperties.value.length > 0) {
    formData.value.property_id = availableProperties.value[0].id
  }
  showModal.value = true
}

const startEdit = (space: Space) => {
  editingSpace.value = space
  formData.value = {
    name: space.name,
    type: space.type,
    capacity: space.capacity,
    description: space.description || '',
    property_id: space.property_id ?? null,
    working_hours_start: space.working_hours_start ?? null,
    working_hours_end: space.working_hours_end ?? null,
    min_duration_minutes: space.min_duration_minutes ?? null,
    max_duration_minutes: space.max_duration_minutes ?? null
  }
  showModal.value = true
}

const closeModal = () => {
  showModal.value = false
  resetForm()
}

const resetForm = () => {
  editingSpace.value = null
  formData.value = {
    name: '',
    type: 'sala',
    capacity: 1,
    description: '',
    working_hours_start: null,
    working_hours_end: null,
    min_duration_minutes: null,
    max_duration_minutes: null,
    property_id: null
  }
}

const toggleStatus = async (space: Space) => {
  loading.value = true
  error.value = ''
  success.value = ''

  try {
    await spacesApi.updateStatus(space.id, !space.is_active)
    success.value = `Space ${space.is_active ? 'deactivated' : 'activated'} successfully!`
    await loadSpaces()

    setTimeout(() => {
      success.value = ''
    }, 3000)
  } catch (err) {
    error.value = handleApiError(err)
  } finally {
    loading.value = false
  }
}

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

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.page-header h2 {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  color: var(--color-text-primary);
}

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

.property-context strong {
  color: var(--color-accent);
}

/* Stats Pills */
.stats-pills {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 24px;
}

.stat-pill {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
  border: 1px solid transparent;
  height: 40px;
  box-sizing: border-box;
}

.stat-pill-number {
  font-weight: 700;
  font-size: 15px;
}

.stat-pill-primary {
  background: var(--color-accent-light);
  color: var(--color-accent);
  border-color: color-mix(in srgb, var(--color-accent) 20%, transparent);
}

.stat-pill-success {
  background: color-mix(in srgb, var(--color-success) 12%, transparent);
  color: var(--color-success);
  border-color: color-mix(in srgb, var(--color-success) 20%, transparent);
}

.stat-pill-danger {
  background: color-mix(in srgb, var(--color-danger) 12%, transparent);
  color: var(--color-danger);
  border-color: color-mix(in srgb, var(--color-danger) 20%, transparent);
}

/* Loading & Empty States */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 20px;
  color: var(--color-text-secondary);
}

.spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--color-border);
  border-top-color: var(--color-accent);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60px 20px;
  color: var(--color-text-muted);
  gap: 16px;
}

.empty-icon {
  color: var(--color-border);
}

.empty-state p {
  color: var(--color-text-secondary);
  font-size: 15px;
}

/* Space Cards Grid */
.space-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
}

.space-card {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  padding: 20px;
  transition: all var(--transition-fast);
}

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

.space-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}

.space-card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.space-card-title h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-primary);
}

.space-card-actions {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
}

.icon-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: var(--radius-sm);
  border: 1px solid var(--color-border);
  background: var(--color-surface);
  color: var(--color-text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.icon-btn:hover {
  color: var(--color-accent);
  border-color: var(--color-accent);
  background: var(--color-accent-light);
}

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

.icon-btn-warning:hover {
  color: var(--color-warning);
  border-color: var(--color-warning);
  background: color-mix(in srgb, var(--color-warning) 10%, transparent);
}

.icon-btn-success:hover {
  color: var(--color-success);
  border-color: var(--color-success);
  background: color-mix(in srgb, var(--color-success) 10%, transparent);
}

.space-card-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.meta-badge {
  display: inline-block;
  padding: 3px 10px;
  border-radius: 10px;
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.meta-type {
  background: var(--color-accent-light);
  color: var(--color-accent);
}

.meta-property {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  background: color-mix(in srgb, var(--color-warning) 12%, transparent);
  color: var(--color-warning);
}

.meta-item {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: var(--color-text-secondary);
}

.space-card-desc {
  margin: 10px 0 0;
  font-size: 13px;
  color: var(--color-text-muted);
  line-height: 1.4;
}

.badge {
  display: inline-block;
  padding: 3px 10px;
  border-radius: 10px;
  font-size: 11px;
  font-weight: 600;
}

.badge-active {
  background: color-mix(in srgb, var(--color-success) 15%, transparent);
  color: var(--color-success);
}

.badge-inactive {
  background: color-mix(in srgb, var(--color-danger) 15%, transparent);
  color: var(--color-danger);
}

/* Buttons */
.btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 10px 20px;
  border: none;
  border-radius: var(--radius-sm);
  font-size: 14px;
  font-weight: 500;
  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-secondary {
  background: var(--color-bg-tertiary);
  color: var(--color-text-primary);
}

.btn-secondary:hover:not(:disabled) {
  background: var(--color-border);
}

/* Form Styles */
.space-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-section-header {
  margin-top: 16px;
  margin-bottom: 8px;
  padding-top: 16px;
  border-top: 1px solid var(--color-border);
}

.form-section-header h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text-primary);
}

.help-text {
  margin: 0;
  font-size: 13px;
  color: var(--color-text-secondary);
}

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

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

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

.form-group input,
.form-group select,
.form-group textarea {
  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);
}

.form-group input:focus,
.form-group select: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);
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

.error {
  padding: 12px;
  background: color-mix(in srgb, var(--color-danger) 10%, transparent);
  color: var(--color-danger);
  border-radius: var(--radius-sm);
  margin-top: 12px;
}

.success {
  padding: 12px;
  background: color-mix(in srgb, var(--color-success) 10%, transparent);
  color: var(--color-success);
  border-radius: var(--radius-sm);
  margin-top: 12px;
}

/* Modal */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: var(--color-surface);
  border-radius: var(--radius-lg);
  padding: 28px;
  max-width: 600px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: var(--shadow-lg);
}

.modal-content h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: var(--color-text-primary);
}

/* Responsive */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
  }

  .space-cards {
    grid-template-columns: 1fr;
  }

  .stats-pills {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
  }

  .stat-pill {
    justify-content: center;
  }
}

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