import { BaseEventOrig, Button, Input, InputProps, Image } from '@tarojs/components';
import Taro from '@tarojs/taro';

import { Cell } from '@taroify/core';
import { useCallback, useRef } from 'react';

import useUserInfo from '@/hooks/use-user-info';
import { logWithPrefix } from '@/utils/common';
import Toast from '@/utils/toast';
import { updateUserInfo } from '@/utils/user';
import { commonUploadProgress, uploadVideo } from '@/utils/video';

import './index.less';

const PREFIX = 'user-info';
const log = logWithPrefix(PREFIX);

export default function UserInfo() {
  const userInfo = useUserInfo();
  const nameRef = useRef(userInfo.nickName);

  const handleChooseAvatar = useCallback(async () => {
    // const { avatarUrl } = e.detail;
    // log('handleChooseAvatar', avatarUrl, e.detail);
    // const { url } = await uploadVideo(avatarUrl, 'image', commonUploadProgress, 'user-avatar');
    // url && updateUserInfo({ avatarUrl: url });
    Taro.chooseMedia({
      mediaType: ['image'],
      sourceType: ['album'],
      count: 1,
      success: async ({ tempFiles }) => {
        log('handleChooseAvatar', tempFiles[0]);
        const { url } = await uploadVideo(tempFiles[0].tempFilePath, 'image', commonUploadProgress, 'user-avatar');
        url && updateUserInfo({ avatarUrl: url });
      },
    });
  }, []);

  const handleInput = useCallback((e: BaseEventOrig<InputProps.inputValueEventDetail>) => {
    const value = e.detail?.value || '';
    nameRef.current = value;
  }, []);

  const handleInputBlurOrConfirm = useCallback(() => {
    const newNickName = nameRef.current;
    if (!newNickName) {
      Toast.error('昵称不能为空');
    }

    log('confirm nickname changed:', newNickName, userInfo.nickName);
    newNickName !== userInfo.nickName && updateUserInfo({ nickName: newNickName });
  }, [userInfo]);

  return (
    <div className={PREFIX}>
      <Cell className={`${PREFIX}__avatar-cell`} title="头像" align="center" isLink>
        <Image
          mode="aspectFill"
          className={`${PREFIX}__avatar`}
          src={userInfo.avatarUrl || require('@/statics/png/default_avatar.png')}
        />
        <Button className={`${PREFIX}__avatar-button`} onClick={handleChooseAvatar} />
      </Cell>
      <Cell title="昵称" align="center" isLink>
        <Input
          type="nickname"
          confirmType="done"
          placeholder="请输入昵称"
          value={nameRef.current}
          onInput={handleInput}
          onBlur={handleInputBlurOrConfirm}
          onConfirm={handleInputBlurOrConfirm}
        />
      </Cell>
    </div>
  );
}
