<template>
  <view class="region-selector" @tap="openSelector">
    <text v-if="displayText" class="region-text">{{ displayText }}</text>
    <text v-else class="region-placeholder">{{ placeholder }}</text>
    <u-icon name="arrow-down" :size="20" color="#999" />
  </view>

  <!-- 遮罩层 -->
  <view v-if="visible" class="mask" @tap="closeSelector"></view>

  <!-- 底部弹窗 -->
  <view :class="['popup-panel', { show: visible }]">
    <view class="panel-header">
      <text class="panel-title">选择地区</text>
      <view class="panel-close" @tap="closeSelector">
        <u-icon name="close" :size="32" color="#999" />
      </view>
    </view>
    <view class="panel-tabs">
      <view
        v-for="(tab, index) in tabs"
        :key="index"
        :class="['tab-item', { active: activeTab === index }]"
        @tap="switchTab(index)"
      >
        <text class="tab-text">{{ tab.label }}</text>
        <view v-if="activeTab === index" class="tab-line"></view>
      </view>
    </view>
    <scroll-view class="panel-content" scroll-y>
      <view class="list-wrapper">
        <view
          v-for="item in currentList"
          :key="item.code"
          :class="['list-item', { selected: isItemSelected(item) }]"
          @tap="selectItem(item)"
        >
          <text class="item-name">{{ item.name }}</text>
          <u-icon v-if="isItemSelected(item)" name="checkmark" :size="28" color="#667eea" />
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { regionData } from '@/data/region';

interface RegionItem {
  code: string;
  name: string;
}

const props = withDefaults(
  defineProps<{
    province?: string;
    city?: string;
    district?: string;
    placeholder?: string;
  }>(),
  {
    province: '',
    city: '',
    district: '',
    placeholder: '请选择省/市/区',
  }
);

const emit = defineEmits<{
  (e: 'change', value: { province: string; city: string; district: string }): void;
}>();

const visible = ref(false);
const activeTab = ref(0);

const selectedProvince = ref<RegionItem | null>(null);
const selectedCity = ref<RegionItem | null>(null);
const selectedDistrict = ref<RegionItem | null>(null);

const tabs = computed(() => [
  { label: selectedProvince.value?.name || '省' },
  { label: selectedCity.value?.name || '市' },
  { label: selectedDistrict.value?.name || '区' },
]);

const displayText = computed(() => {
  const parts: string[] = [];
  if (selectedProvince.value) parts.push(selectedProvince.value.name);
  if (selectedCity.value) parts.push(selectedCity.value.name);
  if (selectedDistrict.value) parts.push(selectedDistrict.value.name);
  return parts.join(' ');
});

const currentList = computed(() => {
  if (activeTab.value === 0) {
    return regionData.provinces;
  } else if (activeTab.value === 1) {
    if (!selectedProvince.value) return [];
    return regionData.cities[selectedProvince.value.code] || [];
  } else {
    if (!selectedCity.value) return [];
    return regionData.districts[selectedCity.value.code] || [];
  }
});

function isItemSelected(item: RegionItem): boolean {
  if (activeTab.value === 0) return selectedProvince.value?.code === item.code;
  if (activeTab.value === 1) return selectedCity.value?.code === item.code;
  return selectedDistrict.value?.code === item.code;
}

function openSelector() {
  activeTab.value = 0;
  visible.value = true;
}

function closeSelector() {
  visible.value = false;
}

function switchTab(index: number) {
  if (index === 0) {
    activeTab.value = 0;
  } else if (index === 1 && selectedProvince.value) {
    activeTab.value = 1;
  } else if (index === 2 && selectedCity.value) {
    activeTab.value = 2;
  }
}

function selectItem(item: RegionItem) {
  if (activeTab.value === 0) {
    selectedProvince.value = item;
    selectedCity.value = null;
    selectedDistrict.value = null;
    activeTab.value = 1;
  } else if (activeTab.value === 1) {
    selectedCity.value = item;
    selectedDistrict.value = null;
    activeTab.value = 2;
  } else {
    selectedDistrict.value = item;
    emitChange();
    closeSelector();
  }
}

function emitChange() {
  emit('change', {
    province: selectedProvince.value?.name || '',
    city: selectedCity.value?.name || '',
    district: selectedDistrict.value?.name || '',
  });
}

watch(
  () => [props.province, props.city, props.district],
  () => {
    if (props.province) {
      const province = regionData.provinces.find((p) => p.name === props.province);
      if (province) {
        selectedProvince.value = province;
        if (props.city) {
          const cities = regionData.cities[province.code] || [];
          const city = cities.find((c) => c.name === props.city);
          if (city) {
            selectedCity.value = city;
            if (props.district) {
              const districts = regionData.districts[city.code] || [];
              const district = districts.find((d) => d.name === props.district);
              if (district) {
                selectedDistrict.value = district;
              }
            }
          }
        }
      }
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.region-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  background: #f5f5f5;
  border-radius: 12rpx;
  padding: 0 24rpx;
  cursor: pointer;
}

.region-text {
  flex: 1;
  font-size: 30rpx;
  color: #333;
}

.region-placeholder {
  flex: 1;
  font-size: 30rpx;
  color: #999;
}

/* 遮罩 */
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

/* 底部弹窗 */
.popup-panel {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  max-height: 70vh;
  padding-bottom: env(safe-area-inset-bottom);
  transform: translateY(100%);
  transition: transform 0.3s ease;

  &.show {
    transform: translateY(0);
  }
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 32rpx;
  border-bottom: 1rpx solid #eee;
}

.panel-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.panel-close {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8rpx;
}

.panel-tabs {
  display: flex;
  padding: 0 32rpx;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  padding: 20rpx 24rpx;
  position: relative;
}

.tab-text {
  font-size: 28rpx;
  color: #666;
}

.tab-item.active .tab-text {
  color: #667eea;
  font-weight: 600;
}

.tab-line {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background: #667eea;
  border-radius: 2rpx;
}

.panel-content {
  height: 400rpx;
}

.list-wrapper {
  min-height: 400rpx;
}

.list-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f5f5f5;

  &.selected {
    background: rgba(102, 126, 234, 0.05);
  }
}

.item-name {
  font-size: 30rpx;
  color: #333;
}

.list-item.selected .item-name {
  color: #667eea;
  font-weight: 600;
}
</style>
