import React, { useState } from 'react';
import { Select } from 'antd';
import _ from 'lodash';
import { AreaCodes, AreaCode } from '@/types/common';
import styles from './style.less';

const Option = Select.Option;

interface AreaSelectionProps {
  areacodes: AreaCodes;
  areacode?: AreaCode;
  onChange?: (areacode: AreaCode) => void;
  className?: string;
  size?: 'large' | 'default' | 'small',
}

const AreaSelection: React.FC<AreaSelectionProps> = ({
  areacode,
  areacodes,
  onChange,
  className = '',
  size,
}) => {
  const [value, setValue] = useState(areacodes[0]);

  const onValueChange = (id: string) => {
    const target = _.find(areacodes, { id });
    if (target) {
      if (onChange) { onChange(target); }
      if (!areacode) { setValue(target); }
    }
  };

  const actual = areacode || value;
  return (
    <div className={`${styles.component} ${className}`}>
      <div className="name">
        <Select
          value={actual && actual.id}
          onChange={onValueChange}
          size={size}
        >
          {areacodes.map(it => (
            <Option
              key={it.id}
              value={it.id}
            >{it.areaname}</Option>
          ))}
        </Select>
      </div>

      <div className="code">
        <Select
          value={actual && actual.id}
          onChange={onValueChange}
          size={size}
        >
          {areacodes.map(it => (
            <Option
              key={it.id}
              value={it.id}
            >+{it.areacode}</Option>
          ))}
        </Select>
      </div>
    </div>
  )
}

export default AreaSelection;
