import { Result as AntdResult, ResultProps, ConfigProvider } from 'antd';
import React, { useContext, useMemo } from 'react';
import classNames from 'classnames';
import { RESULT_ASSETS } from './assets';
import './index.less';
import { translate } from '../utils';

const Prefix = 'btri-result';

const ICON = RESULT_ASSETS;

const PAGE_STATUSES = ['403', '404', '500'] as const;

const title: Record<(typeof PAGE_STATUSES)[number], string> = {
  403: '403',
  404: '404',
  500: '500',
};

function Result(props: ResultProps) {
  const { locale } = useContext(ConfigProvider.ConfigContext);
  const subTitle: Record<(typeof PAGE_STATUSES)[number], string> = {
    403: translate(
      'packages.base.src.Result.index.对不起您暂时没有访问权限',
      locale.locale,
    ),
    404: translate(
      'packages.base.src.Result.index.抱歉您访问的页面不存在',
      locale.locale,
    ),
    500: translate(
      'packages.base.src.Result.index.抱歉服务器出错了',
      locale.locale,
    ),
  };

  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls(Prefix);

  const { status = 'info', icon } = props;

  const defaultIcon = useMemo(() => {
    const src = ICON[status as keyof typeof ICON];
    if (!src) {
      return null;
    }
    const isPageStatus = PAGE_STATUSES.includes(
      status as (typeof PAGE_STATUSES)[number],
    );
    return (
      <img
        src={src}
        alt=""
        width={isPageStatus ? undefined : 48}
        height={isPageStatus ? undefined : 48}
      />
    );
  }, [status]);

  const isPageStatus = PAGE_STATUSES.includes(
    status as (typeof PAGE_STATUSES)[number],
  );

  return (
    <AntdResult
      title={isPageStatus ? title[status as keyof typeof title] : undefined}
      subTitle={
        isPageStatus ? subTitle[status as keyof typeof subTitle] : undefined
      }
      {...props}
      status={isPageStatus ? 'info' : status}
      icon={icon || defaultIcon}
      className={classNames(
        `${prefixCls}`,
        props.className,
        `${prefixCls}-${status}`,
      )}
    />
  );
}

export { Result };
