<script setup lang="ts">
definePageMeta({ middleware: 'auth' })
const { t } = useI18n()
const { api } = useApi()
const toast = useToast()
const route = useRoute()
const routineId = Number(route.params.id)

interface ExerciseLite { id: number, name: string, image_url: string | null, target?: string | null }
interface Item {
  key: number
  exercise_id: number
  exercise: ExerciseLite
  sets: number
  target_reps: string
  rest_seconds: number | null
  tempo: string | null
  target_weight: number | null
  notes: string | null
}
interface RoutineData {
  id: number
  name: string
  description: string | null
  is_public: boolean
  exercises: Array<{
    exercise_id: number
    sets: number | null
    target_reps: string | null
    rest_seconds: number | null
    tempo: string | null
    target_weight: number | null
    notes: string | null
    exercise: ExerciseLite
  }>
}

let keySeq = 1
const name = ref('')
const description = ref('')
const isPublic = ref(false)
const items = ref<Item[]>([])
const dirty = ref(false)
const saving = ref(false)

const { data } = await useAsyncData(
  `routine-${routineId}`,
  () => api<{ data: RoutineData }>(`/api/routines/${routineId}`).then(r => r.data)
)

watchEffect(() => {
  if (!data.value) return
  name.value = data.value.name
  description.value = data.value.description ?? ''
  isPublic.value = !!data.value.is_public
  items.value = (data.value.exercises ?? []).map(e => ({
    key: keySeq++,
    exercise_id: e.exercise_id,
    exercise: e.exercise,
    sets: e.sets ?? 3,
    target_reps: e.target_reps ?? '8-12',
    rest_seconds: e.rest_seconds ?? 90,
    tempo: e.tempo,
    target_weight: e.target_weight != null ? Number(e.target_weight) : null,
    notes: e.notes
  }))
})

function markDirty() { dirty.value = true }

function moveItem(i: number, dir: -1 | 1) {
  const j = i + dir
  if (j < 0 || j >= items.value.length) return
  const arr = items.value
  ;[arr[i], arr[j]] = [arr[j]!, arr[i]!]
  markDirty()
}
function removeItem(i: number) { items.value.splice(i, 1); markDirty() }
function duplicateItem(i: number) {
  const src = items.value[i]!
  items.value.splice(i + 1, 0, { ...src, key: keySeq++ })
  markDirty()
}

// Picker
const pickerOpen = ref(false)
const search = ref('')
const { data: results } = await useAsyncData(
  'routine-ex-picker',
  () => search.value ? api<{ data: ExerciseLite[] }>('/api/exercises', { query: { search: search.value, per_page: 15 } }) : Promise.resolve({ data: [] as ExerciseLite[] }),
  { watch: [search], lazy: true }
)
function addExercise(e: ExerciseLite) {
  items.value.push({ key: keySeq++, exercise_id: e.id, exercise: e, sets: 3, target_reps: '8-12', rest_seconds: 90, tempo: null, target_weight: null, notes: null })
  pickerOpen.value = false
  search.value = ''
  markDirty()
}

async function save() {
  saving.value = true
  try {
    const payload = {
      name: name.value,
      description: description.value || null,
      is_public: isPublic.value,
      exercises: items.value.map((it, i) => ({
        exercise_id: it.exercise_id,
        position: i + 1,
        sets: it.sets,
        target_reps: it.target_reps,
        rest_seconds: it.rest_seconds,
        tempo: it.tempo,
        target_weight: it.target_weight,
        notes: it.notes
      }))
    }
    await api(`/api/routines/${routineId}`, { method: 'PUT', body: payload })
    dirty.value = false
    toast.add({ title: t('routines.builder.saved'), color: 'primary' })
  } catch {
    toast.add({ title: t('common.error'), color: 'error' })
  } finally {
    saving.value = false
  }
}
</script>

<template>
  <div class="space-y-4 pb-28">
    <div class="flex items-center justify-between">
      <UButton to="/routines" icon="i-lucide-arrow-left" color="neutral" variant="ghost" :label="t('common.back')" />
      <UBadge v-if="dirty" color="warning" variant="soft" size="sm">{{ t('routines.builder.unsaved') }}</UBadge>
    </div>

    <!-- En-tête éditable -->
    <div class="space-y-2">
      <UInput v-model="name" :placeholder="t('routines.builder.namePlaceholder')" size="xl" variant="none" class="w-full text-2xl font-black -ml-1" @update:model-value="markDirty" />
      <UTextarea v-model="description" :placeholder="t('routines.builder.descPlaceholder')" :rows="1" autoresize variant="soft" class="w-full" @update:model-value="markDirty" />
      <div class="flex items-center gap-2">
        <USwitch v-model="isPublic" size="sm" @update:model-value="markDirty" />
        <span class="text-sm text-zinc-500">{{ t('routines.builder.public') }}</span>
      </div>
    </div>

    <p v-if="!items.length" class="text-center text-zinc-400 py-10">{{ t('routines.builder.empty') }}</p>

    <!-- Exercices -->
    <div v-for="(it, i) in items" :key="it.key" class="rounded-xl border border-zinc-200 dark:border-zinc-800 overflow-hidden">
      <div class="flex items-center gap-3 p-3 bg-zinc-50 dark:bg-zinc-900/50">
        <span class="shrink-0 size-7 rounded-full sf-flame-bg text-white text-sm font-bold flex items-center justify-center">{{ i + 1 }}</span>
        <img v-if="it.exercise.image_url" :src="it.exercise.image_url" :alt="it.exercise.name" class="size-10 rounded-lg object-cover">
        <p class="font-semibold capitalize flex-1 truncate">{{ it.exercise.name }}</p>
        <div class="flex items-center">
          <UButton icon="i-lucide-chevron-up" color="neutral" variant="ghost" size="xs" :disabled="i === 0" @click="moveItem(i, -1)" />
          <UButton icon="i-lucide-chevron-down" color="neutral" variant="ghost" size="xs" :disabled="i === items.length - 1" @click="moveItem(i, 1)" />
          <UDropdownMenu :items="[[{ label: t('routines.builder.duplicate'), icon: 'i-lucide-copy', onSelect: () => duplicateItem(i) }, { label: t('routines.builder.remove'), icon: 'i-lucide-trash-2', color: 'error', onSelect: () => removeItem(i) }]]">
            <UButton icon="i-lucide-more-vertical" color="neutral" variant="ghost" size="xs" />
          </UDropdownMenu>
        </div>
      </div>
      <div class="p-3 grid grid-cols-2 gap-3">
        <UFormField :label="t('routines.builder.sets')" size="xs">
          <UInput v-model.number="it.sets" type="number" min="1" size="sm" class="w-full" @update:model-value="markDirty" />
        </UFormField>
        <UFormField :label="t('routines.builder.reps')" size="xs">
          <UInput v-model="it.target_reps" placeholder="8-12" size="sm" class="w-full" @update:model-value="markDirty" />
        </UFormField>
        <UFormField :label="t('routines.builder.rest')" size="xs">
          <UInput v-model.number="it.rest_seconds" type="number" min="0" step="15" size="sm" class="w-full" @update:model-value="markDirty" />
        </UFormField>
        <UFormField :label="t('routines.builder.weight')" size="xs">
          <UInput v-model.number="it.target_weight" type="number" min="0" step="2.5" size="sm" class="w-full" @update:model-value="markDirty" />
        </UFormField>
        <UFormField :label="t('routines.builder.tempo')" size="xs">
          <UInput v-model="it.tempo" placeholder="3-1-1" size="sm" class="w-full" @update:model-value="markDirty" />
        </UFormField>
        <UFormField :label="t('routines.builder.notes')" size="xs">
          <UInput v-model="it.notes" size="sm" class="w-full" @update:model-value="markDirty" />
        </UFormField>
      </div>
    </div>

    <UButton block color="neutral" variant="subtle" icon="i-lucide-plus" :label="t('routines.builder.addExercise')" @click="pickerOpen = true" />

    <UButton v-if="items.length" block size="lg" color="primary" variant="soft" icon="i-lucide-play" :label="t('routines.builder.start')" :to="`/session/new?routine=${routineId}`" />

    <!-- Barre de sauvegarde fixe -->
    <div class="fixed bottom-0 inset-x-0 z-40 border-t border-zinc-200 dark:border-zinc-800 bg-white/95 dark:bg-zinc-950/95 backdrop-blur p-3">
      <div class="max-w-2xl mx-auto">
        <UButton block size="lg" color="primary" class="font-bold" icon="i-lucide-save" :label="t('routines.builder.save')" :loading="saving" :disabled="!dirty" @click="save" />
      </div>
    </div>

    <!-- Picker -->
    <UModal v-model:open="pickerOpen" :title="t('routines.builder.addExercise')">
      <template #body>
        <UInput v-model="search" icon="i-lucide-search" :placeholder="t('exercises.search')" size="lg" class="w-full mb-3" autofocus />
        <div class="max-h-96 overflow-y-auto space-y-1">
          <button v-for="e in results?.data ?? []" :key="e.id" class="w-full flex items-center gap-3 p-2 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800 text-left" @click="addExercise(e)">
            <img v-if="e.image_url" :src="e.image_url" :alt="e.name" class="size-9 rounded object-cover">
            <span class="text-sm font-medium capitalize">{{ e.name }}</span>
          </button>
        </div>
      </template>
    </UModal>
  </div>
</template>
