<template>
  <div
    v-if="popupVisible"
    class="region-select-overlay"
    @click.self="handleClose"
  >
    <div class="region-select-popup">
      <div class="popup-header">
        <h3 class="popup-title">选择收益区域</h3>
      </div>
      <div class="popup-content">
        <div class="picker-columns">
          <div class="picker-column">
            <ul>
              <li
                v-for="p in provinces"
                :key="p.id"
                @click="selectProvince(p)"
                :class="{
                  selected: selectedProvince && selectedProvince.id === p.id,
                }"
              >
                {{ p.name }}
              </li>
            </ul>
          </div>
          <div class="picker-column">
            <ul>
              <li
                v-for="c in cities"
                :key="c.id"
                @click="selectCity(c)"
                :class="{ selected: selectedCity && selectedCity.id === c.id }"
              >
                {{ c.name }}
              </li>
            </ul>
          </div>
          <div class="picker-column">
            <ul>
              <li
                v-for="d in districts"
                :key="d.id"
                @click="selectDistrict(d)"
                :class="{
                  selected: selectedDistrict && selectedDistrict.id === d.id,
                }"
              >
                {{ d.name }}
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="popup-footer">
        <button class="popup-btn popup-cancel" @click="handleClose">
          取消
        </button>
        <button class="popup-btn popup-confirm" @click="handleConfirm">
          确认
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { getRegionSelect, setRegion, getRegionAreaTree } from '@/config/mine.js'

export default {
  name: 'region-select',
  data() {
    return {
      popupVisible: false,
      areaTree: [],
      provinces: [],
      cities: [],
      districts: [],
      selectedProvince: null,
      selectedCity: null,
      selectedDistrict: null,
    }
  },
  async created() {
    try {
      const res = await getRegionSelect()
      // Assuming res.data exists and has regionStatus and provinceId
      if (
        res.code === 200 &&
        res.data &&
        res.data.regionStatus === 0 &&
        !res.data.province
      ) {
        await this.loadAreaTree()
        this.popupVisible = true
      }
    } catch (error) {
      console.error('Failed to get region select info:', error)
      // Optionally show a user-facing error message, e.g., using a toast library
    }
  },
  methods: {
    async loadAreaTree() {
      try {
        const res = await getRegionAreaTree()
        if (res.code === 200 && res.data) {
          this.areaTree = res.data
          this.provinces = this.areaTree
          if (this.provinces.length > 0) {
            this.selectProvince(this.provinces[0])
          }
        }
      } catch (error) {
        console.error('Failed to load area tree:', error)
      }
    },
    selectProvince(province) {
      this.selectedProvince = province
      this.cities = province.children || []
      this.selectedCity = null
      this.districts = []
      if (this.cities.length > 0) {
        this.selectCity(this.cities[0])
      } else {
        // Handle cases where a province might not have cities
        this.selectedCity = null
        this.selectedDistrict = null
      }
    },
    selectCity(city) {
      this.selectedCity = city
      this.districts = city.children || []
      this.selectedDistrict = null
      if (this.districts.length > 0) {
        this.selectDistrict(this.districts[0])
      } else {
        // Handle cases where a city might not have districts
        this.selectedDistrict = null
      }
    },
    selectDistrict(district) {
      this.selectedDistrict = district
    },
    handleClose() {
      this.popupVisible = false
    },
    async handleConfirm() {
      if (
        !this.selectedProvince ||
        !this.selectedCity ||
        !this.selectedDistrict
      ) {
        return
      }
      try {
        const params = {
          province: this.selectedProvince.id,
          city: this.selectedCity.id,
          county: this.selectedDistrict.id,
        }
        const res = await setRegion(params)
        if (res.code === 200) {
          this.handleClose()
          this.$emit('success')
          // Optionally show a success message
        } else {
          // Use a proper UI notification for errors
          throw new Error(res.message || 'Failed to set region')
        }
      } catch (error) {
        console.error('Failed to set region:', error)
        // Optionally show a user-facing error message
      }
    },
  },
}
</script>

<style scoped>
.region-select-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  transition: opacity 0.3s ease;
}

.region-select-popup {
  width: 90%;
  max-width: 680rpx;
  background-color: white;
  border-radius: 24rpx;
  animation: scale-up 0.3s ease-out;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.1);
}

.popup-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  flex-shrink: 0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1c1c1e;
  margin: 0;
}

.popup-btn {
  border: none;
  background: none;
  cursor: pointer;
}

.popup-content {
  overflow: hidden;
  flex-grow: 1;
}

.picker-columns {
  display: flex;
  height: 500rpx;
}

.picker-column {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.picker-column:not(:last-child) {
  border-right: 1rpx solid #eaeaeb;
}

.picker-column:nth-child(2) {
  background-color: #fcfcfc;
}

.picker-column::-webkit-scrollbar {
  display: none;
}
.picker-column {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.picker-column ul {
  list-style: none;
  padding: 0;
  margin: 0;
  text-align: center;
}

.picker-column li {
  padding: 24rpx 10rpx;
  font-size: 30rpx;
  color: #666;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition:
    background-color 0.2s ease,
    color 0.2s ease;
}

.picker-column li.selected {
  font-weight: 600;
  color: #007aff;
  background-color: #f0f7ff;
}

.popup-footer {
  display: flex;
  flex-shrink: 0;
  padding: 24rpx;
  gap: 24rpx;
  background-color: #f7f7f7;
  border-top: 1rpx solid #efefef;
}

.popup-footer .popup-btn {
  flex: 1;
  text-align: center;
  padding: 14rpx 0;
  font-size: 28rpx;
  border-radius: 40rpx;
  font-weight: 500;
  transition:
    transform 0.1s ease,
    box-shadow 0.2s ease;
}

.popup-footer .popup-btn:active {
  transform: scale(0.97);
}

.popup-footer .popup-cancel {
  background-color: #eee;
  color: #555;
}

.popup-footer .popup-confirm {
  background: linear-gradient(135deg, #007aff, #0056b3);
  color: white;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.25);
}

@keyframes scale-up {
  from {
    transform: scale(0.8);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}
</style>
