<script setup lang="ts">
/**
 * 文件职责：配送区域编辑抽屉。
 * 1. 展示区域字段编辑表单。
 * 2. 通过回调更新父级状态并提交。
 */
import type { PolygonZoneFormState } from '../types';

import { computed, ref } from 'vue';

import { Button, Drawer, Input, InputNumber } from 'ant-design-vue';

import { countPolygonsInGeoJson } from '../composables/delivery-page/geojson';
import DeliveryPolygonMapModal from './DeliveryPolygonMapModal.vue';

interface Props {
  colorPalette: string[];
  form: PolygonZoneFormState;
  onSetColor: (value: string) => void;
  onSetDeliveryFee: (value: number) => void;
  onSetEtaMinutes: (value: number) => void;
  onSetMinOrderAmount: (value: number) => void;
  onSetName: (value: string) => void;
  onSetPolygonGeoJson: (value: string) => void;
  onSetPriority: (value: number) => void;
  initialCenterAddress: string;
  initialCenterLatitude: null | number;
  initialCenterLongitude: null | number;
  fallbackCityText: string;
  open: boolean;
  title: string;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'submit'): void;
  (event: 'update:open', value: boolean): void;
}>();

function toNumber(value: null | number | string, fallback = 0) {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : fallback;
}

function readInputValue(event: Event) {
  const target = event.target as HTMLInputElement | null;
  return target?.value ?? '';
}

const isMapModalOpen = ref(false);

const polygonCount = computed(() =>
  countPolygonsInGeoJson(props.form.polygonGeoJson),
);

const formattedPolygonGeoJson = computed(() => {
  const raw = props.form.polygonGeoJson?.trim() ?? '';
  if (!raw) return '';

  try {
    return JSON.stringify(JSON.parse(raw), null, 2);
  } catch {
    return raw;
  }
});

function openMapModal() {
  isMapModalOpen.value = true;
}

function handleMapConfirm(geoJson: string) {
  props.onSetPolygonGeoJson(geoJson);
}
</script>

<template>
  <Drawer
    class="delivery-zone-drawer-wrap"
    :open="props.open"
    :title="props.title"
    :width="460"
    :z-index="4000"
    :mask-closable="true"
    @update:open="(value) => emit('update:open', value)"
  >
    <div class="drawer-form-block">
      <label class="drawer-form-label required">区域名称</label>
      <Input
        :value="props.form.name"
        :maxlength="20"
        show-count
        placeholder="例如：核心区域"
        @input="(event) => props.onSetName(readInputValue(event))"
      />
    </div>

    <div class="drawer-form-grid">
      <div class="drawer-form-block">
        <label class="drawer-form-label required">配送费</label>
        <div class="drawer-input-with-unit">
          <InputNumber
            :value="props.form.deliveryFee"
            :min="0"
            :precision="2"
            :step="1"
            :controls="false"
            class="drawer-input"
            @update:value="
              (value) =>
                props.onSetDeliveryFee(toNumber(value, props.form.deliveryFee))
            "
          />
          <span>元</span>
        </div>
      </div>

      <div class="drawer-form-block">
        <label class="drawer-form-label required">起送金额</label>
        <div class="drawer-input-with-unit">
          <InputNumber
            :value="props.form.minOrderAmount"
            :min="0"
            :precision="2"
            :step="1"
            :controls="false"
            class="drawer-input"
            @update:value="
              (value) =>
                props.onSetMinOrderAmount(
                  toNumber(value, props.form.minOrderAmount),
                )
            "
          />
          <span>元</span>
        </div>
      </div>

      <div class="drawer-form-block">
        <label class="drawer-form-label required">预计送达</label>
        <div class="drawer-input-with-unit">
          <InputNumber
            :value="props.form.etaMinutes"
            :min="1"
            :precision="0"
            :step="1"
            :controls="false"
            class="drawer-input"
            @update:value="
              (value) =>
                props.onSetEtaMinutes(toNumber(value, props.form.etaMinutes))
            "
          />
          <span>分钟</span>
        </div>
      </div>

      <div class="drawer-form-block">
        <label class="drawer-form-label required">优先级</label>
        <InputNumber
          :value="props.form.priority"
          :min="1"
          :precision="0"
          :step="1"
          :controls="false"
          class="drawer-input"
          @update:value="
            (value) => props.onSetPriority(toNumber(value, props.form.priority))
          "
        />
      </div>
    </div>

    <div class="drawer-form-block">
      <label class="drawer-form-label">区域颜色</label>
      <div class="color-palette">
        <button
          v-for="color in props.colorPalette"
          :key="color"
          type="button"
          class="color-dot"
          :class="{ active: props.form.color === color }"
          :style="{ background: color }"
          @click="props.onSetColor(color)"
        ></button>
      </div>
    </div>

    <div class="drawer-form-block">
      <label class="drawer-form-label required">区域范围</label>
      <div class="zone-map-actions">
        <Button type="primary" ghost @click="openMapModal">
          {{ polygonCount > 0 ? '重新绘制区域' : '绘制配送区域' }}
        </Button>
      </div>
      <div class="zone-map-summary">
        {{
          polygonCount > 0 ? `已绘制 ${polygonCount} 块区域` : '暂未绘制区域'
        }}
      </div>
      <div class="zone-geojson-preview">
        <Input.TextArea
          :value="formattedPolygonGeoJson"
          :auto-size="{ minRows: 7, maxRows: 11 }"
          readonly
          placeholder="绘制完成后，这里会显示格式化坐标 GeoJSON 数据"
        />
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <Button @click="emit('update:open', false)">取消</Button>
        <Button type="primary" @click="emit('submit')">
          {{ props.form.id ? '保存修改' : '新增并保存' }}
        </Button>
      </div>
    </template>
  </Drawer>

  <DeliveryPolygonMapModal
    v-model:open="isMapModalOpen"
    :initial-geo-json="props.form.polygonGeoJson"
    :initial-center-latitude="props.initialCenterLatitude"
    :initial-center-longitude="props.initialCenterLongitude"
    :initial-center-address="props.initialCenterAddress"
    :fallback-city-text="props.fallbackCityText"
    :zone-color="props.form.color"
    @confirm="handleMapConfirm"
  />
</template>
