<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'
import { api } from '@/api'

const { t } = useI18n()
const authStore = useAuthStore()

interface Order {
  id: string
  number: number
  title: string
  description?: string
  location?: string
  status: string
  start_time?: string
  end_time?: string
  required_staff: number
  assigned_count?: number
  creator_name?: string
}

const orders = ref<Order[]>([])
const loading = ref(true)
const showCreateModal = ref(false)
const statusFilter = ref('')

const newOrder = ref({
  title: '',
  description: '',
  location: '',
  address: '',
  client_name: '',
  client_contact: '',
  start_time: '',
  end_time: '',
  required_staff: 1,
  special_instructions: ''
})

const filteredOrders = computed(() => {
  if (!statusFilter.value) return orders.value
  return orders.value.filter(o => o.status === statusFilter.value)
})

onMounted(async () => {
  await loadOrders()
})

async function loadOrders() {
  loading.value = true
  try {
    const res = await api.get<{ orders: Order[] }>('/orders')
    orders.value = res.data.orders
  } catch (e) {
    console.error('Load orders error:', e)
  } finally {
    loading.value = false
  }
}

async function createOrder() {
  try {
    await api.post('/orders', newOrder.value)
    showCreateModal.value = false
    newOrder.value = {
      title: '',
      description: '',
      location: '',
      address: '',
      client_name: '',
      client_contact: '',
      start_time: '',
      end_time: '',
      required_staff: 1,
      special_instructions: ''
    }
    await loadOrders()
  } catch (e) {
    alert(e instanceof Error ? e.message : t('messages.error'))
  }
}

function getStatusBadge(status: string) {
  const badges: Record<string, string> = {
    draft: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300',
    published: 'badge-primary',
    in_progress: 'badge-warning',
    completed: 'badge-success',
    cancelled: 'badge-danger'
  }
  return badges[status] || 'badge-secondary'
}

function getStatusLabel(status: string) {
  return t(`orders.statuses.${status}`) || status
}

function formatDate(dateStr?: string) {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString()
}
</script>

<template>
  <div class="space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
        📋 {{ t('orders.title') }}
      </h1>
      <button
        v-if="authStore.canManageOrders"
        class="btn btn-primary"
        @click="showCreateModal = true"
      >
        + {{ t('orders.new') }}
      </button>
    </div>

    <!-- Filters -->
    <div class="card">
      <div class="flex items-center gap-4">
        <label class="text-sm font-medium text-gray-700 dark:text-gray-300">{{ t('app.status') }}:</label>
        <select v-model="statusFilter" class="input w-48">
          <option value="">{{ t('app.all') }}</option>
          <option value="draft">{{ t('orders.statuses.draft') }}</option>
          <option value="scheduled">{{ t('orders.statuses.scheduled') }}</option>
          <option value="active">{{ t('orders.statuses.active') }}</option>
          <option value="completed">{{ t('orders.statuses.completed') }}</option>
          <option value="cancelled">{{ t('orders.statuses.cancelled') }}</option>
        </select>
      </div>
    </div>

    <!-- Orders List -->
    <div class="card">
      <div v-if="loading" class="text-center py-8 text-gray-500">
        {{ t('app.loading') }}
      </div>

      <div v-else-if="filteredOrders.length === 0" class="text-center py-8 text-gray-500">
        {{ t('messages.noData') }}
      </div>

      <div v-else class="divide-y divide-gray-200 dark:divide-gray-700">
        <router-link
          v-for="order in filteredOrders"
          :key="order.id"
          :to="`/orders/${order.id}`"
          class="block py-4 hover:bg-gray-50 dark:hover:bg-gray-700/50 -mx-6 px-6 transition-colors"
        >
          <div class="flex items-start justify-between">
            <div class="flex-1">
              <div class="flex items-center gap-3">
                <span class="text-sm text-gray-500 dark:text-gray-400">#{{ order.number }}</span>
                <h3 class="font-medium text-gray-900 dark:text-white">{{ order.title }}</h3>
                <span :class="['badge', getStatusBadge(order.status)]">
                  {{ getStatusLabel(order.status) }}
                </span>
              </div>
              <div class="mt-1 flex items-center gap-4 text-sm text-gray-500 dark:text-gray-400">
                <span v-if="order.location">📍 {{ order.location }}</span>
                <span v-if="order.start_time">🕐 {{ formatDate(order.start_time) }}</span>
                <span>👥 {{ order.assigned_count || 0 }}/{{ order.required_staff }}</span>
              </div>
            </div>
            <span class="text-gray-400">→</span>
          </div>
        </router-link>
      </div>
    </div>

    <!-- Create Modal -->
    <div v-if="showCreateModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div class="card w-full max-w-2xl max-h-[90vh] overflow-y-auto m-4">
        <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-6">
          {{ t('orders.new') }}
        </h2>

        <form @submit.prevent="createOrder" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ t('app.description') }} *</label>
            <input v-model="newOrder.title" type="text" required class="input" />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ t('app.description') }}</label>
            <textarea v-model="newOrder.description" rows="3" class="input" />
          </div>

          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ t('orders.location') }}</label>
              <input v-model="newOrder.location" type="text" class="input" />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ t('users.employees') }}</label>
              <input v-model.number="newOrder.required_staff" type="number" min="1" class="input" />
            </div>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ t('users.address') }}</label>
            <input v-model="newOrder.address" type="text" class="input" />
          </div>

          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ t('orders.client') }}</label>
              <input v-model="newOrder.client_name" type="text" class="input" />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ t('customers.contact') }}</label>
              <input v-model="newOrder.client_contact" type="text" class="input" />
            </div>
          </div>

          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ t('orders.startDate') }}</label>
              <input v-model="newOrder.start_time" type="datetime-local" class="input" />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ t('orders.endDate') }}</label>
              <input v-model="newOrder.end_time" type="datetime-local" class="input" />
            </div>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ t('app.notes') }}</label>
            <textarea v-model="newOrder.special_instructions" rows="2" class="input" />
          </div>

          <div class="flex justify-end gap-3 pt-4">
            <button type="button" class="btn btn-secondary" @click="showCreateModal = false">
              {{ t('app.cancel') }}
            </button>
            <button type="submit" class="btn btn-primary">
              {{ t('app.add') }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>
