<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()

const stats = ref({
  openOrders: 0,
  myOrders: 0,
  pendingTimesheets: 0,
  availableToday: false
})

const recentOrders = ref<any[]>([])
const loading = ref(true)

const greeting = computed(() => {
  const hour = new Date().getHours()
  if (hour < 12) return t('dashboard.welcome')
  if (hour < 18) return t('dashboard.welcome')
  return t('dashboard.welcome')
})

onMounted(async () => {
  try {
    const ordersRes = await api.get<{ orders: any[] }>('/orders')
    recentOrders.value = ordersRes.data.orders.slice(0, 5)
    
    stats.value.openOrders = ordersRes.data.orders.filter(o => 
      ['published', 'in_progress'].includes(o.status)
    ).length
    
    if (authStore.isMitarbeiter) {
      stats.value.myOrders = ordersRes.data.orders.length
    }

    if (authStore.canManageUsers) {
      const tsRes = await api.get<{ timesheets: any[] }>('/timesheets?status=pending')
      stats.value.pendingTimesheets = tsRes.data.timesheets.length
    }

    const today = new Date().toISOString().split('T')[0]
    const availRes = await api.get<{ availability: any[] }>(`/availability?from=${today}&to=${today}`)
    stats.value.availableToday = availRes.data.availability.some(a => a.available && a.user_id === authStore.user?.id)
  } catch (e) {
    console.error('Dashboard load error:', e)
  } finally {
    loading.value = false
  }
})

function getStatusBadge(status: string) {
  const badges: Record<string, string> = {
    draft: 'badge-secondary',
    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
}
</script>

<template>
  <div class="space-y-6">
    <!-- Welcome -->
    <div class="card bg-gradient-to-r from-primary-500 to-primary-700 text-white">
      <h1 class="text-2xl font-bold">
        {{ greeting }}, {{ authStore.user?.first_name }}! 👋
      </h1>
      <p class="mt-1 text-primary-100">
        {{ t('dashboard.overview') }}
      </p>
    </div>

    <!-- Stats Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
      <div class="card">
        <div class="flex items-center gap-4">
          <div class="w-12 h-12 rounded-lg bg-blue-100 dark:bg-blue-900 flex items-center justify-center">
            <span class="text-2xl">📋</span>
          </div>
          <div>
            <p class="text-sm text-gray-500 dark:text-gray-400">{{ t('dashboard.todayOrders') }}</p>
            <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ stats.openOrders }}</p>
          </div>
        </div>
      </div>

      <div v-if="authStore.isMitarbeiter" class="card">
        <div class="flex items-center gap-4">
          <div class="w-12 h-12 rounded-lg bg-green-100 dark:bg-green-900 flex items-center justify-center">
            <span class="text-2xl">✅</span>
          </div>
          <div>
            <p class="text-sm text-gray-500 dark:text-gray-400">{{ t('orders.title') }}</p>
            <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ stats.myOrders }}</p>
          </div>
        </div>
      </div>

      <div v-if="authStore.canManageUsers" class="card">
        <div class="flex items-center gap-4">
          <div class="w-12 h-12 rounded-lg bg-yellow-100 dark:bg-yellow-900 flex items-center justify-center">
            <span class="text-2xl">⏱️</span>
          </div>
          <div>
            <p class="text-sm text-gray-500 dark:text-gray-400">{{ t('dashboard.pendingTimesheets') }}</p>
            <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ stats.pendingTimesheets }}</p>
          </div>
        </div>
      </div>

      <div class="card">
        <div class="flex items-center gap-4">
          <div :class="[
            'w-12 h-12 rounded-lg flex items-center justify-center',
            stats.availableToday ? 'bg-green-100 dark:bg-green-900' : 'bg-gray-100 dark:bg-gray-700'
          ]">
            <span class="text-2xl">{{ stats.availableToday ? '✅' : '❓' }}</span>
          </div>
          <div>
            <p class="text-sm text-gray-500 dark:text-gray-400">{{ t('availability.available') }}</p>
            <p class="text-lg font-medium text-gray-900 dark:text-white">
              {{ stats.availableToday ? t('app.yes') : t('app.no') }}
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- Recent Orders -->
    <div class="card">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-lg font-semibold text-gray-900 dark:text-white">
          {{ t('dashboard.recentActivity') }}
        </h2>
        <router-link to="/orders" class="text-sm text-primary-600 hover:text-primary-700">
          {{ t('app.all') }} →
        </router-link>
      </div>

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

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

      <div v-else class="space-y-3">
        <router-link
          v-for="order in recentOrders"
          :key="order.id"
          :to="`/orders/${order.id}`"
          class="block p-4 rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
        >
          <div class="flex items-center justify-between">
            <div>
              <h3 class="font-medium text-gray-900 dark:text-white">
                #{{ order.number }} - {{ order.title }}
              </h3>
              <p v-if="order.location" class="text-sm text-gray-500 dark:text-gray-400">
                📍 {{ order.location }}
              </p>
            </div>
            <span :class="['badge', getStatusBadge(order.status)]">
              {{ getStatusLabel(order.status) }}
            </span>
          </div>
        </router-link>
      </div>
    </div>
  </div>
</template>
