<script setup lang="ts">
/**
 * Protocols index page.
 *
 * Lists all voting protocols with ModeParamsDisplay component,
 * links to protocol detail pages, and provides creation modal
 * and simulator link.
 */
const protocols = useProtocolsStore()
const auth = useAuthStore()

const showCreateModal = ref(false)
const creating = ref(false)

/** Creation form state. */
const newProtocol = reactive({
  name: '',
  description: '',
  vote_type: 'binary',
  formula_config_id: '',
})

onMounted(async () => {
  await Promise.all([
    protocols.fetchProtocols(),
    protocols.fetchFormulas(),
  ])
})

const voteTypeLabel = (voteType: string) => {
  switch (voteType) {
    case 'binary': return 'Binaire'
    case 'nuanced': return 'Nuance'
    default: return voteType
  }
}

const voteTypeColor = (voteType: string) => {
  switch (voteType) {
    case 'binary': return 'primary'
    case 'nuanced': return 'info'
    default: return 'neutral'
  }
}

const voteTypeOptions = [
  { label: 'Binaire (Pour/Contre)', value: 'binary' },
  { label: 'Nuance (6 niveaux)', value: 'nuanced' },
]

const formulaOptions = computed(() => {
  return protocols.formulas.map(f => ({
    label: f.name,
    value: f.id,
  }))
})

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('fr-FR', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  })
}

function openCreateModal() {
  newProtocol.name = ''
  newProtocol.description = ''
  newProtocol.vote_type = 'binary'
  newProtocol.formula_config_id = ''
  showCreateModal.value = true
}

async function createProtocol() {
  if (!newProtocol.name.trim() || !newProtocol.formula_config_id) return

  creating.value = true
  try {
    await protocols.createProtocol({
      name: newProtocol.name.trim(),
      description: newProtocol.description.trim() || null,
      vote_type: newProtocol.vote_type,
      formula_config_id: newProtocol.formula_config_id,
    })
    showCreateModal.value = false
    await protocols.fetchProtocols()
  } finally {
    creating.value = false
  }
}
</script>

<template>
  <div class="space-y-8">
    <!-- Header -->
    <div class="flex items-start justify-between">
      <div>
        <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
          Protocoles de vote
        </h1>
        <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">
          Configuration des protocoles de vote et formules de seuil WoT
        </p>
      </div>
      <div class="flex items-center gap-3">
        <NuxtLink to="/protocols/formulas">
          <UButton variant="outline" icon="i-lucide-calculator" size="sm">
            Simulateur de formules
          </UButton>
        </NuxtLink>
        <UButton
          v-if="auth.isAuthenticated"
          icon="i-lucide-plus"
          size="sm"
          @click="openCreateModal"
        >
          Nouveau protocole
        </UButton>
      </div>
    </div>

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

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

    <template v-else>
      <!-- Voting Protocols -->
      <div>
        <h2 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
          Protocoles ({{ protocols.protocols.length }})
        </h2>

        <div v-if="protocols.protocols.length === 0">
          <UCard>
            <div class="text-center py-8">
              <UIcon name="i-lucide-settings" class="text-4xl text-gray-400 mb-3" />
              <p class="text-gray-500">Aucun protocole de vote configure</p>
            </div>
          </UCard>
        </div>

        <div v-else class="grid grid-cols-1 lg:grid-cols-2 gap-4">
          <NuxtLink
            v-for="protocol in protocols.protocols"
            :key="protocol.id"
            :to="`/protocols/${protocol.id}`"
            class="block"
          >
            <UCard class="hover:ring-2 hover:ring-primary-300 dark:hover:ring-primary-700 transition-all cursor-pointer">
              <div class="space-y-4">
                <!-- Protocol header -->
                <div class="flex items-start justify-between">
                  <div>
                    <h3 class="font-semibold text-gray-900 dark:text-white">
                      {{ protocol.name }}
                    </h3>
                    <p v-if="protocol.description" class="text-sm text-gray-500 mt-0.5">
                      {{ protocol.description }}
                    </p>
                  </div>
                  <div class="flex items-center gap-2">
                    <UBadge :color="(voteTypeColor(protocol.vote_type) as any)" variant="subtle" size="xs">
                      {{ voteTypeLabel(protocol.vote_type) }}
                    </UBadge>
                    <UBadge v-if="protocol.is_meta_governed" color="warning" variant="subtle" size="xs">
                      Meta-gouverne
                    </UBadge>
                  </div>
                </div>

                <!-- Mode params with component -->
                <div v-if="protocol.mode_params">
                  <ModeParamsDisplay :mode-params="protocol.mode_params" />
                </div>

                <!-- Formula config summary -->
                <div class="border-t border-gray-100 dark:border-gray-800 pt-3">
                  <h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">
                    Formule : {{ protocol.formula_config.name }}
                  </h4>
                  <div class="grid grid-cols-3 gap-2 text-xs">
                    <div>
                      <span class="text-gray-400 block">Duree</span>
                      <span class="font-medium text-gray-900 dark:text-white">
                        {{ protocol.formula_config.duration_days }}j
                      </span>
                    </div>
                    <div>
                      <span class="text-gray-400 block">Majorite</span>
                      <span class="font-medium text-gray-900 dark:text-white">
                        {{ protocol.formula_config.majority_pct }}%
                      </span>
                    </div>
                    <div>
                      <span class="text-gray-400 block">Base</span>
                      <span class="font-medium text-gray-900 dark:text-white">
                        {{ protocol.formula_config.base_exponent }}
                      </span>
                    </div>
                    <div>
                      <span class="text-gray-400 block">Gradient</span>
                      <span class="font-medium text-gray-900 dark:text-white">
                        {{ protocol.formula_config.gradient_exponent }}
                      </span>
                    </div>
                    <div v-if="protocol.formula_config.smith_exponent !== null">
                      <span class="text-gray-400 block">Smith</span>
                      <span class="font-medium text-gray-900 dark:text-white">
                        {{ protocol.formula_config.smith_exponent }}
                      </span>
                    </div>
                    <div v-if="protocol.formula_config.techcomm_exponent !== null">
                      <span class="text-gray-400 block">TechComm</span>
                      <span class="font-medium text-gray-900 dark:text-white">
                        {{ protocol.formula_config.techcomm_exponent }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </UCard>
          </NuxtLink>
        </div>
      </div>

      <!-- Formula Configurations -->
      <div>
        <h2 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
          Configurations de formule ({{ protocols.formulas.length }})
        </h2>

        <div v-if="protocols.formulas.length === 0">
          <UCard>
            <div class="text-center py-8">
              <UIcon name="i-lucide-calculator" class="text-4xl text-gray-400 mb-3" />
              <p class="text-gray-500">Aucune configuration de formule</p>
            </div>
          </UCard>
        </div>

        <div v-else>
          <UCard>
            <div class="overflow-x-auto">
              <table class="w-full text-sm">
                <thead>
                  <tr class="border-b border-gray-200 dark:border-gray-700">
                    <th class="text-left px-4 py-3 font-medium text-gray-500">Nom</th>
                    <th class="text-left px-4 py-3 font-medium text-gray-500">Duree</th>
                    <th class="text-left px-4 py-3 font-medium text-gray-500">Majorite</th>
                    <th class="text-left px-4 py-3 font-medium text-gray-500">B</th>
                    <th class="text-left px-4 py-3 font-medium text-gray-500">G</th>
                    <th class="text-left px-4 py-3 font-medium text-gray-500">C</th>
                    <th class="text-left px-4 py-3 font-medium text-gray-500">Smith</th>
                    <th class="text-left px-4 py-3 font-medium text-gray-500">TechComm</th>
                    <th class="text-left px-4 py-3 font-medium text-gray-500">Date</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="formula in protocols.formulas"
                    :key="formula.id"
                    class="border-b border-gray-100 dark:border-gray-800"
                  >
                    <td class="px-4 py-3 font-medium text-gray-900 dark:text-white">
                      {{ formula.name }}
                    </td>
                    <td class="px-4 py-3 text-gray-600">{{ formula.duration_days }}j</td>
                    <td class="px-4 py-3 text-gray-600">{{ formula.majority_pct }}%</td>
                    <td class="px-4 py-3 font-mono text-gray-600">{{ formula.base_exponent }}</td>
                    <td class="px-4 py-3 font-mono text-gray-600">{{ formula.gradient_exponent }}</td>
                    <td class="px-4 py-3 font-mono text-gray-600">{{ formula.constant_base }}</td>
                    <td class="px-4 py-3 font-mono text-gray-600">
                      {{ formula.smith_exponent ?? '-' }}
                    </td>
                    <td class="px-4 py-3 font-mono text-gray-600">
                      {{ formula.techcomm_exponent ?? '-' }}
                    </td>
                    <td class="px-4 py-3 text-gray-500 text-xs">
                      {{ formatDate(formula.created_at) }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </UCard>
        </div>
      </div>

      <!-- Formula explainer -->
      <UCard>
        <div class="space-y-3">
          <h3 class="text-sm font-semibold text-gray-500 uppercase tracking-wide">
            Reference : Formule de seuil WoT
          </h3>
          <code class="block p-3 bg-gray-100 dark:bg-gray-800 rounded text-sm font-mono">
            Seuil = C + B^W + (M + (1-M) * (1 - (T/W)^G)) * max(0, T-C)
          </code>
          <div class="grid grid-cols-2 md:grid-cols-3 gap-3 text-xs text-gray-500">
            <div><strong>C</strong> = constante de base (plancher fixe)</div>
            <div><strong>B</strong> = exposant de base (B^W tend vers 0 si B &lt; 1)</div>
            <div><strong>W</strong> = taille du corpus WoT</div>
            <div><strong>T</strong> = nombre total de votes</div>
            <div><strong>M</strong> = ratio de majorite (M = majorite_pct / 100)</div>
            <div><strong>G</strong> = exposant du gradient d'inertie</div>
          </div>
        </div>
      </UCard>
    </template>

    <!-- Create protocol modal -->
    <UModal v-model:open="showCreateModal">
      <template #content>
        <div class="p-6 space-y-6">
          <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
            Nouveau protocole de vote
          </h3>

          <div class="space-y-4">
            <div class="space-y-2">
              <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
                Nom du protocole
              </label>
              <UInput v-model="newProtocol.name" placeholder="Ex: Vote standard G1" />
            </div>

            <div class="space-y-2">
              <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
                Description (optionnel)
              </label>
              <UTextarea v-model="newProtocol.description" placeholder="Description du protocole..." :rows="2" />
            </div>

            <div class="space-y-2">
              <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
                Type de vote
              </label>
              <USelect
                v-model="newProtocol.vote_type"
                :items="voteTypeOptions"
                value-key="value"
              />
            </div>

            <div class="space-y-2">
              <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
                Configuration de formule
              </label>
              <USelect
                v-model="newProtocol.formula_config_id"
                :items="formulaOptions"
                placeholder="Selectionnez une formule..."
                value-key="value"
              />
            </div>
          </div>

          <div class="flex justify-end gap-3">
            <UButton variant="ghost" color="neutral" @click="showCreateModal = false">
              Annuler
            </UButton>
            <UButton
              :loading="creating"
              :disabled="!newProtocol.name.trim() || !newProtocol.formula_config_id"
              @click="createProtocol"
            >
              Creer le protocole
            </UButton>
          </div>
        </div>
      </template>
    </UModal>
  </div>
</template>
