import { chinaRegions } from '../data/china-regions.js';

const option = (value, label, selected = false) => `<option value="${value}" ${selected ? 'selected' : ''}>${label}</option>`;

export function regionSelects(region = {}, { required = true, className = 'region-selects' } = {}) {
  const province = chinaRegions.find(item => item.code === region.provinceCode);
  const city = province?.cities.find(item => item.code === region.cityCode);
  const requiredText = required ? 'required' : '';
  return `<div class="${className}" data-region-group>
    <label><span>省 / 自治区 / 直辖市${required ? ' *' : ''}</span><select name="provinceCode" data-region-level="province" ${requiredText}><option value="">请选择省份</option>${chinaRegions.map(item => option(item.code, item.name, item.code === region.provinceCode)).join('')}</select></label>
    <label><span>市 / 州${required ? ' *' : ''}</span><select name="cityCode" data-region-level="city" ${requiredText}><option value="">请先选择省份</option>${(province?.cities || []).map(item => option(item.code, item.name, item.code === region.cityCode)).join('')}</select></label>
    <label><span>区 / 县${required ? ' *' : ''}</span><select name="districtCode" data-region-level="district" ${requiredText}><option value="">请先选择城市</option>${(city?.districts || []).map(item => option(item.code, item.name, item.code === region.districtCode)).join('')}</select></label>
  </div>`;
}

export function updateRegionSelects(select) {
  const group = select.closest('[data-region-group]');
  if (!group) return;
  const provinceSelect = group.querySelector('[name="provinceCode"]');
  const citySelect = group.querySelector('[name="cityCode"]');
  const districtSelect = group.querySelector('[name="districtCode"]');
  const province = chinaRegions.find(item => item.code === provinceSelect?.value);
  if (select.dataset.regionLevel === 'province') {
    citySelect.innerHTML = `<option value="">请选择城市</option>${(province?.cities || []).map(item => option(item.code, item.name)).join('')}`;
    districtSelect.innerHTML = '<option value="">请先选择城市</option>';
  } else if (select.dataset.regionLevel === 'city') {
    const city = province?.cities.find(item => item.code === citySelect?.value);
    districtSelect.innerHTML = `<option value="">请选择区县</option>${(city?.districts || []).map(item => option(item.code, item.name)).join('')}`;
  }
}

export function mountRegionSelects(root, region = {}, options = {}) {
  const address = root?.querySelector('[name="address"]');
  if (!address || root.querySelector('[data-region-group]')) return;
  address.closest('label')?.insertAdjacentHTML('beforebegin', regionSelects(region, options));
}

export function formatRegionAddress(region = {}) {
  const parts = [region.provinceName, region.cityName, region.districtName]
    .filter((value, index, values) => value && value !== values[index - 1]);
  return [...parts, region.address].filter(Boolean).join('');
}
