<template>
  <GlassCard class="p-6 overflow-x-auto">
    <div class="flex justify-between items-center mb-4">
      <h2 class="text-xl font-semibold text-cyan-400">Peer Management</h2>
      <GlassButton @click="isAddPeerModalOpen = true" class="from-cyan-500 to-blue-500">
        + Add Peer
      </GlassButton>
    </div>
    <table class="w-full text-left text-white/90">
      <thead>
        <tr class="border-b border-white/10">
          <th class="p-3 text-white/70">Peer Name</th>
          <th class="p-3 text-white/70">Public Key</th>
          <th class="p-3 text-white/70">IP Address</th>
          <th class="p-3 text-white/70">Allow Access (CIDRs)</th>
          <th class="p-3 text-white/70">Allow Internet</th>
          <th class="p-3 text-white/70">Expiry Date</th>
          <th class="p-3 text-white/70">Data Usage</th>
          <th class="p-3 text-white/70">Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="peer in peers" :key="peer.id" class="border-b border-white/5 hover:bg-white/5 transition-colors">
          <td class="p-3">{{ peer.name }}</td>
          <td class="p-3 font-mono text-sm text-white/70 truncate max-w-[200px]" :title="peer.publicKey">{{ peer.publicKey }}</td>
          <td class="p-3 font-mono text-sm text-white/70">{{ peer.ip }}</td>
          <td class="p-3">
            <CIDRTagInput v-model="peer.allowedAccess" placeholder="Add CIDR" />
          </td>
          <td class="p-3">
            <InternetToggle v-model="peer.allowInternet" />
          </td>
          <td class="p-3 text-white/70">
            {{ peer.expiresAt ? new Date(peer.expiresAt).toLocaleDateString() : 'Never' }}
          </td>
          <td class="p-3 text-white/70">
            {{ peer.currentDataUsageBytes ? formatBytes(peer.currentDataUsageBytes) : '0 B' }}
          </td>
          <td class="p-3 flex gap-2">
            <button @click="openEditPeer(peer)" class="px-3 py-1 bg-white/10 backdrop-blur-md rounded-lg border border-white/20 hover:bg-white/20 hover:border-yellow-400/50 transition-all text-yellow-400 text-sm">
              Edit
            </button>
            <button @click="showQRCode(peer)" class="px-3 py-1 bg-white/10 backdrop-blur-md rounded-lg border border-white/20 hover:bg-white/20 hover:border-cyan-400/50 transition-all text-cyan-400 text-sm">
              QR Code
            </button>
            <button @click="downloadConfig(peer.id)" class="px-3 py-1 bg-white/10 backdrop-blur-md rounded-lg border border-white/20 hover:bg-white/20 hover:border-green-400/50 transition-all text-green-400 text-sm">
              Config
            </button>
            <button @click="deletePeer(peer.id)" class="px-3 py-1 bg-white/10 backdrop-blur-md rounded-lg border border-white/20 hover:bg-white/20 hover:border-red-400/50 transition-all text-red-400 text-sm">
              Delete
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- Add Peer Modal -->
    <TransitionRoot appear :show="isAddPeerModalOpen" as="template">
      <TransitionChild
        as="template"
        enter="duration-300 ease-out"
        enter-from="opacity-0"
        enter-to="opacity-100"
        leave="duration-200 ease-in"
        leave-from="opacity-100"
        leave-to="opacity-0"
      >
        <div class="fixed inset-0 bg-black/70 backdrop-blur-sm" @click="isAddPeerModalOpen = false" />
      </TransitionChild>

      <TransitionChild
        as="template"
        enter="duration-300 ease-out"
        enter-from="opacity-0 scale-95"
        enter-to="opacity-100 scale-100"
        leave="duration-200 ease-in"
        leave-from="opacity-100 scale-100"
        leave-to="opacity-0 scale-95"
      >
        <DialogPanel class="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-lg rounded-2xl bg-gradient-to-br from-gray-900/90 to-gray-800/90 backdrop-blur-xl p-6 border border-white/20 shadow-xl">
          <DialogTitle class="text-lg font-medium text-cyan-400 mb-4">Add New Peer</DialogTitle>
          <div class="space-y-4">
            <div>
              <label class="block text-white/70 mb-1">Public Key</label>
              <GlassInput v-model="newPeer.publicKey" placeholder="Paste Public Key (or auto-generate)" class="w-full" />
            </div>
            <div>
              <label class="block text-white/70 mb-1">IP Address</label>
              <GlassInput v-model="newPeer.ip" placeholder="e.g., 10.0.0.5/32" class="w-full" />
            </div>
            <div>
              <label class="block text-white/70 mb-1">Allow Access (CIDRs)</label>
              <CIDRTagInput v-model="newPeer.allowedAccess" placeholder="Add CIDR (e.g., 192.168.1.0/24)" />
            </div>
            <div class="flex items-center justify-between">
              <span class="text-white/70">Allow Internet</span>
              <InternetToggle v-model="newPeer.allowInternet" />
            </div>
            <div>
              <label class="block text-white/70 mb-1">Expiry Date</label>
              <input 
                type="date" 
                v-model="newPeer.expiresAt" 
                class="w-full px-4 py-2 bg-white/5 backdrop-blur-md rounded-lg border border-white/20 text-white/90 focus:outline-none focus:border-cyan-400/50 transition-all"
              />
            </div>
            <div>
              <label class="block text-white/70 mb-1">Data Limit (GB)</label>
              <GlassInput 
                v-model.number="newPeer.dataLimitGB" 
                type="number" 
                min="0" 
                step="0.1" 
                placeholder="Leave empty for no limit" 
                class="w-full" 
              />
            </div>
          </div>
          <div class="flex gap-4 mt-6 justify-end">
            <GlassButton @click="isAddPeerModalOpen = false" class="from-gray-500 to-gray-600">Cancel</GlassButton>
            <GlassButton @click="addPeer" class="from-cyan-500 to-blue-500">Add Peer</GlassButton>
          </div>
        </DialogPanel>
      </TransitionChild>
    </TransitionRoot>

    <!-- Edit Peer Modal -->
    <TransitionRoot appear :show="isEditPeerModalOpen" as="template">
      <TransitionChild
        as="template"
        enter="duration-300 ease-out"
        enter-from="opacity-0"
        enter-to="opacity-100"
        leave="duration-200 ease-in"
        leave-from="opacity-100"
        leave-to="opacity-0"
      >
        <div class="fixed inset-0 bg-black/70 backdrop-blur-sm" @click="isEditPeerModalOpen = false" />
      </TransitionChild>

      <TransitionChild
        as="template"
        enter="duration-300 ease-out"
        enter-from="opacity-0 scale-95"
        enter-to="opacity-100 scale-100"
        leave="duration-200 ease-in"
        leave-from="opacity-100 scale-100"
        leave-to="opacity-0 scale-95"
      >
        <DialogPanel class="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-lg rounded-2xl bg-gradient-to-br from-gray-900/90 to-gray-800/90 backdrop-blur-xl p-6 border border-white/20 shadow-xl">
          <DialogTitle class="text-lg font-medium text-cyan-400 mb-4">Edit Peer</DialogTitle>
          <div class="space-y-4" v-if="selectedPeerForEdit">
            <div>
              <label class="block text-white/70 mb-1">Public Key</label>
              <GlassInput v-model="selectedPeerForEdit.publicKey" placeholder="Public Key" class="w-full" />
            </div>
            <div>
              <label class="block text-white/70 mb-1">IP Address</label>
              <GlassInput v-model="selectedPeerForEdit.ip" placeholder="e.g., 10.0.0.5/32" class="w-full" />
            </div>
            <div>
              <label class="block text-white/70 mb-1">Allow Access (CIDRs)</label>
              <CIDRTagInput v-model="selectedPeerForEdit.allowedAccess" placeholder="Add CIDR (e.g., 192.168.1.0/24)" />
            </div>
            <div class="flex items-center justify-between">
              <span class="text-white/70">Allow Internet</span>
              <InternetToggle v-model="selectedPeerForEdit.allowInternet" />
            </div>
            <div>
              <label class="block text-white/70 mb-1">Expiry Date</label>
              <input 
                type="date" 
                v-model="selectedPeerForEdit.expiresAt" 
                class="w-full px-4 py-2 bg-white/5 backdrop-blur-md rounded-lg border border-white/20 text-white/90 focus:outline-none focus:border-cyan-400/50 transition-all"
              />
            </div>
            <div>
              <label class="block text-white/70 mb-1">Data Limit (GB)</label>
              <GlassInput 
                v-model.number="selectedPeerForEdit.dataLimitGB" 
                type="number" 
                min="0" 
                step="0.1" 
                placeholder="Leave empty for no limit" 
                class="w-full" 
              />
            </div>
          </div>
          <div class="flex gap-4 mt-6 justify-end">
            <GlassButton @click="isEditPeerModalOpen = false" class="from-gray-500 to-gray-600">Cancel</GlassButton>
            <GlassButton @click="updatePeer" class="from-cyan-500 to-blue-500">Save Changes</GlassButton>
          </div>
        </DialogPanel>
      </TransitionChild>
    </TransitionRoot>

    <!-- QR Code Modal -->
    <TransitionRoot appear :show="isQRCodeModalOpen" as="template">
      <TransitionChild
        as="template"
        enter="duration-300 ease-out"
        enter-from="opacity-0"
        enter-to="opacity-100"
        leave="duration-200 ease-in"
        leave-from="opacity-100"
        leave-to="opacity-0"
      >
        <div class="fixed inset-0 bg-black/70 backdrop-blur-sm" @click="isQRCodeModalOpen = false" />
      </TransitionChild>

      <TransitionChild
        as="template"
        enter="duration-300 ease-out"
        enter-from="opacity-0 scale-95"
        enter-to="opacity-100 scale-100"
        leave="duration-200 ease-in"
        leave-from="opacity-100 scale-100"
        leave-to="opacity-0 scale-95"
      >
        <DialogPanel class="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-md rounded-2xl bg-gradient-to-br from-gray-900/90 to-gray-800/90 backdrop-blur-xl p-6 border border-white/20 shadow-xl">
          <DialogTitle class="text-lg font-medium text-cyan-400 mb-4">Peer QR Code</DialogTitle>
          <div class="flex flex-col items-center gap-4">
            <img 
              v-if="selectedPeerForQR" 
              :src="`/api/peers/${selectedPeerForQR.id}/qrcode`" 
              alt="Peer QR Code" 
              class="w-64 h-64 bg-white p-4 rounded-lg"
            />
            <p v-if="selectedPeerForQR" class="text-white/70 text-sm text-center">{{ selectedPeerForQR.name }}</p>
          </div>
          <div class="flex justify-end mt-6">
            <GlassButton @click="isQRCodeModalOpen = false" class="from-gray-500 to-gray-600">Close</GlassButton>
          </div>
        </DialogPanel>
      </TransitionChild>
    </TransitionRoot>
  </GlassCard>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { TransitionRoot, TransitionChild, Dialog, DialogPanel, DialogTitle } from '@headlessui/vue'
import GlassCard from './glass/GlassCard.vue'
import GlassInput from './glass/GlassInput.vue'
import GlassButton from './glass/GlassButton.vue'
import CIDRTagInput from './CIDRTagInput.vue'
import InternetToggle from './InternetToggle.vue'

interface Peer {
  id: string
  name: string
  publicKey: string
  ip: string
  allowedAccess: string[]
  allowInternet: boolean
  expiresAt?: string | null
  dataLimitGB?: number | null
  currentDataUsageBytes?: number | null
}

const props = defineProps<{
  serverId: string
}>()

const peers = ref<Peer[]>([
  {
    id: '1',
    name: 'Client 1',
    publicKey: 'xTIBA5rboUvnH3h2+JQ0qf0pI0n6KJ7g5Uc5gG0q0=',
    ip: '10.0.0.2/32',
    allowedAccess: ['192.168.1.0/24', '10.0.0.1/32'],
    allowInternet: true
  },
  {
    id: '2',
    name: 'Client 2',
    publicKey: 'yUIBA6scpVwoH4h3+KR1qf1qJ1o7KJ8h6Vd6hH1r1=',
    ip: '10.0.0.3/32',
    allowedAccess: [],
    allowInternet: false
  },
  {
    id: '3',
    name: 'Client 3',
    publicKey: 'zVJCB7tdqWxpI5h4+LS2rg2rK2p8LK9i7We7iI2s2=',
    ip: '10.0.0.4/32',
    allowedAccess: ['172.16.0.0/16'],
    allowInternet: true
  }
])

const isAddPeerModalOpen = ref(false)
const isQRCodeModalOpen = ref(false)
const isEditPeerModalOpen = ref(false)
const selectedPeerForQR = ref<Peer | null>(null)
const selectedPeerForEdit = ref<Peer | null>(null)
const newPeer = ref({
  publicKey: '',
  ip: '',
  allowedAccess: [] as string[],
  allowInternet: false,
  expiresAt: null as string | null,
  dataLimitGB: null as number | null
})

const formatBytes = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const openEditPeer = (peer: Peer) => {
  selectedPeerForEdit.value = { ...peer }
  isEditPeerModalOpen.value = true
}

const updatePeer = async () => {
  if (!selectedPeerForEdit.value) return
  try {
    const peer = selectedPeerForEdit.value
    const response = await fetch(`/api/peers/${peer.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        publicKey: peer.publicKey,
        ip: peer.ip,
        allowedAccess: peer.allowedAccess,
        allowInternet: peer.allowInternet,
        expiresAt: peer.expiresAt,
        dataLimitGB: peer.dataLimitGB
      })
    })
    if (!response.ok) throw new Error('Failed to update peer')
    const updatedPeer = await response.json()
    const index = peers.value.findIndex(p => p.id === updatedPeer.id)
    if (index !== -1) {
      peers.value[index] = updatedPeer
    }
    isEditPeerModalOpen.value = false
    selectedPeerForEdit.value = null
  } catch (error) {
    console.error('Update peer error:', error)
    alert('Failed to update peer. Check console for details.')
  }
}

const addPeer = async () => {
  try {
    const response = await fetch(`/api/servers/${props.serverId}/peers`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(newPeer.value)
    })
    if (!response.ok) throw new Error('Failed to add peer')
    const createdPeer = await response.json()
    peers.value.push({ ...createdPeer, name: `Client ${peers.value.length + 1}` })
    isAddPeerModalOpen.value = false
    newPeer.value = { publicKey: '', ip: '', allowedAccess: [], allowInternet: false, expiresAt: null, dataLimitGB: null }
  } catch (error) {
    console.error('Add peer error:', error)
    alert('Failed to add peer. Check console for details.')
  }
}

const deletePeer = async (id: string) => {
  if (!confirm('Are you sure you want to delete this peer?')) return
  try {
    const response = await fetch(`/api/peers/${id}`, { method: 'DELETE' })
    if (!response.ok) throw new Error('Failed to delete peer')
    peers.value = peers.value.filter(peer => peer.id !== id)
  } catch (error) {
    console.error('Delete peer error:', error)
    alert('Failed to delete peer. Check console for details.')
  }
}

const showQRCode = (peer: Peer) => {
  selectedPeerForQR.value = peer
  isQRCodeModalOpen.value = true
}

const downloadConfig = async (id: string) => {
  try {
    const response = await fetch(`/api/peers/${id}/config`)
    if (!response.ok) throw new Error('Failed to download config')
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `peer-${id}.conf`
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)
  } catch (error) {
    console.error('Download config error:', error)
    alert('Failed to download config. Check console for details.')
  }
}
</script>
