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

import { Fragment, useCallback, useRef, useState } from 'react';

import PageLoading from '@/components/page-loading';
import SafeBottomPadding from '@/components/safe-bottom-padding';
import { EventName } from '@/constants/app';
import { CollectEventName } from '@/constants/event';
import { ProfileGroupType, ProfileTitleMap } from '@/constants/material';
import ProfileAdvantagesFragment from '@/fragments/profile/advantages';
import ProfileBasicFragment from '@/fragments/profile/basic';
import ProfileExperienceFragment from '@/fragments/profile/experience';
import ProfileIntentionFragment from '@/fragments/profile/intention';
import { MaterialProfile } from '@/types/material';
import { logWithPrefix } from '@/utils/common';
import { collectEvent } from '@/utils/event';
import { isProfileNotChange, requestProfileDetail, updateProfile } from '@/utils/material';
import { getPageQuery, navigateBack } from '@/utils/route';
import Toast from '@/utils/toast';

import './index.less';

const PREFIX = 'page-material-edit-profile';
const log = logWithPrefix(PREFIX);

export default function MaterialEdit() {
  const [profile, setProfile] = useState<MaterialProfile | null>(null);
  const [groupType, setGroupType] = useState<ProfileGroupType | null>(null);
  const ref = useRef<{ getData: () => Partial<MaterialProfile> } | null>(null);
  const ProfileFragment =
    groupType === ProfileGroupType.Basic
      ? ProfileBasicFragment
      : groupType === ProfileGroupType.Intention
        ? ProfileIntentionFragment
        : groupType === ProfileGroupType.Experience
          ? ProfileExperienceFragment
          : groupType === ProfileGroupType.Advantages
            ? ProfileAdvantagesFragment
            : Fragment;
  log('MaterialEdit', groupType, ref);

  const handleSubmit = useCallback(async () => {
    try {
      const data = ref.current?.getData();
      if (!data || !profile) {
        throw new Error('数据异常');
      }
      if (isProfileNotChange(profile, data)) {
        log('profile not change');
        navigateBack();
        return;
      }
      data.id = profile.id;
      await updateProfile(data);
      Taro.eventCenter.trigger(EventName.UPDATE_PROFILE);
      Toast.success('保存成功');
      navigateBack();
      log('handleSubmit', data);
    } catch (e) {
      Toast.error('保存失败请重试');
      collectEvent(CollectEventName.UPDATE_MATERIAL_FAILED, e);
    }
  }, [ref, profile]);

  useLoad(async () => {
    const query = getPageQuery<{ type: ProfileGroupType }>();
    const type = query.type || ProfileGroupType.Intention;
    const title = ProfileTitleMap[type];
    Taro.setNavigationBarTitle({ title });
    setGroupType(type);

    try {
      const profileInfo = await requestProfileDetail();
      setProfile(profileInfo);
    } catch (e) {
      console.error(e);
      Toast.error('出错了，请重试');
    }
  });

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

  return (
    <div className={PREFIX}>
      <ProfileFragment ref={ref} profile={profile} />
      <SafeBottomPadding />
      <div className={`${PREFIX}__footer`}>
        <Button className={`${PREFIX}__submit-btn`} onClick={handleSubmit}>
          保存
        </Button>
        <SafeBottomPadding />
      </div>
    </div>
  );
}
