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

import { $t } from '@vben/locales';

import type { ReportDatasetItem } from '#/api/online-dev/report-manager';

import ChartBindForm, {
  type ChartBindFormState,
} from './chart-bind-form.vue';
import { parseChartOptionToFormState } from './chart-bind-utils';

export interface CellChartSelection {
  startRow: number;
  startColumn: number;
  sheetId?: string;
  cellData?: Record<string, any>;
}

const props = defineProps<{
  selection: CellChartSelection | null;
  datasets: ReportDatasetItem[];
}>();

const emit = defineEmits<{
  apply: [payload: {
    startRow: number;
    startColumn: number;
    echartType: string;
    option: Record<string, any>;
    preserveCustom: Record<string, any>;
  }];
}>();

const bindFormRef = ref<InstanceType<typeof ChartBindForm> | null>(null);
const formState = ref<ChartBindFormState | null>(null);

const positionLabel = computed(() => {
  if (!props.selection) return '';
  return $t('report-manager.properties.position', {
    row: props.selection.startRow + 1,
    col: props.selection.startColumn + 1,
  });
});

function customToFormState(
  custom: Record<string, any>,
  datasets: ReportDatasetItem[],
): ChartBindFormState {
  const { chartType, drawingId, height, width, type, ...restOption } = custom;
  return parseChartOptionToFormState(
    custom.chartType || 'bar',
    restOption,
    datasets,
  );
}

watch(
  () => props.selection,
  (sel) => {
    if (!sel) {
      formState.value = null;
      return;
    }
    formState.value = customToFormState(
      sel.cellData?.custom || {},
      props.datasets || [],
    );
  },
  { deep: true },
);

function onFormChange() {
  if (!props.selection) return;
  const custom = props.selection.cellData?.custom || {};
  const { chartType, drawingId, height, width, type, ...restOption } = custom;
  const option = bindFormRef.value?.buildOption(restOption) || {};
  emit('apply', {
    startRow: props.selection.startRow,
    startColumn: props.selection.startColumn,
    echartType: formState.value?.echartType || custom.chartType || 'bar',
    option,
    preserveCustom: {
      drawingId,
      height,
      width,
      type: 'chart',
    },
  });
}
</script>

<template>
  <div v-if="!selection" class="text-xs text-[var(--el-text-color-secondary)]">
    {{ $t('report-manager.chart.cellEmpty') }}
  </div>
  <div v-else>
    <p class="mb-2 text-xs text-[var(--el-text-color-secondary)]">
      {{ positionLabel }}
    </p>
    <p class="mb-2 text-xs font-medium">
      {{ $t('report-manager.chart.cellTitle') }}
    </p>
    <ChartBindForm
      ref="bindFormRef"
      :datasets="datasets"
      :model-value="formState"
      @change="onFormChange"
    />
  </div>
</template>
