<template>
  <div class="menu-management">
    <h1>Menüverwaltung</h1>
    <div class="button-container">
      <button @click="addMenuItem">Hauptmenü hinzufügen</button>
      <button @click="saveMenuData">Speichern</button>
    </div>
    <div v-if="selectedMenuItem" class="edit-form">
      <h2>{{ isEditMode ? 'Menüpunkt bearbeiten' : 'Menüpunkt erstellen' }}</h2>
      <form @submit.prevent="saveMenuData">
        <label for="name">Name</label>
        <input id="name" v-model="selectedMenuItem.name" placeholder="Name" />

        <label for="link">Link</label>
        <input id="link" v-model="selectedMenuItem.link" placeholder="Link" />

        <label for="page-title">Seitenname</label>
        <input id="page-title" v-model="selectedMenuItem.pageTitle" placeholder="Seitenname" />

        <label for="order-id">Order ID</label>
        <input id="order-id" v-model.number="selectedMenuItem.order_id" placeholder="Order ID" type="number" class="order-id" />

        <div class="checkbox-container">
          <label>
            <input type="checkbox" v-model="selectedMenuItem.showInMenu" />
            Im Menü anzeigen
          </label>
          <label>
            <input type="checkbox" v-model="selectedMenuItem.requiresAuth" />
            Authentifizierung erforderlich
          </label>
        </div>

        <label for="parent-id">Elternelement</label>
        <select id="parent-id" v-model.number="selectedMenuItem.parent_id">
          <option value="-1">Ohne Elternelement</option>
          <option v-for="item in flattenedMenuData" :key="item.id" :value="item.id">
            {{ getIndentedName(item) }}
          </option>
        </select>

        <label for="component">Vue-Komponente</label>
        <input id="component" v-model="selectedMenuItem.component" placeholder="Vue-Komponente" />
        
        <button type="button" @click="resetForm">Neuen Menüpunkt erstellen</button>
        <button type="submit">Speichern</button>
      </form>
    </div>
    <div class="tree-view">
      <ul>
        <li v-for="menuItem in sortedMenuData" :key="menuItem.id">
          <div class="menu-item">
            <span @click="selectMenuItem(menuItem)">
              {{ menuItem.name }} (ID: {{ menuItem.order_id }})
            </span>
            <div class="action-buttons">
              <button @click="addSubmenu(menuItem)" class="action-button">Untermenü hinzufügen</button>
              <button @click="removeMenuItem(menuItem)" class="action-button">Löschen</button>
            </div>
          </div>
          <ul v-if="menuItem.submenu.length">
            <li v-for="submenuItem in sortedSubmenu(menuItem)" :key="submenuItem.id">
              <div class="menu-item">
                <span @click="selectMenuItem(submenuItem)">
                  {{ submenuItem.name }} (ID: {{ submenuItem.order_id }})
                </span>
                <div class="action-buttons">
                  <button @click="addSubmenu(submenuItem)" class="action-button">Untermenü hinzufügen</button>
                  <button @click="removeSubmenu(menuItem, submenuItem)" class="action-button">Löschen</button>
                </div>
              </div>
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import axios from '../../axios';
import { useStore } from 'vuex';

export default {
  name: 'MenuManagement',
  setup() {
    const store = useStore();
    const menuData = ref([]);
    const selectedMenuItem = ref(null);
    const isEditMode = ref(false);

    const fetchMenuData = async () => {
      try {
        const response = await axios.get('/menu-data');
        menuData.value = response.data;
      } catch (error) {
        console.error('Fehler beim Abrufen der Menü-Daten:', error);
      }
    };

    const saveMenuData = async () => {
      try {
        const flatMenuData = flattenMenuData(menuData.value);
        await axios.post('/menu-data', flatMenuData);
        alert('Menü-Daten erfolgreich gespeichert');
      } catch (error) {
        console.error('Fehler beim Speichern der Menü-Daten:', error);
      }
    };

    const flattenMenuData = (data) => {
      return data.reduce((acc, item) => {
        const newItem = {
          ...item,
          page_title: item.pageTitle,
          show_in_menu: item.showInMenu,
          requires_auth: item.requiresAuth,
        };
        const { submenu, ...rest } = newItem;
        acc.push(rest);
        if (submenu && submenu.length) {
          acc.push(...flattenMenuData(submenu, newItem.id));
        }
        return acc;
      }, []);
    };

    const flattenMenuStructure = (menuItems, indent = 0) => {
      return menuItems.reduce((acc, item) => {
        acc.push({ ...item, indent });
        if (item.submenu && item.submenu.length) {
          acc.push(...flattenMenuStructure(item.submenu, item.id, indent + 1));
        }
        console.log
        return acc;
      }, []);
    };

    const addMenuItem = () => {
      const newItem = {
        name: '',
        link: '',
        component: '',
        pageTitle: '',
        showInMenu: true,
        requiresAuth: false,
        order_id: 0,
        submenu: [],
        parent_id: 0,
      };
      menuData.value.push(newItem);
      selectMenuItem(newItem);
      isEditMode.value = false;
    };

    const addSubmenu = (menuItem) => {
      const newSubItem = {
        name: '',
        link: '',
        component: '',
        pageTitle: '',
        showInMenu: true,
        requiresAuth: false,
        order_id: 0,
      };
      menuItem.submenu.push(newSubItem);
      selectMenuItem(newSubItem);
      isEditMode.value = false;
    };

    const removeMenuItem = (menuItem) => {
      const index = menuData.value.indexOf(menuItem);
      if (index > -1) {
        menuData.value.splice(index, 1);
      }
      selectedMenuItem.value = null;
    };

    const removeSubmenu = (menuItem, submenuItem) => {
      const index = menuItem.submenu.indexOf(submenuItem);
      if (index > -1) {
        menuItem.submenu.splice(index, 1);
      }
      selectedMenuItem.value = null;
    };

    const selectMenuItem = (menuItem) => {
      selectedMenuItem.value = menuItem;
      isEditMode.value = true;
    };

    const resetForm = () => {
      selectedMenuItem.value = null;
      isEditMode.value = false;
    };

    const sortedMenuData = computed(() => {
      return [...menuData.value].sort((a, b) => a.order_id - b.order_id);
    });

    const sortedSubmenu = (menuItem) => {
      return menuItem.submenu.slice().sort((a, b) => a.order_id - b.order_id);
    };

    const getIndentedName = (item) => {
      return '\u00A0'.repeat(item.indent * 2) + item.name;
    };

    const flattenedMenuData = computed(() => {
      const menuStruct =  flattenMenuStructure(store.state.menuData);
      console.log(menuStruct);
      return menuStruct;
    });

    onMounted(() => {
      fetchMenuData();
    });

    return {
      menuData,
      sortedMenuData,
      sortedSubmenu,
      selectedMenuItem,
      fetchMenuData,
      saveMenuData,
      addMenuItem,
      addSubmenu,
      removeMenuItem,
      removeSubmenu,
      selectMenuItem,
      getIndentedName,
      isEditMode,
      resetForm,
      flattenedMenuData,
    };
  },
};
</script>

<style scoped>
.menu-management {
  width: 100%;
  margin: auto;
}

.button-container {
  display: inline-flex;
  gap: 10px;
  margin-bottom: 20px;
}

.tree-view {
  margin-top: 20px;
}

.tree-view ul {
  list-style-type: none;
  padding: 0;
}

.tree-view li {
  margin-bottom: 5px;
  padding-left: 20px;
}

.tree-view .menu-item {
  display: inline-flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
}

.tree-view span {
  cursor: pointer;
  color: black;
}

.tree-view button {
  border: none;
  height: 1.6em;
  padding: 0 0.5em;
  margin: 1px;
  border-radius: 5px;
}

.tree-view span:hover {
  text-decoration: underline;
}

.edit-form {
  margin-top: 20px;
}

.edit-form label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.edit-form input:not([type="checkbox"]) {
  display: block;
  margin-bottom: 10px;
}

.edit-form .checkbox-container {
  display: flex;
  flex-direction: column;
  margin-right: 10px;
}

.edit-form .order-id {
  width: 50px;
}

.edit-form button {
  margin-top: 5px;
}
</style>
