<template>
  <div v-if="order">
    <div class="flex items-center justify-between mb-6">
      <div>
        <router-link to="/orders" class="text-sm text-gray-500 hover:text-gray-700">Comenzi</router-link>
        <h1 class="text-2xl font-bold text-gray-900">{{ order.nr_comanda }}</h1>
      </div>
      <div class="flex gap-2">
        <button
          v-if="order.status === 'DRAFT'"
          @click="handleValidate"
          class="px-4 py-2 bg-green-600 text-white text-sm rounded-md hover:bg-green-700"
        >
          Valideaza
        </button>
        <span
          class="inline-flex items-center px-3 py-1.5 rounded-full text-sm font-medium"
          :class="statusClass(order.status)"
        >
          {{ order.status }}
        </span>
      </div>
    </div>

    <!-- Order info -->
    <div class="bg-white rounded-lg shadow p-4 mb-6">
      <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
        <div>
          <p class="text-gray-500">Nr. auto</p>
          <p class="font-medium">{{ order.nr_auto || '-' }}</p>
        </div>
        <div>
          <p class="text-gray-500">Client</p>
          <p class="font-medium">{{ order.client_nume || '-' }}</p>
        </div>
        <div>
          <p class="text-gray-500">Marca / Model</p>
          <p class="font-medium">{{ order.marca_denumire || '-' }} {{ order.model_denumire || '' }}</p>
        </div>
        <div>
          <p class="text-gray-500">KM intrare</p>
          <p class="font-medium">{{ order.km_intrare || '-' }}</p>
        </div>
      </div>
      <div v-if="order.observatii" class="mt-3 text-sm">
        <p class="text-gray-500">Observatii</p>
        <p>{{ order.observatii }}</p>
      </div>
    </div>

    <!-- Order lines -->
    <div class="bg-white rounded-lg shadow mb-6">
      <div class="px-4 py-3 border-b border-gray-200">
        <h2 class="text-lg font-semibold text-gray-900">Linii comanda</h2>
      </div>

      <div v-if="lines.length === 0" class="p-4 text-sm text-gray-500">
        Nicio linie adaugata.
      </div>

      <table v-else class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Tip</th>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Descriere</th>
            <th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase hidden md:table-cell">Cant/Ore</th>
            <th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase hidden md:table-cell">Pret</th>
            <th class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase">Total</th>
            <th v-if="order.status === 'DRAFT'" class="px-4 py-2 w-10"></th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-100">
          <tr v-for="l in lines" :key="l.id">
            <td class="px-4 py-2 text-xs">
              <span
                class="px-1.5 py-0.5 rounded text-xs font-medium"
                :class="l.tip === 'manopera' ? 'bg-purple-100 text-purple-700' : 'bg-orange-100 text-orange-700'"
              >
                {{ l.tip === 'manopera' ? 'MAN' : 'MAT' }}
              </span>
            </td>
            <td class="px-4 py-2 text-sm text-gray-900">{{ l.descriere }}</td>
            <td class="px-4 py-2 text-sm text-right text-gray-600 hidden md:table-cell">
              {{ l.tip === 'manopera' ? `${l.ore}h` : `${l.cantitate} ${l.um}` }}
            </td>
            <td class="px-4 py-2 text-sm text-right text-gray-600 hidden md:table-cell">
              {{ l.tip === 'manopera' ? `${(l.pret_ora || 0).toFixed(2)}/h` : `${(l.pret_unitar || 0).toFixed(2)}/${l.um}` }}
            </td>
            <td class="px-4 py-2 text-sm text-right font-medium text-gray-900">
              {{ (l.total || 0).toFixed(2) }}
            </td>
            <td v-if="order.status === 'DRAFT'" class="px-4 py-2">
              <button @click="handleRemoveLine(l.id)" class="text-red-500 hover:text-red-700 text-xs">X</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Add line form (only for draft) -->
    <OrderLineForm v-if="order.status === 'DRAFT'" @add="handleAddLine" class="mb-6" />

    <!-- Totals -->
    <div class="bg-white rounded-lg shadow p-4">
      <div class="flex justify-end">
        <div class="w-64 space-y-1 text-sm">
          <div class="flex justify-between">
            <span class="text-gray-500">Manopera:</span>
            <span class="font-medium">{{ (order.total_manopera || 0).toFixed(2) }} RON</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-500">Materiale:</span>
            <span class="font-medium">{{ (order.total_materiale || 0).toFixed(2) }} RON</span>
          </div>
          <div class="flex justify-between border-t pt-1 text-base">
            <span class="font-semibold">Total general:</span>
            <span class="font-bold">{{ (order.total_general || 0).toFixed(2) }} RON</span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div v-else class="text-center py-12 text-gray-500">
    Se incarca...
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useOrdersStore } from '../../stores/orders.js'
import { onTableChange } from '../../db/database.js'
import OrderLineForm from '../../components/orders/OrderLineForm.vue'

const route = useRoute()
const ordersStore = useOrdersStore()

const order = ref(null)
const lines = ref([])

async function loadOrder() {
  order.value = await ordersStore.getById(route.params.id)
  lines.value = await ordersStore.getLines(route.params.id)
}

onMounted(() => {
  loadOrder()
  onTableChange('orders', loadOrder)
  onTableChange('order_lines', async () => {
    lines.value = await ordersStore.getLines(route.params.id)
    order.value = await ordersStore.getById(route.params.id)
  })
})

async function handleAddLine(lineData) {
  await ordersStore.addLine(route.params.id, lineData)
}

async function handleRemoveLine(lineId) {
  await ordersStore.removeLine(lineId, route.params.id)
}

async function handleValidate() {
  await ordersStore.validateOrder(route.params.id)
}

function statusClass(status) {
  switch (status) {
    case 'DRAFT': return 'bg-yellow-100 text-yellow-800'
    case 'VALIDAT': return 'bg-green-100 text-green-800'
    case 'FACTURAT': return 'bg-blue-100 text-blue-800'
    default: return 'bg-gray-100 text-gray-800'
  }
}
</script>
