<template>
  <div>
    <div class="flex items-center justify-between pb-12">
      <h1 class="text-4xl font-bold text-primary-500">Sites</h1>
      <button
        type="button"
        class="rounded-lg bg-primary-500 px-4 py-2 text-md font-semibold text-white hover:bg-secondary-500"
        @click="openCreate"
      >
        Ajouter un site
      </button>
    </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="max-h-[80vh] overflow-auto rounded-lg border border-neutral-200 bg-white">
      <div class="grid grid-cols-[1fr_140px_160px] gap-4 border-b border-neutral-200 bg-tertiary-500 px-6 py-3 text-md font-semibold text-neutral-700">
        <span class="text-left">Nom</span>
        <span class="text-left">Couleur</span>
        <span class="text-right">Actions</span>
      </div>
      <div v-if="isLoading" class="px-6 py-4 text-md text-neutral-500">
        Chargement...
      </div>
      <div v-else>
        <div
          v-for="site in sites"
          :key="site.id"
          class="grid grid-cols-[1fr_140px_160px] items-center gap-4 border-b border-neutral-100 px-6 py-3 text-md text-neutral-800 last:border-b-0"
        >
          <span class="text-left">{{ site.name }}</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 class="flex items-center justify-end gap-2">
            <button
              type="button"
              class="rounded-md border border-neutral-200 px-2 py-1 text-md font-semibold text-neutral-700 hover:bg-neutral-100"
              @click="openEdit(site)"
            >
              Modifier
            </button>
            <button
              type="button"
              class="rounded-md border border-red-200 px-2 py-1 text-md font-semibold text-red-600 hover:bg-red-50"
              @click="confirmDelete(site)"
            >
              Supprimer
            </button>
          </div>
        </div>
      </div>
    </div>

    <AppDrawer v-model="isDrawerOpen" :title="drawerTitle">
      <form class="space-y-4" @submit.prevent="handleSubmit">
        <div>
          <label class="text-md font-semibold text-neutral-700" for="name">Nom</label>
          <input
            id="name"
            v-model="form.name"
            type="text"
            class="mt-2 w-full rounded-md border border-neutral-300 px-3 py-2 text-base text-neutral-900 focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-200"
          />
        </div>
        <div>
          <label class="text-md font-semibold text-neutral-700" for="color">Couleur</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 class="flex justify-end gap-3 pt-2">
          <button
            type="button"
            class="rounded-lg border border-neutral-200 px-4 py-2 text-md font-semibold text-neutral-700 hover:bg-neutral-100"
            @click="closeDrawer"
          >
            Annuler
          </button>
          <button
            type="submit"
            class="rounded-lg bg-primary-500 px-4 py-2 text-md font-semibold text-white hover:bg-secondary-500"
            :disabled="isSubmitting"
          >
            Enregistrer
          </button>
        </div>
      </form>
    </AppDrawer>
  </div>
</template>

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

const isDrawerOpen = ref(false)
const isSubmitting = ref(false)
const isLoading = 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 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

  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
      })
    }

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

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

  await deleteSite(site.id)
  await loadSites()
}
</script>
