import type { RouteExtended, TokenAmount } from '@lifi/sdk';
import { Fragment } from 'react';
import { StepDivider } from '../../components/StepDivider/StepDivider.js';
import type { WidgetSubvariant } from '../../types/widget.js';
import { Step } from './Step.js';
import { safeBigInt } from '../../utils/utils.js';

export const getStepList = (
  route?: RouteExtended,
  subvariant?: WidgetSubvariant,
) =>
  (route?.steps || [])?.map((step, index, steps) => {
    const lastIndex = steps.length - 1;

    const fromToken: TokenAmount | undefined =
      index === 0
        ? {
            ...step.action.fromToken,
            amount: safeBigInt(step?.action?.fromAmount),
            symbol: step?.action?.fromToken?.symbol,
            decimals: step?.action?.fromToken?.decimals,
          }
        : undefined;

    let toToken: TokenAmount | undefined;
    let impactToken: TokenAmount | undefined;

    if (index === lastIndex) {
      // const toAmount = step?.execution?.toAmount ?? step?.estimate?.toAmount;

      toToken = {
        ...(step?.execution?.toToken ?? step?.action?.toToken),
        amount: step?.execution?.toAmount
          ? safeBigInt(step?.execution?.toAmount)
          : subvariant === 'custom'
            ? safeBigInt(route?.toAmount)
            : safeBigInt(step?.estimate?.toAmount),
        symbol: (step?.execution?.toToken ?? step?.action?.toToken)?.symbol,
        decimals: (step?.execution?.toToken ?? step?.action?.toToken)?.decimals,
      };

      impactToken = {
        ...steps[0].action.fromToken,
        amount: safeBigInt(steps[0].action.fromAmount),
        symbol: steps[0].action.fromToken?.symbol,
        decimals: steps[0].action.fromToken?.decimals,
      };
    }

    const toAddress =
      index === lastIndex && route?.fromAddress !== route?.toAddress
        ? route?.toAddress
        : undefined;

    return (
      <Fragment key={step.id}>
        <Step
          step={step}
          fromToken={fromToken}
          toToken={toToken}
          impactToken={impactToken}
          toAddress={toAddress}
          routePriceImpact={Number((route as any)?.priceImpact || 0)}
        />
        {steps.length > 1 && index !== steps.length - 1 ? (
          <StepDivider />
        ) : null}
      </Fragment>
    );
  });
