<template>
  <div class="page-container">
    <Toast />

    <div class="card">
      <!-- Header -->
      <div class="card-header" style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--space-sm);">
        <h2 style="font-size: var(--text-xl); font-weight: var(--font-semibold); margin: 0;">
          Comenzi Service
        </h2>
        <router-link to="/service-auto/comanda-noua">
          <Button label="Comandă Nouă" icon="pi pi-plus" size="small" />
        </router-link>
      </div>

      <!-- Filters row -->
      <div class="card-body" style="padding-bottom: 0;">
        <div class="filters-row">
          <div class="filter-group">
            <label class="filter-label">Status</label>
            <Dropdown
              v-model="filters.validat"
              :options="statusOptions"
              option-label="label"
              option-value="value"
              placeholder="Toate"
              class="w-full"
              @change="resetAndLoad"
            />
          </div>

          <div class="filter-group">
            <label class="filter-label">De la</label>
            <Calendar
              v-model="filters.data_de_la"
              date-format="dd.mm.yy"
              placeholder="—"
              class="w-full"
              @date-select="resetAndLoad"
            />
          </div>

          <div class="filter-group">
            <label class="filter-label">Până la</label>
            <Calendar
              v-model="filters.data_pana_la"
              date-format="dd.mm.yy"
              placeholder="—"
              class="w-full"
              @date-select="resetAndLoad"
            />
          </div>

          <div class="filter-group filter-actions">
            <Button
              label="Resetează"
              icon="pi pi-filter-slash"
              severity="secondary"
              outlined
              size="small"
              @click="clearFilters"
            />
          </div>
        </div>
      </div>

      <!-- Table -->
      <div class="card-body">
        <DataTable
          :value="comenzi"
          :lazy="true"
          :paginator="true"
          :rows="perPage"
          :total-records="total"
          :loading="loading"
          class="p-datatable-sm"
          striped-rows
          @page="onPage"
        >
          <template #empty>
            <div style="text-align: center; padding: var(--space-xl); color: var(--text-color-secondary);">
              Nicio comandă găsită
            </div>
          </template>

          <Column field="nrord" header="Nr. Ord." style="min-width: 100px;" />

          <Column field="datai" header="Data" style="min-width: 100px;" />

          <Column header="Status" style="min-width: 110px;">
            <template #body="{ data }">
              <span :class="['status-badge', statusClass(data)]">
                {{ statusLabel(data) }}
              </span>
            </template>
          </Column>

          <Column header="Tip" style="min-width: 130px;">
            <template #body="{ data }">
              {{ data.tip_denumire }}
            </template>
          </Column>

          <Column header="Client / Vehicul" style="min-width: 240px;">
            <template #body="{ data }">
              <span style="color: var(--text-color);">{{ data.vehicul || '—' }}</span>
            </template>
          </Column>
        </DataTable>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useToast } from 'primevue/usetoast'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Dropdown from 'primevue/dropdown'
import Calendar from 'primevue/calendar'
import Button from 'primevue/button'
import Toast from 'primevue/toast'
import serviceAutoApi from '../services/api.js'

const toast = useToast()

// ─── State ────────────────────────────────────────────────────────────────────

const comenzi = ref([])
const total = ref(0)
const loading = ref(false)
const page = ref(1)
const perPage = ref(20)

const filters = ref({
  validat: null,
  data_de_la: null,
  data_pana_la: null,
})

const statusOptions = [
  { label: 'Toate', value: null },
  { label: 'Deschisă', value: 0 },
  { label: 'Validată', value: 1 },
]

// ─── Helpers ──────────────────────────────────────────────────────────────────

const fmtDate = (d) => d ? d.toISOString().slice(0, 10) : undefined

function statusLabel(row) {
  if (row.inchis_fortat) return 'Arhivată'
  return row.validat ? 'Validată' : 'Deschisă'
}

function statusClass(row) {
  if (row.inchis_fortat) return 'status-archived'
  return row.validat ? 'status-validated' : 'status-open'
}

// ─── Data loading ─────────────────────────────────────────────────────────────

async function loadComenzi() {
  loading.value = true
  try {
    const params = {
      page: page.value,
      per_page: perPage.value,
    }
    if (filters.value.validat !== null) params.validat = filters.value.validat
    if (filters.value.data_de_la)       params.data_de_la = fmtDate(filters.value.data_de_la)
    if (filters.value.data_pana_la)     params.data_pana_la = fmtDate(filters.value.data_pana_la)

    const { data } = await serviceAutoApi.getComenzi(params)
    comenzi.value = data.comenzi
    total.value = data.total
  } catch (err) {
    const status = err.response?.status
    if (status === 503) {
      toast.add({ severity: 'error', summary: 'Eroare conexiune', detail: 'Serviciul bazei de date nu este disponibil', life: 5000 })
    } else {
      toast.add({ severity: 'error', summary: 'Eroare', detail: 'Nu s-au putut încărca comenzile', life: 4000 })
    }
  } finally {
    loading.value = false
  }
}

function resetAndLoad() {
  page.value = 1
  loadComenzi()
}

function clearFilters() {
  filters.value = { validat: null, data_de_la: null, data_pana_la: null }
  page.value = 1
  loadComenzi()
}

function onPage(event) {
  page.value = event.page + 1  // PrimeVue is 0-indexed
  perPage.value = event.rows
  loadComenzi()
}

onMounted(loadComenzi)
</script>

<style scoped>
.filters-row {
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-md);
  align-items: flex-end;
  margin-bottom: var(--space-md);
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: var(--space-xs);
  min-width: 150px;
}

.filter-group.filter-actions {
  justify-content: flex-end;
  padding-bottom: 2px;
}

.filter-label {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--text-color-secondary);
}

/* Status badges */
.status-badge {
  display: inline-block;
  padding: 2px var(--space-sm);
  border-radius: var(--radius-sm);
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
}

.status-open {
  background: var(--green-50);
  color: var(--green-600);
}

.status-validated {
  background: var(--blue-50);
  color: var(--blue-600);
}

.status-archived {
  background: var(--surface-hover);
  color: var(--text-color-secondary);
}

[data-theme="dark"] .status-open {
  background: var(--green-900);
  color: var(--green-200);
}

[data-theme="dark"] .status-validated {
  background: var(--blue-900);
  color: var(--blue-200);
}

[data-theme="dark"] .status-archived {
  background: var(--surface-100);
  color: var(--text-color-secondary);
}
</style>
