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

const { t } = useI18n()
const authStore = useAuthStore()
const timesheets = ref<any[]>([])
const loading = ref(true)
const showCreateModal = ref(false)
const newTimesheet = ref({ work_date: '', start_time: '', end_time: '', order_id: '' })
const orders = ref<any[]>([])

onMounted(async () => {
  await Promise.all([loadTimesheets(), loadOrders()])
})

async function loadTimesheets() {
  loading.value = true
  try {
    const res = await api.get<{ timesheets: any[] }>('/timesheets')
    timesheets.value = res.data.timesheets
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

async function loadOrders() {
  try {
    const res = await api.get<{ orders: any[] }>('/orders')
    orders.value = res.data.orders
  } catch (e) {
    console.error(e)
  }
}

async function createTimesheet() {
  try {
    await api.post('/timesheets', newTimesheet.value)
    showCreateModal.value = false
    newTimesheet.value = { work_date: '', start_time: '', end_time: '', order_id: '' }
    await loadTimesheets()
  } catch (e) {
    alert(e instanceof Error ? e.message : t('messages.error'))
  }
}

async function reviewTimesheet(id: string, status: 'approved' | 'rejected') {
  const reason = status === 'rejected' ? prompt(t('availability.reason') + ':') : null
  if (status === 'rejected' && !reason) return
  
  try {
    await api.post(`/timesheets/${id}/review`, { status, rejection_reason: reason })
    await loadTimesheets()
  } catch (e) {
    alert(e instanceof Error ? e.message : t('messages.error'))
  }
}

function getStatusBadge(status: string) {
  return { pending: 'badge-warning', approved: 'badge-success', rejected: 'badge-danger' }[status] || ''
}

function getStatusLabel(status: string) {
  return t(`timesheets.statuses.${status}`) || status
}
</script>

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

    <div class="card">
      <div v-if="loading" class="text-center py-8 text-gray-500">{{ t('app.loading') }}</div>
      <div v-else-if="timesheets.length === 0" class="text-center py-8 text-gray-500">{{ t('messages.noData') }}</div>
      
      <div v-else class="space-y-3">
        <div v-for="ts in timesheets" :key="ts.id" class="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
          <div>
            <p class="font-medium">{{ new Date(ts.work_date).toLocaleDateString() }}</p>
            <p class="text-sm text-gray-500">
              {{ ts.start_time }} - {{ ts.end_time }} 
              <span v-if="ts.hours_worked">({{ ts.hours_worked }}h)</span>
            </p>
            <p v-if="ts.order_title" class="text-sm text-gray-500">📋 {{ ts.order_title }}</p>
            <p v-if="authStore.canManageUsers" class="text-sm text-gray-500">👤 {{ ts.user_name }}</p>
          </div>
          <div class="flex items-center gap-2">
            <span :class="['badge', getStatusBadge(ts.status)]">{{ getStatusLabel(ts.status) }}</span>
            <template v-if="authStore.canManageUsers && ts.status === 'pending'">
              <button class="btn btn-success text-sm" @click="reviewTimesheet(ts.id, 'approved')">✓</button>
              <button class="btn btn-danger text-sm" @click="reviewTimesheet(ts.id, 'rejected')">✗</button>
            </template>
          </div>
        </div>
      </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-md m-4">
        <h2 class="text-xl font-semibold mb-6">{{ t('timesheets.new') }}</h2>
        <form @submit.prevent="createTimesheet" class="space-y-4">
          <div>
            <label class="block text-sm font-medium mb-1">{{ t('app.date') }} *</label>
            <input v-model="newTimesheet.work_date" type="date" required class="input" />
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium mb-1">{{ t('app.from') }}</label>
              <input v-model="newTimesheet.start_time" type="time" class="input" />
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">{{ t('app.to') }}</label>
              <input v-model="newTimesheet.end_time" type="time" class="input" />
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium mb-1">{{ t('orders.title') }}</label>
            <select v-model="newTimesheet.order_id" class="input">
              <option value="">-- {{ t('app.none') }} --</option>
              <option v-for="o in orders" :key="o.id" :value="o.id">#{{ o.number }} - {{ o.title }}</option>
            </select>
          </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.submit') }}</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>
