<script setup>
import { ref, computed, watch } from 'vue'
import { PRICING_PRESETS } from 'src/composables/useJobOffers'

const props = defineProps({
  modelValue: Boolean,
  technicians: { type: Array, default: () => [] },
  allTags: { type: Array, default: () => [] },
  prefill: { type: Object, default: null },  // Pre-fill from existing job
})
const emit = defineEmits(['update:modelValue', 'create'])

const form = ref(resetForm())
const notifySms = ref(true)

function resetForm () {
  return {
    subject: '',
    address: '',
    customer: '',
    scheduledDate: '',
    startTime: '',
    duration: 1,
    priority: 'medium',
    pricingPreset: 'standard',
    offerMode: 'broadcast',
    targetTechs: [],
    requiredTags: [],
    expiresAt: '',
    isCustomerRequest: false,
    salesOrder: '',
  }
}

watch(() => props.modelValue, v => {
  if (v) {
    form.value = resetForm()
    if (props.prefill) {
      form.value.subject = props.prefill.subject || ''
      form.value.address = props.prefill.address || ''
      form.value.customer = props.prefill.customer || ''
      form.value.scheduledDate = props.prefill.scheduledDate || ''
      form.value.startTime = props.prefill.startTime || ''
      form.value.duration = props.prefill.duration || 1
      form.value.priority = props.prefill.priority || 'medium'
      form.value.jobName = props.prefill.id || props.prefill.name || ''
    }
  }
})

const pricing = computed(() => PRICING_PRESETS[form.value.pricingPreset] || PRICING_PRESETS.standard)
const estimatedTotal = computed(() => pricing.value.displacement + Math.round(form.value.duration * pricing.value.hourlyRate))

const pricingOptions = Object.entries(PRICING_PRESETS).map(([k, v]) => ({
  value: k, label: v.label, description: v.description,
}))

// Priorité Dispatch Job — SOURCE UNIQUE (config/dispatch-priority) : « Moyenne » = ambre partout (fini le bleu divergent).
import { DISPATCH_PRIORITIES as priorityOptions } from 'src/config/dispatch-priority'

const modeOptions = [
  { value: 'broadcast', label: '📡 Diffusion', hint: 'Tous les techs disponibles' },
  { value: 'targeted', label: '🎯 Ciblé', hint: 'Techs spécifiques' },
  { value: 'pool', label: '📋 File d\'attente', hint: 'Premier arrivé, premier servi' },
]

function submit () {
  emit('create', { ...form.value }, notifySms.value)
  emit('update:modelValue', false)
}
</script>

<template>
<q-dialog :model-value="modelValue" @update:model-value="emit('update:modelValue', $event)" persistent>
  <q-card class="create-offer-card" dark>
    <q-card-section class="offer-modal-header">
      <div class="offer-modal-title">
        <span>📡</span> Créer une offre de travail
      </div>
      <q-btn flat round dense icon="close" @click="emit('update:modelValue', false)" />
    </q-card-section>

    <q-separator dark />

    <q-card-section class="offer-modal-body">
      <!-- Subject -->
      <q-input v-model="form.subject" label="Sujet / Description" dark filled dense class="offer-field" />

      <!-- Address + Customer -->
      <div class="offer-row">
        <q-input v-model="form.address" label="Adresse" dark filled dense class="offer-field" style="flex:2" />
        <q-input v-model="form.customer" label="Client" dark filled dense class="offer-field" style="flex:1" />
      </div>

      <!-- Date + Time + Duration -->
      <div class="offer-row">
        <q-input v-model="form.scheduledDate" label="Date" type="date" dark filled dense class="offer-field" />
        <q-input v-model="form.startTime" label="Heure" type="time" dark filled dense class="offer-field" />
        <q-input v-model.number="form.duration" label="Durée (h)" type="number" step="0.5" min="0.5" max="24" dark filled dense class="offer-field" />
      </div>

      <!-- Priority -->
      <div class="offer-row">
        <div class="offer-field-group">
          <label class="offer-label">Priorité</label>
          <div class="offer-priority-row">
            <button v-for="p in priorityOptions" :key="p.value"
                    class="offer-priority-btn" :class="{ active: form.priority === p.value }"
                    :style="form.priority === p.value ? 'background:'+p.color+';color:#fff' : ''"
                    @click="form.priority = p.value">
              {{ p.label }}
            </button>
          </div>
        </div>
      </div>

      <!-- Offer mode -->
      <div class="offer-field-group">
        <label class="offer-label">Mode de diffusion</label>
        <div class="offer-mode-row">
          <button v-for="m in modeOptions" :key="m.value"
                  class="offer-mode-btn" :class="{ active: form.offerMode === m.value }"
                  @click="form.offerMode = m.value">
            <span class="offer-mode-icon">{{ m.label.slice(0,2) }}</span>
            <span>{{ m.label.slice(2) }}</span>
            <small>{{ m.hint }}</small>
          </button>
        </div>
      </div>

      <!-- Targeted techs (if targeted mode) -->
      <div v-if="form.offerMode === 'targeted'" class="offer-field-group">
        <label class="offer-label">Techniciens ciblés</label>
        <q-select v-model="form.targetTechs" :options="technicians.map(t => ({ label: t.fullName, value: t.id }))"
                  multiple emit-value map-options use-chips dark filled dense
                  option-value="value" option-label="label"
                  class="offer-field" />
      </div>

      <!-- Required tags -->
      <q-select v-model="form.requiredTags" :options="allTags.map(t => t.label || t.name || t)"
                multiple use-chips dark filled dense label="Tags / Compétences requises" class="offer-field" />

      <q-separator dark class="q-my-sm" />

      <!-- Pricing -->
      <div class="offer-field-group">
        <label class="offer-label">💰 Tarification</label>
        <div class="offer-pricing-row">
          <button v-for="p in pricingOptions" :key="p.value"
                  class="offer-pricing-btn" :class="{ active: form.pricingPreset === p.value }"
                  @click="form.pricingPreset = p.value">
            <span class="offer-pricing-name">{{ p.label }}</span>
            <small>{{ p.description }}</small>
          </button>
        </div>
      </div>

      <!-- Cost estimate -->
      <div v-if="pricing.displacement > 0 || pricing.hourlyRate > 0" class="offer-cost-estimate">
        <div class="offer-cost-line">
          <span>Déplacement</span>
          <span>{{ pricing.displacement }}$</span>
        </div>
        <div class="offer-cost-line">
          <span>Main-d'œuvre ({{ form.duration }}h × {{ pricing.hourlyRate }}$/h)</span>
          <span>{{ Math.round(form.duration * pricing.hourlyRate) }}$</span>
        </div>
        <div class="offer-cost-line offer-cost-total">
          <span>Total estimé</span>
          <span>{{ estimatedTotal }}$ {{ pricing.currency }}</span>
        </div>
      </div>

      <!-- Customer request toggle -->
      <q-toggle v-model="form.isCustomerRequest" label="Demande client (checkout portail)" dark dense class="q-mt-xs" />

      <!-- Sales order link -->
      <q-input v-if="form.isCustomerRequest" v-model="form.salesOrder" label="Bon de commande (Sales Order)" dark filled dense class="offer-field" />

      <!-- Expiry -->
      <q-input v-model="form.expiresAt" label="Expiration (optionnel)" type="datetime-local" dark filled dense class="offer-field" />

      <!-- SMS notification toggle -->
      <q-toggle v-model="notifySms" label="Notifier par SMS" dark dense class="q-mt-xs" />
    </q-card-section>

    <q-separator dark />

    <q-card-actions align="right" class="offer-modal-footer">
      <q-btn flat label="Annuler" dark @click="emit('update:modelValue', false)" />
      <q-btn unelevated color="primary" label="📡 Diffuser l'offre" :disable="!form.subject" @click="submit" />
    </q-card-actions>
  </q-card>
</q-dialog>
</template>

<style lang="scss">
.create-offer-card {
  width: 560px; max-width: 95vw; background: #12151e !important;
}
.offer-modal-header {
  display: flex; align-items: center; justify-content: space-between;
  .offer-modal-title { font-size: 1rem; font-weight: 600; display: flex; align-items: center; gap: 6px; }
}
.offer-modal-body { display: flex; flex-direction: column; gap: 8px; }
.offer-row { display: flex; gap: 8px; }
.offer-field { flex: 1; }
.offer-field-group { margin: 4px 0; }
.offer-label { font-size: 0.72rem; color: #9ca3af; font-weight: 500; margin-bottom: 4px; display: block; }
.offer-priority-row, .offer-mode-row, .offer-pricing-row {
  display: flex; gap: 6px;
}
.offer-priority-btn, .offer-mode-btn, .offer-pricing-btn {
  border: 1px solid rgba(255,255,255,0.08); border-radius: 6px;
  background: rgba(255,255,255,0.04); color: #c8cad6;
  cursor: pointer; transition: all 0.15s; text-align: left;
  &:hover { background: rgba(255,255,255,0.08); }
  &.active { border-color: #3b82f6; background: rgba(59,130,246,0.12); }
}
.offer-priority-btn { padding: 5px 14px; font-size: 0.78rem; font-weight: 500; }
.offer-mode-btn {
  padding: 8px 12px; flex: 1; display: flex; flex-direction: column; gap: 2px;
  font-size: 0.78rem;
  small { font-size: 0.65rem; color: #6b7280; }
}
.offer-pricing-btn {
  padding: 8px 12px; flex: 1; display: flex; flex-direction: column; gap: 2px;
  font-size: 0.78rem;
  .offer-pricing-name { font-weight: 600; }
  small { font-size: 0.65rem; color: #6b7280; }
}
.offer-cost-estimate {
  background: rgba(250,204,21,0.06); border: 1px solid rgba(250,204,21,0.12);
  border-radius: 6px; padding: 8px 12px;
}
.offer-cost-line {
  display: flex; justify-content: space-between; font-size: 0.78rem; color: #d4d4d8;
  padding: 2px 0;
  &.offer-cost-total { font-weight: 700; color: #fbbf24; border-top: 1px solid rgba(250,204,21,0.15); margin-top: 4px; padding-top: 6px; }
}
.offer-modal-footer { padding: 8px 16px; }
</style>
