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

    <div class="card" style="max-width: 560px; margin: var(--space-xl) auto;">
      <div class="card-header">
        <h2 style="font-size: var(--text-xl); font-weight: var(--font-semibold); margin: 0;">
          Comandă Nouă
        </h2>
      </div>

      <div class="card-body">
        <form class="form-stack" @submit.prevent="submitComanda">

          <!-- Firmă -->
          <div class="field">
            <label style="font-weight: var(--font-medium); font-size: var(--text-sm); color: var(--text-color-secondary);">
              Firmă *
            </label>
            <Dropdown
              v-model="form.id_firma"
              :options="firme"
              option-label="firma"
              option-value="id_firma"
              placeholder="Selectează firma"
              :disabled="isSubmitting || loadingFirme"
              :loading="loadingFirme"
              class="w-full"
            />
          </div>

          <!-- Tip comandă -->
          <div class="field">
            <label style="font-weight: var(--font-medium); font-size: var(--text-sm); color: var(--text-color-secondary);">
              Tip comandă *
            </label>
            <Dropdown
              v-model="form.tip_id"
              :options="tipuriComanda"
              option-label="denumire"
              option-value="id_tip"
              placeholder="Selectează tipul comenzii"
              :disabled="isSubmitting || loadingTipuri"
              :loading="loadingTipuri"
              class="w-full"
            />
          </div>

          <!-- Client / Mașină -->
          <div class="field">
            <label style="font-weight: var(--font-medium); font-size: var(--text-sm); color: var(--text-color-secondary);">
              Client / Mașină *
            </label>
            <Dropdown
              ref="clientDropdownRef"
              v-model="form.id_masiniclient"
              :options="masini"
              option-label="label"
              option-value="id_masiniclient"
              placeholder="Selectează client / mașină"
              :disabled="isSubmitting || loadingMasini"
              :loading="loadingMasini"
              filter
              class="w-full"
            />
          </div>

          <!-- Operații solicitate -->
          <div class="field">
            <label style="font-weight: var(--font-medium); font-size: var(--text-sm); color: var(--text-color-secondary);">
              Operații solicitate *
            </label>
            <Textarea
              v-model="form.solicitari"
              rows="4"
              placeholder="Descrieți operațiile solicitate de client..."
              :disabled="isSubmitting"
              style="width: 100%; resize: vertical;"
            />
          </div>

          <!-- Submit -->
          <div style="display: flex; justify-content: flex-end; padding-top: var(--space-sm);">
            <Button
              type="submit"
              label="Creează Comanda"
              icon="pi pi-check"
              :disabled="!isFormValid || isSubmitting"
              :loading="isSubmitting"
            />
          </div>

        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useToast } from 'primevue/usetoast'
import Dropdown from 'primevue/dropdown'
import Textarea from 'primevue/textarea'
import Button from 'primevue/button'
import Toast from 'primevue/toast'
import serviceAutoApi from '../services/api.js'

const toast = useToast()
const clientDropdownRef = ref(null)
const isSubmitting = ref(false)

// ─── Lookup data (from Oracle via API) ────────────────────────────────────────

const firme = ref([])
const tipuriComanda = ref([])
const masini = ref([])
const loadingFirme = ref(false)
const loadingTipuri = ref(false)
const loadingMasini = ref(false)

async function loadLookups() {
  loadingFirme.value = true
  loadingTipuri.value = true
  loadingMasini.value = true

  const [firmeRes, tipuriRes, masiniRes] = await Promise.allSettled([
    serviceAutoApi.getFirme(),
    serviceAutoApi.getTipDeviz(),
    serviceAutoApi.getMasini(),
  ])

  if (firmeRes.status === 'fulfilled') {
    firme.value = firmeRes.value.data
    // Default: first company
    if (firme.value.length > 0 && form.value.id_firma === null) {
      form.value.id_firma = firme.value[0].id_firma
    }
  } else {
    toast.add({ severity: 'warn', summary: 'Firme', detail: 'Nu s-au putut încărca firmele', life: 4000 })
  }

  if (tipuriRes.status === 'fulfilled') {
    tipuriComanda.value = tipuriRes.value.data
  } else {
    toast.add({ severity: 'warn', summary: 'Tipuri', detail: 'Nu s-au putut încărca tipurile de deviz', life: 4000 })
  }

  if (masiniRes.status === 'fulfilled') {
    masini.value = masiniRes.value.data
  } else {
    toast.add({ severity: 'warn', summary: 'Mașini', detail: 'Nu s-au putut încărca mașinile', life: 4000 })
  }

  loadingFirme.value = false
  loadingTipuri.value = false
  loadingMasini.value = false
}

onMounted(loadLookups)

// ─── Form state ────────────────────────────────────────────────────────────

const emptyForm = () => ({
  id_firma: null,
  tip_id: null,
  id_masiniclient: null,
  solicitari: '',
})

const form = ref(emptyForm())

const isFormValid = computed(() =>
  form.value.id_firma !== null &&
  form.value.tip_id !== null &&
  form.value.id_masiniclient !== null &&
  form.value.solicitari.trim().length > 0
)

// ─── Submit ────────────────────────────────────────────────────────────────

async function submitComanda() {
  if (!isFormValid.value) return

  isSubmitting.value = true
  try {
    const { data } = await serviceAutoApi.creeazaComanda({
      tip_id: form.value.tip_id,
      id_masiniclient: form.value.id_masiniclient,
      solicitari: form.value.solicitari.trim(),
      id_firma: form.value.id_firma,
    })

    toast.add({
      severity: 'success',
      summary: 'Comandă creată',
      detail: `Nr ${data.nrord}`,
      life: 3000,
    })

    // Reset — preserve firma + tip (user creează mai multe consecutive)
    const savedFirma = form.value.id_firma
    const savedTip = form.value.tip_id
    form.value = emptyForm()
    form.value.id_firma = savedFirma
    form.value.tip_id = savedTip

    await nextTick()
    clientDropdownRef.value?.$el?.querySelector('input, [role="combobox"]')?.focus()

  } catch (err) {
    const status = err.response?.status
    if (status === 422) {
      toast.add({ severity: 'error', summary: 'Validare', detail: err.response?.data?.detail || 'Date invalide', life: 5000 })
    } else if (status === 503) {
      toast.add({ severity: 'error', summary: 'Eroare conexiune', detail: 'Serviciul nu este disponibil. Verificați conexiunea Oracle.', life: 5000 })
    } else {
      toast.add({ severity: 'error', summary: 'Eroare internă', detail: 'A apărut o eroare pe server. Reîncercați sau contactați suportul.', life: 5000 })
    }
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.form-stack {
  display: grid;
  gap: var(--space-md);
}
</style>
