import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { Button, Text, View } from '@tarojs/components';
import { loadRegions, type RegionItem } from '@/services/catalog';
import { loadProfile, updateProfile, type StudentProfile } from '@/services/profile';
import '../student.css';

export default function StudentRegionPage() {
  const [regions, setRegions] = useState<RegionItem[]>([]);
  const [profile, setProfile] = useState<StudentProfile | null>(null);
  const [busy, setBusy] = useState('');
  const [error, setError] = useState('');

  function reload() {
    Promise.all([
      loadRegions().catch(() => ({ items: [] })),
      loadProfile().catch(() => ({ item: null })),
    ]).then(([regionPayload, profilePayload]) => {
      setRegions(regionPayload.items || []);
      setProfile(profilePayload.item || null);
    }).catch(nextError => setError(nextError instanceof Error ? nextError.message : '地区加载失败'));
  }

  useEffect(() => {
    reload();
  }, []);

  async function selectRegion(item: RegionItem) {
    setBusy(item.id);
    setError('');
    try {
      await updateProfile({ regionId: item.id });
      Taro.showToast({ title: '已切换地区', icon: 'success' });
      reload();
    } catch (nextError) {
      setError(nextError instanceof Error ? nextError.message : '地区保存失败');
    } finally {
      setBusy('');
    }
  }

  const currentRegionId = profile?.target?.regionId;

  return (
    <View className='student-page'>
      <View className='student-topbar'>
        <View className='student-title-block'>
          <Text className='student-kicker'>Region</Text>
          <Text className='student-title'>选择地区</Text>
          <Text className='student-subtitle'>地区会影响题库入口、分数线、资料、考试倒计时和会员权益范围。</Text>
        </View>
        <Button className='secondary-button' onClick={() => Taro.navigateBack()}>返回</Button>
      </View>

      <View className='list-stack'>
        {regions.map(item => (
          <View className={`list-row ${item.id === currentRegionId ? 'active' : ''}`} key={item.id} onClick={() => selectRegion(item)}>
            <Text className='row-main'>{item.name}{item.isHot ? ' · 热门' : ''}</Text>
            <Text className='row-meta'>{item.shortName || item.code || '地区'}{item.id === currentRegionId ? ' · 当前选择' : ''}</Text>
            {busy === item.id ? <Text className='row-meta'>保存中...</Text> : null}
          </View>
        ))}
      </View>

      {!regions.length ? <View className='empty-state'>当前租户暂无可选地区，请联系后台管理员配置地区和题库入口。</View> : null}
      {error ? <Text className='error-text'>{error}</Text> : null}
    </View>
  );
}
