<script lang="ts" setup>
import { onUnmounted, ref, watch } from 'vue';

import ColorPicker from '#/components/form/components/color-picker.vue';

const props = defineProps<{
  open: boolean;
  x: number;
  y: number;
  col: number;
  color: string;
}>();

const emit = defineEmits<{
  'update:color': [value: string];
  apply: [col: number, color: string | undefined];
  close: [];
}>();

const draftColor = ref(props.color);

watch(
  () => props.color,
  (v) => {
    draftColor.value = v;
  },
);

watch(
  () => props.open,
  (open) => {
    if (open) {
      draftColor.value = props.color;
      document.addEventListener('keydown', onKeyDown);
      document.addEventListener('pointerdown', onPointerDown, true);
    } else {
      removeListeners();
    }
  },
);

function removeListeners() {
  document.removeEventListener('keydown', onKeyDown);
  document.removeEventListener('pointerdown', onPointerDown, true);
}

function onKeyDown(e: KeyboardEvent) {
  if (e.key === 'Escape') {
    emit('close');
  }
}

function onPointerDown(e: PointerEvent) {
  const target = e.target as Node | null;
  const panel = panelRef.value;
  if (panel && target && !panel.contains(target)) {
    emit('close');
  }
}

const panelRef = ref<HTMLElement | null>(null);

function onColorUpdate(value: string) {
  draftColor.value = value;
  emit('update:color', value);
  emit('apply', props.col, value || undefined);
}

onUnmounted(removeListeners);
</script>

<template>
  <Teleport to="body">
    <div
      v-if="open"
      ref="panelRef"
      class="header-color-picker-popover"
      :style="{ left: `${x}px`, top: `${y}px` }"
      @contextmenu.prevent
    >
      <div class="popover-title">表头颜色</div>
      <ColorPicker
        :value="draftColor"
        placeholder="选择颜色"
        @update:value="onColorUpdate"
      />
    </div>
  </Teleport>
</template>

<style scoped lang="scss">
.header-color-picker-popover {
  position: fixed;
  z-index: 10000;
  padding: 12px;
  background: #fff;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.popover-title {
  font-size: 13px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #1d2129;
}

.is-dark .header-color-picker-popover {
  background: #1f1f1f;
  border-color: #424242;

  .popover-title {
    color: rgba(255, 255, 255, 0.85);
  }
}
</style>
