<script setup>
import { ref, inject, computed, watch } from 'vue'
import TagEditor from 'src/components/shared/TagEditor.vue'
import { TECH_COLORS } from 'src/config/erpnext'
import { rankTechs, refineWithDrivingTimes } from 'src/composables/useBestTech'
import { localDateStr } from 'src/composables/useHelpers'

const props = defineProps({ modelValue: Object })
const emit = defineEmits(['update:modelValue', 'confirm', 'cancel'])

const store = inject('store')
const MAPBOX_TOKEN = inject('MAPBOX_TOKEN')
const getTagColor = inject('getTagColor')
const onCreateTag = inject('onCreateTag')
const onUpdateTag = inject('onUpdateTag')
const onRenameTag = inject('onRenameTag')
const onDeleteTag = inject('onDeleteTag')
const searchAddr = inject('searchAddr')
const addrResults = inject('addrResults')
const selectAddr = inject('selectAddr')

const showRanking = ref(false)
const ranking = ref([])
const rankingLoading = ref(false)

const hasJobCoords = computed(() => props.modelValue?.latitude && props.modelValue?.longitude)

async function findBestTech () {
  if (!props.modelValue) return
  rankingLoading.value = true
  showRanking.value = true

  const jobCoords = hasJobCoords.value ? [props.modelValue.longitude, props.modelValue.latitude] : null
  const dateStr = props.modelValue.date || localDateStr(new Date())

  let results = rankTechs({
    technicians: store.technicians,
    jobCoords,
    jobDuration: props.modelValue.duration_h || 1,
    jobTags: props.modelValue.tags || [],
    dateStr,
  })

  // Refine top 3 with real driving times
  if (jobCoords) {
    results = await refineWithDrivingTimes(results, jobCoords, 3)
  }

  ranking.value = results
  rankingLoading.value = false
}

function pickTech (techId) {
  if (!props.modelValue) return
  props.modelValue.techId = techId
  showRanking.value = false
}

// Reset ranking when modal closes
watch(() => props.modelValue, (v) => { if (!v) { showRanking.value = false; ranking.value = [] } })

function close () { emit('update:modelValue', null); emit('cancel') }
</script>

<template>
<div v-if="modelValue" class="sb-overlay" @click.self="close">
  <div class="sb-modal sb-modal-wo">
    <div class="sb-modal-hdr">
      <span>+ Nouveau work order</span>
      <button class="sb-rp-close" @click="close">✕</button>
    </div>
    <div class="sb-modal-body sb-wo-body">
      <div class="sb-wo-form">
        <div class="sb-form-row">
          <label class="sb-form-lbl">Titre *</label>
          <input class="sb-form-input" v-model="modelValue.subject" placeholder="Ex: Remplacement modem" autofocus />
        </div>
        <div class="sb-form-row">
          <label class="sb-form-lbl">Adresse</label>
          <div class="sb-addr-wrap">
            <input class="sb-form-input" v-model="modelValue.address" placeholder="123 rue Exemple, Montréal"
                   @input="searchAddr(modelValue.address)" @blur="setTimeout(()=>addrResults.length=0,200)" autocomplete="off" />
            <div v-if="addrResults.length" class="sb-addr-dropdown">
              <div v-for="a in addrResults" :key="a.address_full" class="sb-addr-item"
                   @mousedown.prevent="selectAddr(a, modelValue)">
                <strong>{{ a.address_full }}</strong>
                <span v-if="a.code_postal" class="sb-addr-cp">{{ a.code_postal }}</span>
                <span v-if="a.ville" class="sb-addr-city">{{ a.ville }}</span>
              </div>
            </div>
          </div>
          <div v-if="modelValue.latitude" class="sb-addr-confirmed">
            ✓ {{ modelValue.ville || '' }} {{ modelValue.code_postal || '' }}
          </div>
        </div>
        <div class="sb-form-row">
          <label class="sb-form-lbl">Note</label>
          <textarea class="sb-form-input" v-model="modelValue.note" rows="2" placeholder="Ex: chien dangereux, sonner 2x…" style="resize:vertical"></textarea>
        </div>
        <div class="sb-form-row">
          <label class="sb-form-lbl">Durée (h)</label>
          <input type="number" class="sb-form-input" v-model.number="modelValue.duration_h" min="0.5" max="12" step="0.5" />
        </div>
        <div class="sb-form-row">
          <label class="sb-form-lbl">Priorité</label>
          <select class="sb-form-sel" v-model="modelValue.priority">
            <option value="low">Basse</option>
            <option value="medium">Moyenne</option>
            <option value="high">Haute</option>
          </select>
        </div>
        <div class="sb-form-row">
          <label class="sb-form-lbl">Tags / Skills</label>
          <TagEditor v-model="modelValue.tags" :all-tags="store.allTags" :get-color="getTagColor"
                    @create="onCreateTag" @update-tag="onUpdateTag" @rename-tag="onRenameTag" @delete-tag="onDeleteTag" />
        </div>
        <div class="sb-form-row">
          <label class="sb-form-lbl">Technicien</label>
          <div class="sb-tech-pick">
            <select class="sb-form-sel" v-model="modelValue.techId" style="flex:1">
              <option value="">— Non assigné —</option>
              <option v-for="t in store.technicians" :key="t.id" :value="t.id">{{ t.fullName }}</option>
            </select>
            <button class="sb-best-tech-btn" @click="findBestTech" :disabled="rankingLoading" title="Trouver le meilleur technicien">
              {{ rankingLoading ? '⏳' : '⚡' }} Optimal
            </button>
          </div>
        </div>

        <!-- Best tech ranking results -->
        <div v-if="showRanking && ranking.length" class="sb-ranking">
          <div class="sb-ranking-hdr">
            <span>⚡ Classement optimal</span>
            <button class="sb-ranking-close" @click="showRanking=false">✕</button>
          </div>
          <div v-for="(r, idx) in ranking" :key="r.tech.id"
               class="sb-rank-row" :class="{ 'sb-rank-best': idx === 0, 'sb-rank-selected': modelValue.techId === r.tech.id }"
               @click="pickTech(r.tech.id)">
            <div class="sb-rank-pos">
              <span v-if="idx === 0" class="sb-rank-medal">🥇</span>
              <span v-else-if="idx === 1" class="sb-rank-medal">🥈</span>
              <span v-else-if="idx === 2" class="sb-rank-medal">🥉</span>
              <span v-else class="sb-rank-num">#{{ idx + 1 }}</span>
            </div>
            <div class="sb-rank-avatar" :style="'background:' + TECH_COLORS[r.tech.colorIdx]">
              {{ r.tech.fullName.split(' ').map(n => n[0]).join('').toUpperCase() }}
            </div>
            <div class="sb-rank-info">
              <div class="sb-rank-name">{{ r.tech.fullName }}</div>
              <div class="sb-rank-reasons">
                <span v-for="(reason, ri) in r.reasons" :key="ri" class="sb-rank-reason">{{ reason }}</span>
              </div>
            </div>
            <div class="sb-rank-action">
              <button class="sb-rank-pick" @click.stop="pickTech(r.tech.id)">Choisir</button>
            </div>
          </div>
        </div>

        <div class="sb-form-row" v-if="modelValue.techId">
          <label class="sb-form-lbl">Date planifiée</label>
          <input type="date" class="sb-form-input" v-model="modelValue.date" />
        </div>
      </div>
      <div v-if="modelValue.latitude" class="sb-wo-minimap">
        <img :src="'https://api.mapbox.com/styles/v1/mapbox/dark-v11/static/pin-s+6366f1('+modelValue.longitude+','+modelValue.latitude+')/'+modelValue.longitude+','+modelValue.latitude+',14,0/280x280@2x?access_token='+MAPBOX_TOKEN"
             alt="Carte" class="sb-minimap-img" />
      </div>
    </div>
    <div class="sb-modal-ftr">
      <button class="sbf-primary-btn" :disabled="!modelValue.subject?.trim()" @click="emit('confirm')">✓ Créer</button>
      <button class="sb-rp-btn" @click="close">Annuler</button>
    </div>
  </div>
</div>
</template>

<style scoped>
.sb-tech-pick { display: flex; gap: 6px; align-items: center; }
.sb-best-tech-btn {
  padding: 4px 10px; border: 1px solid #6366f1; border-radius: 6px;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: #fff; font-size: 12px; font-weight: 600; cursor: pointer;
  white-space: nowrap; transition: all .15s;
}
.sb-best-tech-btn:hover { filter: brightness(1.1); transform: translateY(-1px); }
.sb-best-tech-btn:disabled { opacity: .6; cursor: wait; }

.sb-ranking {
  margin: 8px 0 4px; border: 1px solid #334155; border-radius: 8px;
  background: #0f172a; overflow: hidden;
}
.sb-ranking-hdr {
  display: flex; justify-content: space-between; align-items: center;
  padding: 8px 12px; background: #1e293b; font-size: 13px; font-weight: 600; color: #e2e8f0;
}
.sb-ranking-close { background: none; border: none; color: #94a3b8; cursor: pointer; font-size: 14px; }

.sb-rank-row {
  display: flex; align-items: center; gap: 10px; padding: 8px 12px;
  cursor: pointer; transition: background .1s; border-bottom: 1px solid #1e293b;
}
.sb-rank-row:last-child { border-bottom: none; }
.sb-rank-row:hover { background: #1e293b; }
.sb-rank-best { background: rgba(99, 102, 241, .08); }
.sb-rank-selected { background: rgba(99, 102, 241, .15); outline: 1px solid #6366f1; }

.sb-rank-pos { width: 28px; text-align: center; flex-shrink: 0; }
.sb-rank-medal { font-size: 18px; }
.sb-rank-num { font-size: 12px; color: #64748b; font-weight: 600; }

.sb-rank-avatar {
  width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center;
  justify-content: center; font-size: 11px; font-weight: 700; color: #fff; flex-shrink: 0;
}

.sb-rank-info { flex: 1; min-width: 0; }
.sb-rank-name { font-size: 13px; font-weight: 600; color: #e2e8f0; }
.sb-rank-reasons { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 2px; }
.sb-rank-reason { font-size: 11px; color: #94a3b8; }

.sb-rank-action { flex-shrink: 0; }
.sb-rank-pick {
  padding: 3px 10px; border: 1px solid #475569; border-radius: 4px;
  background: #1e293b; color: #e2e8f0; font-size: 11px; cursor: pointer;
}
.sb-rank-pick:hover { background: #6366f1; border-color: #6366f1; }
</style>
