<script setup lang="ts">
import type { MandateCreate } from '~/stores/mandates'

const mandates = useMandatesStore()

const filterType = ref<string | undefined>(undefined)
const filterStatus = ref<string | undefined>(undefined)

const typeOptions = [
  { label: 'Tous les types', value: undefined },
  { label: 'Comite technique', value: 'techcomm' },
  { label: 'Forgeron', value: 'smith' },
  { label: 'Personnalise', value: 'custom' },
]

const statusOptions = [
  { label: 'Tous les statuts', value: undefined },
  { label: 'Brouillon', value: 'draft' },
  { label: 'Candidature', value: 'candidacy' },
  { label: 'En vote', value: 'voting' },
  { label: 'Actif', value: 'active' },
  { label: 'Rapport', value: 'reporting' },
  { label: 'Termine', value: 'completed' },
  { label: 'Revoque', value: 'revoked' },
]

async function loadMandates() {
  await mandates.fetchAll({
    mandate_type: filterType.value,
    status: filterStatus.value,
  })
}

onMounted(() => {
  loadMandates()
})

watch([filterType, filterStatus], () => {
  loadMandates()
})

// --- Create mandate modal ---

const showCreateModal = ref(false)
const mandateTypeOptions = [
  { label: 'Comite technique', value: 'techcomm' },
  { label: 'Forgeron', value: 'smith' },
  { label: 'Personnalise', value: 'custom' },
]

const newMandate = ref<MandateCreate>({
  title: '',
  description: '',
  mandate_type: 'techcomm',
})
const creating = ref(false)

async function handleCreate() {
  creating.value = true
  try {
    const mandate = await mandates.create(newMandate.value)
    showCreateModal.value = false
    newMandate.value = { title: '', description: '', mandate_type: 'techcomm' }
    if (mandate) {
      navigateTo(`/mandates/${mandate.id}`)
    }
  } catch {
    // Error handled by store
  } finally {
    creating.value = false
  }
}
</script>

<template>
  <div class="space-y-6">
    <!-- Header -->
    <div class="flex items-start justify-between">
      <div>
        <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
          Mandats
        </h1>
        <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">
          Mandats de gouvernance : comite technique, forgerons et roles specifiques
        </p>
      </div>
      <UButton
        icon="i-lucide-plus"
        label="Nouveau mandat"
        color="primary"
        @click="showCreateModal = true"
      />
    </div>

    <!-- Filters -->
    <div class="flex flex-wrap gap-4">
      <USelect
        v-model="filterType"
        :items="typeOptions"
        placeholder="Type de mandat"
        class="w-56"
      />
      <USelect
        v-model="filterStatus"
        :items="statusOptions"
        placeholder="Statut"
        class="w-48"
      />
    </div>

    <!-- Loading state -->
    <template v-if="mandates.loading">
      <div class="space-y-3">
        <USkeleton v-for="i in 4" :key="i" class="h-12 w-full" />
      </div>
    </template>

    <!-- Error state -->
    <template v-else-if="mandates.error">
      <UCard>
        <div class="flex items-center gap-3 text-red-500">
          <UIcon name="i-lucide-alert-circle" class="text-xl" />
          <p>{{ mandates.error }}</p>
        </div>
      </UCard>
    </template>

    <!-- Empty state -->
    <template v-else-if="mandates.list.length === 0">
      <UCard>
        <div class="text-center py-8">
          <UIcon name="i-lucide-user-check" class="text-4xl text-gray-400 mb-3" />
          <p class="text-gray-500">Aucun mandat pour le moment</p>
        </div>
      </UCard>
    </template>

    <!-- Mandates list -->
    <template v-else>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <MandatesMandateCard
          v-for="mandate in mandates.list"
          :key="mandate.id"
          :mandate="mandate"
        />
      </div>
    </template>

    <!-- Create mandate modal -->
    <UModal v-model:open="showCreateModal">
      <template #content>
        <form class="p-6 space-y-4" @submit.prevent="handleCreate">
          <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
            Nouveau mandat
          </h3>

          <div class="space-y-1">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">
              Titre <span class="text-red-500">*</span>
            </label>
            <UInput
              v-model="newMandate.title"
              placeholder="Titre du mandat..."
              required
            />
          </div>

          <div class="space-y-1">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">
              Description
            </label>
            <UTextarea
              v-model="newMandate.description"
              placeholder="Description du mandat..."
              :rows="3"
            />
          </div>

          <div class="space-y-1">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">
              Type de mandat <span class="text-red-500">*</span>
            </label>
            <USelect
              v-model="newMandate.mandate_type"
              :items="mandateTypeOptions"
            />
          </div>

          <div class="flex justify-end gap-2 pt-4 border-t border-gray-200 dark:border-gray-700">
            <UButton
              label="Annuler"
              variant="ghost"
              color="neutral"
              @click="showCreateModal = false"
            />
            <UButton
              type="submit"
              label="Creer"
              icon="i-lucide-plus"
              color="primary"
              :loading="creating"
              :disabled="!newMandate.title?.trim()"
            />
          </div>
        </form>
      </template>
    </UModal>
  </div>
</template>
