import { BaseEventOrig, InputProps } from '@tarojs/components';

import { forwardRef, useCallback, useImperativeHandle, useState } from 'react';

import BlFormInput from '@/components/bl-form-input';
import BlFormItem from '@/components/bl-form-item';
import { BlFormRadio, BlFormRadioGroup } from '@/components/bl-form-radio';
import { GenderType } from '@/constants/material';
import { MaterialProfile } from '@/types/material';
import { logWithPrefix, string2Number } from '@/utils/common';

import './index.less';

interface IProps {
  profile: Partial<MaterialProfile>;
}

const PREFIX = 'fragment-profile-basic';
const log = logWithPrefix(PREFIX);

function ProfileBasicFragment(props: IProps, ref) {
  const { profile } = props;
  const [name, setName] = useState(profile.name || '');
  const [gender, setGender] = useState<GenderType>(profile.gender || GenderType.WOMEN);
  const [age, setAge] = useState(profile.age || '');
  const [workedSecCategoryStr, setWorkedSecCategoryStr] = useState(profile.workedSecCategoryStr || '');

  const handleInputName = useCallback((e: BaseEventOrig<InputProps.inputEventDetail>) => {
    const value = e.detail.value || '';
    setName(value);
  }, []);

  const handleInputAge = useCallback((e: BaseEventOrig<InputProps.inputEventDetail>) => {
    const value = e.detail.value || '';
    if (Number.isNaN(Number(value))) {
      return;
    }
    setAge(string2Number(value));
  }, []);

  const handleGenderChange = useCallback((value: GenderType) => {
    log('handleGenderChange', value);
    setGender(value);
  }, []);
  const handleInputWorkedSecCategoryStr = useCallback((e: BaseEventOrig<InputProps.inputEventDetail>) => {
    const value = e.detail.value || '';
    setWorkedSecCategoryStr(value);
  }, []);

  useImperativeHandle(
    ref,
    () => ({
      getData: () => ({ name, gender, age, workedSecCategoryStr }),
    }),
    [name, gender, age, workedSecCategoryStr]
  );

  return (
    <div className={PREFIX}>
      <BlFormItem title="称呼">
        <BlFormInput value={name} onInput={handleInputName} />
      </BlFormItem>
      <BlFormItem title="年龄">
        <BlFormInput value={String(age)} type="number" maxlength={3} onInput={handleInputAge} rightText="岁" />
      </BlFormItem>
      <BlFormItem title="性别">
        <BlFormRadioGroup direction="horizontal" value={gender} onChange={handleGenderChange}>
          <BlFormRadio name={GenderType.WOMEN} text="女" value={gender} />
          <BlFormRadio name={GenderType.MEN} text="男" value={gender} />
        </BlFormRadioGroup>
      </BlFormItem>
      <BlFormItem title="直播过的品类" optional>
        <BlFormInput value={workedSecCategoryStr} maxlength={140} onInput={handleInputWorkedSecCategoryStr} />
      </BlFormItem>
    </div>
  );
}

export default forwardRef(ProfileBasicFragment);
