<template>
  <div class="h-full flex flex-col overflow-hidden">
    <div class="flex items-center justify-between pb-6">
      <h1 class="text-4xl font-bold text-primary-500">Sites</h1>
      <MalioButton
        label="Ajouter"
        icon-name="mdi:plus"
        icon-position="left"
        @click="openCreate"
      />
    </div>

    <div
      v-if="!isLoading && sites.length === 0"
      class="rounded-lg border border-neutral-200 bg-white p-6 text-md text-neutral-600"
    >
      Aucun site pour le moment.
    </div>

    <div v-else class="min-h-0 overflow-auto rounded-md bg-white">
      <div class="grid grid-cols-[1fr_140px] gap-4 border border-black bg-tertiary-500 px-6 py-3 text-[20px] font-semibold text-black rounded-t-md sticky top-0 z-10">
        <span class="text-left">Nom</span>
        <span class="text-left">Couleur</span>
      </div>
      <div v-if="isLoading" class="px-6 py-4 text-md text-neutral-500">
        Chargement...
      </div>
      <div v-else class="border-x border-b border-primary-500 rounded-b-md">
        <div
          v-for="site in sites"
          :key="site.id"
          class="grid grid-cols-[1fr_140px] items-center gap-4 border-b border-primary-500 px-6 py-3 text-md font-bold text-primary-500 last:border-b-0 cursor-pointer hover:bg-tertiary-500"
          draggable="true"
          @click="openEdit(site)"
          @dragstart="handleDragStart($event, site)"
          @dragover="handleDragOver"
          @drop="handleDrop($event, site)"
        >
          <span class="flex items-center gap-2 text-left">
            <span class="select-none text-xs">::</span>
            <span>{{ site.name }}</span>
          </span>
          <div class="flex items-center gap-2 justify-start">
            <span
              class="inline-block h-3 w-3 rounded-full"
              :style="{ backgroundColor: site.color }"
            />
            <span class="text-md uppercase text-neutral-500">{{ site.color }}</span>
          </div>
        </div>
      </div>
    </div>

    <MalioDrawer v-model="isDrawerOpen">
      <template #header>
        <h2 class="text-[32px] font-semibold text-primary-500">{{ drawerTitle }}</h2>
      </template>
      <form class="space-y-4" @submit.prevent="handleSubmit">
        <MalioInputText :reserve-message-space="false"
          v-model="form.name"
          label="Nom *"
          group-class="mt-2"
          :error="showNameError ? 'Le nom du site est obligatoire.' : ''"
        />
        <div>
          <label class="text-md font-semibold text-neutral-700" for="color">
            Couleur <span class="text-red-600">*</span>
          </label>
          <div class="mt-2 flex items-center gap-3">
            <input
              id="color"
              v-model="form.color"
              type="color"
              class="h-10 w-16 cursor-pointer rounded-md border border-neutral-300 bg-white p-1"
            />
            <span class="text-md font-semibold text-neutral-600">{{ form.color }}</span>
          </div>
        </div>
        <div v-if="editingSite" class="grid grid-cols-2 gap-3 pt-2">
          <MalioButton
            label="Supprimer"
            variant="danger"
            button-class="w-full"
            @click="confirmDelete(editingSite)"
          />
          <MalioButton
            type="submit"
            label="Modifier"
            button-class="w-full"
            :disabled="isSubmitting || !isFormValid"
          />
        </div>
        <div v-else class="flex justify-center pt-2">
          <MalioButton
            type="submit"
            label="Valider"
            button-class="w-[200px]"
            :disabled="isSubmitting || !isFormValid"
          />
        </div>
      </form>
    </MalioDrawer>
  </div>
</template>

<script setup lang="ts">
import type { Site } from '~/services/dto/site'
import { createSite, deleteSite, listSites, updateSite, updateSiteOrder } from '~/services/sites'

useHead({
    title: 'Sites'
})

const isDrawerOpen = ref(false)
const isSubmitting = ref(false)
const isLoading = ref(false)
const isReordering = ref(false)

const sites = ref<Site[]>([])
const editingSite = ref<Site | null>(null)

const drawerTitle = computed(() =>
  editingSite.value ? 'Modifier un site' : 'Ajouter un site'
)

const form = reactive({
  name: '',
  color: '#222783'
})

const validationTouched = reactive({
  name: false
})

const isNameValid = computed(() => form.name.trim() !== '')
const isFormValid = computed(() => isNameValid.value)

const showNameError = computed(() => validationTouched.name && !isNameValid.value)

const loadSites = async () => {
  isLoading.value = true
  try {
    sites.value = await listSites()
  } finally {
    isLoading.value = false
  }
}

onMounted(loadSites)

const resetForm = () => {
  form.name = ''
  form.color = '#222783'
}

const openCreate = () => {
  editingSite.value = null
  resetForm()
  isDrawerOpen.value = true
}

const openEdit = (site: Site) => {
  editingSite.value = site
  form.name = site.name
  form.color = site.color
  isDrawerOpen.value = true
}

const closeDrawer = () => {
  isDrawerOpen.value = false
  editingSite.value = null
  resetForm()
}

const handleSubmit = async () => {
  if (isSubmitting.value) return
  validationTouched.name = true
  if (!isFormValid.value) return

  isSubmitting.value = true
  try {
    if (editingSite.value) {
      await updateSite(editingSite.value.id, {
        name: form.name,
        color: form.color
      })
    } else {
      await createSite({
        name: form.name,
        color: form.color,
        displayOrder: sites.value.length + 1
      })
    }

    closeDrawer()
    await loadSites()
  } finally {
    isSubmitting.value = false
  }
}

watch(isDrawerOpen, (isOpen) => {
  if (!isOpen) {
    validationTouched.name = false
  }
})

const confirmDelete = async (site: Site) => {
  const ok = window.confirm(`Supprimer le site ${site.name} ?`)
  if (!ok) return

  await deleteSite(site.id)
  await loadSites()
}

const handleDragStart = (event: DragEvent, site: Site) => {
  if (isReordering.value || !event.dataTransfer) return
  event.dataTransfer.effectAllowed = 'move'
  event.dataTransfer.setData('text/plain', String(site.id))
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
}

const handleDrop = async (event: DragEvent, site: Site) => {
  event.preventDefault()
  if (isReordering.value) return

  const dragId = Number(event.dataTransfer?.getData('text/plain'))
  if (!dragId || dragId === site.id) return

  const fromIndex = sites.value.findIndex((item) => item.id === dragId)
  const toIndex = sites.value.findIndex((item) => item.id === site.id)
  if (fromIndex < 0 || toIndex < 0 || fromIndex === toIndex) return

  const reordered = [...sites.value]
  const [moved] = reordered.splice(fromIndex, 1)
  reordered.splice(toIndex, 0, moved)

  const updates: Array<{ id: number; displayOrder: number }> = []
  reordered.forEach((item, index) => {
    const nextOrder = index + 1
    if ((item.displayOrder ?? 0) !== nextOrder) {
      updates.push({ id: item.id, displayOrder: nextOrder })
    }
    item.displayOrder = nextOrder
  })

  sites.value = reordered
  if (updates.length === 0) return

  isReordering.value = true
  try {
    await Promise.all(updates.map((update) => updateSiteOrder(update.id, update.displayOrder)))
  } catch {
    window.alert("Impossible de reordonner les sites.")
    await loadSites()
  } finally {
    isReordering.value = false
  }
}
</script>
