<template>
  <div>
    <!-- Power Flow -->
    <h4 :class="headingClass">Power Flow</h4>
    <div :class="rowClass"><label :class="labelClass">Titel</label><input :class="inputClass" type="text" v-model="widget.text"></div>
    <div :class="rowClass">
      <label :class="labelClass">Knoten</label>
      <span class="text-[12px] text-muted">{{ powerNodeCount }}</span>
      <button class="ml-auto border border-border bg-panel-2 px-2.5 py-1.5 rounded-lg text-[11px] font-semibold hover:bg-[#e4ebf2]" @click="addPowerNode">+ Node</button>
    </div>
    <div :class="rowClass">
      <label :class="labelClass">Verbindungen</label>
      <button class="border border-border bg-panel-2 px-2.5 py-1.5 rounded-lg text-[11px] font-semibold hover:bg-[#e4ebf2]" @click="togglePowerLinkMode">
        {{ isLinkModeActive ? 'Modus: aktiv' : 'Modus: aus' }}
      </button>
      <button v-if="isLinkModeActive && linkSourceLabel" class="ml-auto border border-border bg-panel-2 px-2.5 py-1.5 rounded-lg text-[11px] hover:bg-[#e4ebf2]" @click="clearPowerLinkSource">Quelle loeschen</button>
    </div>
    <div class="text-[11px] text-muted mb-2">{{ linkModeHint }}</div>
    <div v-if="powerFlowLinkItems.length" class="mt-2">
      <div v-for="link in powerFlowLinkItems" :key="link.id" class="border border-border rounded-lg px-2.5 py-2 mb-2 bg-panel-2">
        <div class="flex items-center gap-2 mb-2 text-[11px] text-muted">
          <span class="px-1.5 py-0.5 rounded-md bg-white border border-border text-text max-w-[90px] truncate">{{ link.fromLabel }}</span>
          <span>-&gt;</span>
          <span class="px-1.5 py-0.5 rounded-md bg-white border border-border text-text max-w-[90px] truncate">{{ link.toLabel }}</span>
          <button class="ml-auto w-6 h-6 rounded-md border border-red-200 bg-[#f7dede] text-[#b3261e] grid place-items-center text-[11px] cursor-pointer hover:bg-[#f2cfcf]" @click="removePowerLink(link.id)">x</button>
        </div>
        <div class="flex items-center gap-2 mb-2 text-[11px] text-muted">
          <label class="w-[70px] text-[11px] text-muted">Linie</label>
          <input class="h-[22px] w-[32px] cursor-pointer border-0 bg-transparent p-0" type="color" v-model="link.widget.bgColor">
          <input class="w-[70px] bg-white border border-border rounded-md px-2 py-1 text-[11px]" type="number" min="1" max="12" v-model.number="link.widget.w">
          <span class="text-[10px] text-muted">px</span>
        </div>
        <div class="flex items-center gap-2 mb-2 text-[11px] text-muted">
          <label class="w-[70px] text-[11px] text-muted">Speed</label>
          <select class="flex-1 bg-white border border-border rounded-md px-2 py-1 text-[11px]" v-model.number="link.widget.textSrc">
            <optgroup v-for="group in groupedSources(sourceOptions.powerlink)" :key="group.label" :label="group.label">
              <option v-for="opt in group.values" :key="opt" :value="opt">{{ textSources[opt] }}</option>
            </optgroup>
          </select>
        </div>
        <div v-if="link.widget.textSrc === 0" class="flex items-center gap-2 mb-2 text-[11px] text-muted">
          <label class="w-[70px] text-[11px] text-muted">Wert</label>
          <input class="flex-1 bg-white border border-border rounded-md px-2 py-1 text-[11px]" type="text" inputmode="decimal" v-model="link.widget.text" placeholder="z.B. 60">
        </div>
        <div v-else class="flex flex-col gap-2 text-[11px] text-muted">
          <div class="flex items-center gap-2">
            <label class="w-[70px] text-[11px] text-muted">Faktor</label>
            <input class="flex-1 bg-white border border-border rounded-md px-2 py-1 text-[11px]" type="text" inputmode="decimal" v-model="link.widget.text" placeholder="z.B. 0.2">
          </div>
          <div class="flex items-center gap-2">
            <label class="w-[70px] text-[11px] text-muted">KNX</label>
            <select class="flex-1 bg-white border border-border rounded-md px-2 py-1 text-[11px]" v-model.number="link.widget.knxAddr">
              <option :value="0">-- Waehlen --</option>
              <option v-for="addr in store.knxAddresses" :key="`${addr.addr}-${addr.index}`" :value="addr.addr">
                GA {{ addr.addrStr }} (GO{{ addr.index }})
              </option>
            </select>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="text-[11px] text-muted">Keine Verbindungen.</div>

    <!-- Style -->
    <h4 :class="headingClass">Stil</h4>
    <div :class="rowClass"><label :class="labelClass">Textfarbe</label><input :class="colorInputClass" type="color" v-model="widget.textColor"></div>
    <div :class="rowClass"><label :class="labelClass">Hintergrund</label><input :class="colorInputClass" type="color" v-model="widget.bgColor"></div>
    <div :class="rowClass"><label :class="labelClass">Deckkraft</label><input :class="inputClass" type="number" min="0" max="255" v-model.number="widget.bgOpacity"></div>
    <div :class="rowClass"><label :class="labelClass">Radius</label><input :class="inputClass" type="number" v-model.number="widget.radius"></div>
    <h4 :class="headingClass">Rand</h4>
    <div :class="rowClass"><label :class="labelClass">Breite</label><input :class="inputClass" type="number" min="0" max="32" v-model.number="widget.borderWidth"></div>
    <div :class="rowClass"><label :class="labelClass">Farbe</label><input :class="colorInputClass" type="color" v-model="widget.borderColor"></div>
    <div :class="rowClass"><label :class="labelClass">Deckkraft</label><input :class="inputClass" type="number" min="0" max="255" v-model.number="widget.borderOpacity"></div>

    <!-- Shadow -->
    <h4 :class="headingClass">Schatten</h4>
    <div :class="rowClass"><label :class="labelClass">Aktiv</label><input class="accent-[var(--accent)]" type="checkbox" v-model="widget.shadow.enabled"></div>
    <div :class="rowClass"><label :class="labelClass">X</label><input :class="inputClass" type="number" v-model.number="widget.shadow.x"></div>
    <div :class="rowClass"><label :class="labelClass">Y</label><input :class="inputClass" type="number" v-model.number="widget.shadow.y"></div>
    <div :class="rowClass"><label :class="labelClass">Blur</label><input :class="inputClass" type="number" v-model.number="widget.shadow.blur"></div>
    <div :class="rowClass"><label :class="labelClass">Farbe</label><input :class="colorInputClass" type="color" v-model="widget.shadow.color"></div>
  </div>
</template>

<script setup>
import { computed } from 'vue';
import { useEditorStore } from '../../../stores/editor';
import { sourceOptions, textSources, textSourceGroups, WIDGET_TYPES } from '../../../constants';
import { rowClass, labelClass, inputClass, headingClass, colorInputClass } from '../shared/styles';

const props = defineProps({
  widget: { type: Object, required: true }
});

const store = useEditorStore();

const powerNodeCount = computed(() => {
  if (!props.widget || props.widget.type !== WIDGET_TYPES.POWERFLOW || !store.activeScreen) return 0;
  return store.activeScreen.widgets.filter((child) => child.parentId === props.widget.id && child.type === WIDGET_TYPES.POWERNODE).length;
});

const powerFlowLinkItems = computed(() => {
  if (!props.widget || props.widget.type !== WIDGET_TYPES.POWERFLOW || !store.activeScreen) return [];
  const nodes = store.activeScreen.widgets.filter((child) => child.parentId === props.widget.id && child.type === WIDGET_TYPES.POWERNODE);
  const nodeMap = new Map(nodes.map((node) => [node.id, node]));

  return store.activeScreen.widgets
    .filter((child) => child.parentId === props.widget.id && child.type === WIDGET_TYPES.POWERLINK)
    .map((link) => {
      const fromNode = nodeMap.get(link.x);
      const toNode = nodeMap.get(link.y);
      return {
        id: link.id,
        widget: link,
        fromLabel: getPowerNodeLabel(fromNode, link.x),
        toLabel: getPowerNodeLabel(toNode, link.y)
      };
    });
});

const isLinkModeActive = computed(() => {
  return store.powerLinkMode.active && store.powerLinkMode.powerflowId === props.widget?.id;
});

const linkSourceLabel = computed(() => {
  if (!isLinkModeActive.value || !store.activeScreen || !store.powerLinkMode.fromNodeId) return '';
  const node = store.activeScreen.widgets.find((child) => child.id === store.powerLinkMode.fromNodeId);
  return getPowerNodeLabel(node, store.powerLinkMode.fromNodeId);
});

const linkModeHint = computed(() => {
  if (!isLinkModeActive.value) return 'Aktiviere den Modus und klicke zwei Knoten, um eine Verbindung zu erstellen.';
  if (!linkSourceLabel.value) return 'Klicke den Startknoten.';
  return `Quelle: ${linkSourceLabel.value} - jetzt Zielknoten waehlen.`;
});

function groupedSources(options) {
  const allowed = new Set(options || []);
  return textSourceGroups
    .map((group) => ({
      label: group.label,
      values: group.values.filter((value) => allowed.has(value))
    }))
    .filter((group) => group.values.length > 0);
}

function addPowerNode() {
  store.addWidget('powernode');
}

function togglePowerLinkMode() {
  if (!props.widget || props.widget.type !== WIDGET_TYPES.POWERFLOW) return;
  const nextState = !(store.powerLinkMode.active && store.powerLinkMode.powerflowId === props.widget.id);
  store.setPowerLinkMode(nextState, props.widget.id);
}

function clearPowerLinkSource() {
  if (!props.widget || props.widget.type !== WIDGET_TYPES.POWERFLOW) return;
  store.powerLinkMode.fromNodeId = null;
}

function removePowerLink(linkId) {
  store.removePowerLink(linkId);
}

function splitPowerNodeText(text) {
  if (typeof text !== 'string') return { label: '', value: '' };
  const parts = text.split('\n');
  const label = parts[0] ?? '';
  const value = parts.slice(1).join('\n');
  return { label, value };
}

function getPowerNodeLabel(node, fallbackId) {
  if (!node) return `Node ${fallbackId ?? ''}`.trim();
  const parts = splitPowerNodeText(node.text);
  return parts.label || `Node ${node.id}`;
}
</script>
