<template>
  <div class="border border-gray-200 rounded-lg mb-4">
    <div class="p-4 flex items-center justify-between">
      <div class="flex items-center">
        <svg class="w-4 h-4 mr-3 text-gray-400 cursor-move handle" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
          <path stroke-linecap="round" stroke-linejoin="round" d="M3 7.5 7.5 3m0 0L12 7.5M7.5 3v13.5m13.5 0L16.5 21m0 0L12 16.5m4.5 4.5V7.5"></path>
        </svg>

        <div class="font-medium text-md text-gray-800 leading-tight cursor-pointer" @click.prevent="componentCollapsed = !componentCollapsed">
          {{ name }}
        </div>
      </div>


      <div class="space-x-2">
        <button @click.prevent="componentCollapsed = !componentCollapsed" :class="{ '-rotate-90': componentCollapsed }" class="transform p-2 bg-gray-200 rounded-full hover:bg-sky-500 hover:text-white transition">
          <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5"></path>
          </svg>
        </button>

        <button @click.prevent="$emit('deleteComponent', component)" class="p-2 bg-gray-200 rounded-full hover:bg-red-500 hover:text-white transition">
          <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor"
               viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"></path>
          </svg>
        </button>
      </div>
    </div>

    <div v-show="!componentCollapsed" class="px-4 pb-4 space-y-4 divide-y">
      <FieldRenderer
          v-for="field in fields"
          :field="field"
          v-model="component.data[field.name]"
      />
    </div>
  </div>
</template>

<script setup>
import {computed, ref} from "vue";
import FieldRenderer from "./FieldRenderer.vue";

const props = defineProps({
  component: {
    type: Object,
    required: true,
  },
  availableComponents: {
    type: Array,
    default: () => []
  }
})

defineEmits(['deleteComponent'])

const name = computed(() => {
  return props.availableComponents.find(component => component.type === props.component.type).name
})

const fields = computed(() => {
  return props.availableComponents.find(component => component.type === props.component.type).fields
})

const componentCollapsed = ref(false)
</script>