import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Status, getSubscriptionStatusColor, formatSubscriptionStatus, getLineTimeInfo } from '@blocklet/payment-react';
import type { TSubscription } from '@blocklet/payment-types';
import { AccessTimeOutlined } from '@mui/icons-material';

export default function SubscriptionStatus({
  subscription,
  ...rest
}: {
  subscription: TSubscription;
  [key: string]: any;
}) {
  const { t } = useLocaleContext();
  if (subscription.status === 'active' || subscription.status === 'trialing') {
    if (subscription.cancel_at_period_end && subscription.current_period_end > Date.now() / 1000) {
      const dateInfo = getLineTimeInfo(subscription.current_period_end * 1000);
      return (
        <Status
          icon={<AccessTimeOutlined />}
          label={t('admin.subscription.cancel.will', {
            date: dateInfo.time,
            prefix: dateInfo.isToday ? 'at' : 'on',
          })}
          color="warning"
          {...rest}
        />
      );
    }

    if (subscription.cancel_at && subscription.cancel_at >= Date.now() / 1000) {
      const dateInfo = getLineTimeInfo(subscription.cancel_at * 1000);
      return (
        <Status
          icon={<AccessTimeOutlined />}
          label={t('admin.subscription.cancel.will', {
            date: dateInfo.time,
            prefix: dateInfo.isToday ? 'at' : 'on',
          })}
          color="warning"
          {...rest}
        />
      );
    }

    if (subscription.trial_end && subscription.trial_end > Date.now() / 1000) {
      const dateInfo = getLineTimeInfo(subscription.trial_end * 1000);
      return (
        <Status
          label={t('admin.subscription.trialEnd', {
            date: dateInfo.time,
            prefix: dateInfo.isToday ? 'at' : 'on',
          })}
          color="info"
          {...rest}
        />
      );
    }
  }

  if (subscription.pause_collection && ['active', 'trialing'].includes(subscription.status)) {
    if (subscription.pause_collection.resumes_at && subscription.pause_collection.resumes_at > Date.now() / 1000) {
      const dateInfo = getLineTimeInfo(subscription.pause_collection.resumes_at * 1000);
      return (
        <Status
          icon={<AccessTimeOutlined />}
          label={t('admin.subscription.pause.until.custom', {
            date: dateInfo.time,
            prefix: dateInfo.isToday ? 'at' : 'on',
          })}
          color="default"
          {...rest}
        />
      );
    }

    return <Status label={t('admin.subscription.pause.until.never')} color="default" />;
  }

  return (
    <Status
      label={formatSubscriptionStatus(subscription.status)}
      color={getSubscriptionStatusColor(subscription.status)}
      {...rest}
    />
  );
}
