import Taro, { useLoad } from '@tarojs/taro';

import { useCallback, useRef, useState } from 'react';

import SearchCity from '@/components/search-city';
import { EventName, OpenSource } from '@/constants/app';
import { logWithPrefix } from '@/utils/common';
import { getPageQuery, navigateBack } from '@/utils/route';
import './index.less';

const PREFIX = 'search-city-profile';

const log = logWithPrefix(PREFIX);
const realtimeLogger = Taro.getRealtimeLogManager();
realtimeLogger.tag(PREFIX);

export default function SearchCityProfilePage() {
  const [currentCity, setCurrentCity] = useState<string>('');
  const openSourceRef = useRef<OpenSource>(OpenSource.None);

  const handleSelectCity = useCallback(cityCode => {
    realtimeLogger.info('handleSelectCity openSource', openSourceRef.current);
    Taro.eventCenter.trigger(EventName.SELECT_CITY, { openSource: openSourceRef.current, cityCode: String(cityCode) });
    navigateBack(1);
  }, []);

  useLoad(() => {
    const query = getPageQuery<{ city: string; source: OpenSource }>();
    log('query', query);
    const { city: cityCode, source: openSource } = query;
    realtimeLogger.info('searchCity query source', openSource);
    if (!cityCode) {
      return;
    }
    setCurrentCity(cityCode);
    openSourceRef.current = openSource || OpenSource.None;
  });

  return (
    <div className={PREFIX}>
      <SearchCity onSelectCity={handleSelectCity} currentCity={currentCity} />
    </div>
  );
}
