<template>
    <div class="testing">
        <h1>Testing</h1>

        <h3>Items</h3>
        <ul>
            <li v-for="item in items" :key="item.id">
                <span>{{ item.text }}</span>

                <btn @click="deleteItem(item.id)">Delete</btn>
            </li>
        </ul>

        <label>
            <span>Add Item: </span>
            <input type="text" v-model="newItem" />
            <btn @click="addItem">Add</btn>
        </label>

        <btn @click="sendMessage">Send Message</btn>
    </div>
</template>

<script setup>
import Btn from '@shared/Btn.vue'
import { onMounted, onUnmounted, ref } from 'vue';

const items = ref([])
const newItem = ref('')
const ws = ref(null)
const isConnected = ref(false)

onMounted(async () => {
  await getItems()

  // WebSocket connection
  ws.value = new WebSocket('ws://localhost:3001/ws/testing')

  ws.value.onopen = () => {
    console.log('Connected to WebSocket')
    isConnected.value = true
  }

  ws.value.onmessage = (event) => {
    const data = JSON.parse(event.data)

    switch (data.type) {
      case 'connected':
        console.log(data.message)
        break
      case 'echo':
        console.log('Echo received')
        console.log(data)
        break
    }
  }
  ws.value.onclose = () => {
    console.log('Disconnected from WebSocket')
    isConnected.value = false
  }
  ws.value.onerror = (error) => {
    console.error('WebSocket error:', error)
  }
})

const getItems = async () => {
  const response = await fetch('http://localhost:3001/api/testing/items')
  const data = await response.json()
  items.value = data.items
}
const addItem = async () => {
    try {
        const response = await fetch('http://localhost:3001/api/testing/items', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ text: newItem.value }),
        })

        if (!response.ok) {
            throw new Error('Failed to add item')
        }

        await getItems()
        newItem.value = ''
    } catch (error) {
        console.error(error)
    }
}
const deleteItem = async (id) => {
  try {
      const response = await fetch(`http://localhost:3001/api/testing/items/${id}`, {
          method: 'DELETE'
      })

      if (!response.ok) {
          throw new Error('Failed to delete item')
      }

      await getItems()
  } catch (error) {
      console.error(error)
  }
}
const sendMessage = () => {
    if (ws.value && isConnected.value) {
      ws.value.send(JSON.stringify({
        type: 'test',
        message: {
          text: 'test'
        }
      }))
    }
}

onUnmounted(() => {
  if (ws.value) {
    ws.value.close()
  }
})
</script>

<style lang="scss">
.testing {
    height: 100%;
}
</style>
