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

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

import MaterialManagePopup from '@/components/material-manage-popup';
import PageLoading from '@/components/page-loading';
import SafeBottomPadding from '@/components/safe-bottom-padding';
import { EventName, RoleType } from '@/constants/app';
import { CollectEventName } from '@/constants/event';
import { MaterialStatus } from '@/constants/material';
import ProfileViewFragment from '@/fragments/profile/view';
import { MaterialProfile } from '@/types/material';
import { collectEvent } from '@/utils/event';
import { getMaterialShareMessage, requestProfileDetail, updateProfileStatus } from '@/utils/material';
import { getCommonShareMessage } from '@/utils/share';
import Toast from '@/utils/toast';

import './index.less';
import { switchRoleType } from '@/utils/app';

const PREFIX = 'page-material-profile';

export default function MaterialProfilePage() {
  const [profile, setProfile] = useState<MaterialProfile | null>(null);
  const [showManage, setShowManage] = useState(false);

  const handleClickManage = useCallback(() => setShowManage(true), []);

  const handleChangeStatus = useCallback(
    async (newStatus: boolean) => {
      if (!profile || newStatus === profile.isOpen) {
        return;
      }
      try {
        await updateProfileStatus({ resumeId: profile.id, userOpen: newStatus });
        profile.isOpen = newStatus;
      } catch (e) {
        Toast.error('保存失败请重试');
        collectEvent(CollectEventName.UPDATE_MATERIAL_FAILED, e);
      }
    },
    [profile]
  );

  useEffect(() => {
    const callback = async () => {
      try {
        const profileDetail = await requestProfileDetail();
        setProfile(profileDetail);
      } catch (e) {
        Toast.error('加载失败');
      }
    };
    Taro.eventCenter.on(EventName.CREATE_PROFILE, callback);
    Taro.eventCenter.on(EventName.UPDATE_PROFILE, callback);
    return () => {
      Taro.eventCenter.off(EventName.CREATE_PROFILE, callback);
      Taro.eventCenter.off(EventName.UPDATE_PROFILE, callback);
    };
  }, []);

  useLoad(async () => {
    try {
      const profileDetail = await requestProfileDetail();
      setProfile(profileDetail);
    } catch (e) {
      Toast.error('加载失败');
    }
  });

  useShareAppMessage(async () => {
    const shareMessage = await getMaterialShareMessage(profile, false);
    return shareMessage || getCommonShareMessage({ useCapture: false });
  });

  if (!profile) {
    return <PageLoading />;
  }

  return (
    <div className={PREFIX}>
      <ProfileViewFragment profile={profile} editable />
      <div className={`${PREFIX}__footer`}>
        <div className={`${PREFIX}__footer__buttons`}>
          <Button className={`${PREFIX}__footer__buttons__share`} openType="share">
            分享
          </Button>
          <Button className={`${PREFIX}__footer__buttons__manager`} onClick={handleClickManage}>
            管理
          </Button>
        </div>
        <SafeBottomPadding />
      </div>
      <div>
        <MaterialManagePopup
          open={showManage}
          onSave={handleChangeStatus}
          onClose={() => setShowManage(false)}
          value={profile.userOpen ? MaterialStatus.Open : MaterialStatus.Close}
        />
      </div>
    </div>
  );
}
