<template>
  <div class="space-y-2">
    <div class="flex gap-2">
      <input
        v-model="inputValue"
        type="text"
        :placeholder="placeholder || 'Add CIDR (e.g., 192.168.1.0/24)'"
        class="flex-1 bg-white/5 backdrop-blur-sm border border-white/10 rounded-lg px-4 py-2 text-white placeholder-white/30 focus:outline-none focus:border-cyan-400/50 transition-colors"
        @keydown.enter="addCIDR"
      />
      <button
        @click="addCIDR"
        class="px-4 py-2 bg-white/10 backdrop-blur-md rounded-lg border border-white/20 shadow-xl hover:bg-white/20 hover:border-cyan-400/50 transition-all duration-300 text-cyan-400"
      >
        Add
      </button>
    </div>
    <p v-if="error" class="text-red-400 text-sm">{{ error }}</p>
    <div class="flex flex-wrap gap-2">
      <div
        v-for="(cidr, index) in modelValue"
        :key="index"
        class="flex items-center gap-1 px-3 py-1 bg-white/10 backdrop-blur-md border border-white/20 rounded-full text-white/90 text-sm hover:border-cyan-400/30 transition-colors"
      >
        <span>{{ cidr }}</span>
        <button
          @click="removeCIDR(index)"
          class="text-white/50 hover:text-red-400 transition-colors ml-1"
        >
          &times;
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const props = defineProps<{
  modelValue: string[]
  placeholder?: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: string[]): void
}>()

const inputValue = ref('')
const error = ref('')

const validateCIDR = (cidr: string): boolean => {
  const cidrRegex = /^(\d{1,3}\.){3}\d{1,3}\/(\d{1,2})$/
  if (!cidrRegex.test(cidr)) {
    error.value = 'Invalid CIDR format. Use e.g., 192.168.1.0/24'
    return false
  }
  const [ip, prefixStr] = cidr.split('/')
  const octets = ip.split('.').map(Number)
  const prefix = Number(prefixStr)
  
  if (octets.some(octet => octet < 0 || octet > 255)) {
    error.value = 'Invalid IP octet (must be 0-255)'
    return false
  }
  if (prefix < 0 || prefix > 32) {
    error.value = 'Invalid prefix (must be 0-32)'
    return false
  }
  error.value = ''
  return true
}

const addCIDR = () => {
  const trimmed = inputValue.value.trim()
  if (!trimmed) return
  if (props.modelValue.includes(trimmed)) {
    error.value = 'CIDR already exists'
    return
  }
  if (validateCIDR(trimmed)) {
    emit('update:modelValue', [...props.modelValue, trimmed])
    inputValue.value = ''
    error.value = ''
  }
}

const removeCIDR = (index: number) => {
  const newList = [...props.modelValue]
  newList.splice(index, 1)
  emit('update:modelValue', newList)
}
</script>
