import { AreaPicker, Popup } from '@taroify/core';
import { AreaData } from '@taroify/core/area-picker/area-picker.shared';
import { useCallback, useRef } from 'react';

import SafeBottomPadding from '@/components/safe-bottom-padding';
import { CITY_LIST, COUNTY_LIST, PROVINCE_LIST } from '@/constants/city';

import './index.less';

interface IProps {
  depth?: 1 | 2 | 3;
  areaValues?: string[];
  onCancel: () => void;
  onConfirm: (areaValues: string[]) => void;
}

interface IPopupProps extends IProps {
  open: boolean;
}

const PREFIX = 'city-picker';
const areaList: AreaData = {
  province_list: PROVINCE_LIST,
  city_list: CITY_LIST,
  county_list: COUNTY_LIST,
};
const DEFAULT_AREA = ['110000', '110100', '110101'];

function CityPicker(props: IProps) {
  const { areaValues = DEFAULT_AREA, depth = 3, onCancel, onConfirm } = props;
  const provinceCodeRef = useRef(areaValues[0]);
  const cityCodeRef = useRef(areaValues[1]);
  const countyCodeRef = useRef(areaValues[2]);

  const handleClickConfirm = useCallback(() => {
    onConfirm([provinceCodeRef.current, cityCodeRef.current, countyCodeRef.current]);
  }, [onConfirm]);

  const handleChange = useCallback((values: string[]) => {
    provinceCodeRef.current = values[0];
    cityCodeRef.current = values[1];
    countyCodeRef.current = values[2];
  }, []);

  return (
    <div className={PREFIX}>
      <AreaPicker
        depth={depth}
        className={`${PREFIX}__area-picker`}
        areaList={areaList}
        defaultValue={areaValues}
        onCancel={onCancel}
        onChange={handleChange}
        onConfirm={handleClickConfirm}
      ></AreaPicker>
    </div>
  );
}

export function CityPickerPopup(props: IPopupProps) {
  const { open, onCancel } = props;
  return (
    <Popup className={PREFIX} placement="bottom" open={open} onClose={onCancel}>
      <CityPicker {...props} />
      <SafeBottomPadding />
    </Popup>
  );
}

export default CityPicker;
