import { Box, Badge } from 'components/common';
import { Quotas, UserQuota } from './Quotas';

import { formatCurrency, formatDate } from 'utils';

const DATE_FORMAT: Intl.DateTimeFormatOptions = {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
};

export interface PackageInformationProps {
  data: {
    name: string;
    price: number;
    status: string;
    cancelAtPeriodEnd: boolean;
    billingCycle: string;
    nextPayment: string | null;
    quotas: UserQuota[];
  };
  hasScheduledChange: boolean;
  scheduled: boolean;
  onCancel?: () => void;
}

export const PackageInformation = ({
  data,
  hasScheduledChange,
  scheduled,
  onCancel,
}: PackageInformationProps) => {
  const current = !scheduled;
  const isTrial = data.status === 'trial';
  const cancelAt = data.cancelAtPeriodEnd;

  const renderDate = (date: string) => {
    const txt = current
      ? isTrial
        ? 'Trial ends'
        : cancelAt
        ? 'Will be canceled'
        : hasScheduledChange
        ? 'Effective until'
        : 'Next payment'
      : 'Effective from';

    return `${txt} ${formatDate(date, DATE_FORMAT)}`;
  };

  return (
    <Box
      className="fz14 rounded4"
      style={{ border: '1px solid var(--borderColor)' }}
    >
      <Box spacingY={2} padding={4}>
        <Box display="flex" justify="between">
          <Box spacing={2}>
            <span className="bold">{data.name}</span>
            <Badge
              color={current ? 'green' : 'gray'}
              className="fz12"
              bold
              uppercase
            >
              {data.status}
            </Badge>
          </Box>

          <span
            className="bold"
            title={
              data.billingCycle === 'annual'
                ? 'Billed annually'
                : 'Billed monthly'
            }
          >
            {formatCurrency(data.price)} / month
          </span>
        </Box>

        <Box display="flex" justify="between">
          {data.nextPayment ? (
            <span className="c-gray">{renderDate(data.nextPayment)}</span>
          ) : (
            <span className="c-gray">
              Change or renew your plan to activate the subscription
            </span>
          )}
          {!cancelAt && onCancel && (
            <span className="c-gray link" onClick={onCancel}>
              {current ? 'Cancel subscription' : 'Cancel change'}
            </span>
          )}
        </Box>
      </Box>

      {current && (
        <Box style={{ borderTop: '1px solid var(--borderColor)' }} padding={4}>
          <Quotas data={data.quotas} />
        </Box>
      )}
    </Box>
  );
};
