import type { TokenAmount } from '@lifi/sdk';
import { ExpandLess, ExpandMore } from '@mui/icons-material';
import { Box, Collapse, Typography } from '@mui/material';
import type { MouseEventHandler } from 'react';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useAccount } from '../../hooks/useAccount.js';
import { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';
import type { CardProps } from '../Card/Card.js';
import { Card } from '../Card/Card.js';
import { CardIconButton } from '../Card/CardIconButton.js';
import { CardLabel, CardLabelTypography } from '../Card/CardLabel.js';
import { StepActions } from '../StepActions/StepActions.js';
import { Token } from '../Token/Token.js';
import { TokenContainer } from './RouteCard.style.js';
import { RouteCardEssentials } from './RouteCardEssentials.js';
// import { RouteCardEssentialsExpanded } from './RouteCardEssentialsExpanded.js';
import type { RouteCardProps } from './types.js';
import { TokenPnLTypography } from '../TokenRate/TokenRate.style.js';
import axios from 'axios';
import { MOVE_CHAIN_ID } from '../../utils/constants.js';

export const RouteCard: React.FC<
  RouteCardProps & Omit<CardProps, 'variant'>
> = ({
  route,
  active,
  variant = 'default',
  expanded: defaulExpanded,
  ...other
}) => {
  const { account } = useAccount();
  const { t } = useTranslation();
  const { subvariant } = useWidgetConfig();
  const [cardExpanded, setCardExpanded] = useState(defaulExpanded);

  const handleExpand: MouseEventHandler<HTMLButtonElement> = (e) => {
    e.stopPropagation();
    setCardExpanded((expanded) => !expanded);
  };

  const token: TokenAmount =
    subvariant === 'custom'
      ? { ...route.fromToken, amount: BigInt(route?.fromAmount || 0) }
      : { ...route.toToken, amount: BigInt(route?.toAmount || 0) };

  const impactToken: TokenAmount | undefined =
    subvariant !== 'custom'
      ? { ...route.fromToken, amount: BigInt(route?.fromAmount || 0) }
      : undefined;

  const tags = route.tags?.filter(
    (tag) => tag === 'CHEAPEST' || tag === 'FASTEST',
  );

  const [dataPnl, setDataPnL] = useState({
    pnl: 0,
    percent: 0,
  });

  const handleCalPnL = async (data: any, address: string) => {
    try {
      const formatAmountFrom =
        Number(data?.fromAmount) / 10 ** data?.fromToken?.decimals;
      const formatAmountTo =
        Number(data?.toAmount) / 10 ** data?.toToken?.decimals;

      const payload = {
        owner: address,
        from: {
          address: data?.fromToken?.address,
          symbol: data?.fromToken?.symbol,
          quantity: formatAmountFrom,
          price: Number(data?.fromToken?.priceUSD),
        },
        to: {
          address: data?.toToken?.address,
          symbol: data?.toToken?.symbol,
          quantity: formatAmountTo,
          price: Number(data?.toToken?.priceUSD),
        },
      };

      const response = await axios
        .post(
          `https://api.getnimbus.io/swap/pnl?chain=${data?.fromChainId}`,
          payload,
        )
        .then((res) => res?.data?.data);

      if (response && response?.newRealizedPnL !== 0) {
        setDataPnL({
          pnl: response?.newRealizedPnL - response?.currentRealizedPnL,
          percent:
            Number(response?.cost) === 0
              ? 0
              : (response?.newRealizedPnL - response?.currentRealizedPnL) /
                Number(response?.cost),
        });
      }
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    if (
      route?.fromChainId &&
      route?.fromChainId === MOVE_CHAIN_ID &&
      account?.isConnected
    ) {
      handleCalPnL(route, account?.address || '');
    }
  }, [route, account]);

  const cardContent = (
    <Box flex={1}>
      {subvariant !== 'refuel' && route.tags?.length ? (
        <Box display="flex" alignItems="center" mb={2}>
          {tags?.length ? (
            <CardLabel type={active ? 'active' : undefined}>
              <CardLabelTypography>
                {t(`main.tags.${tags[0].toLowerCase()}` as any)}
              </CardLabelTypography>
            </CardLabel>
          ) : null}
        </Box>
      ) : null}

      <TokenContainer>
        <Token
          token={token}
          impactToken={impactToken}
          step={route?.steps ? route?.steps[0] : undefined}
          stepVisible={!cardExpanded}
          isFromRoute={true}
          routePriceImpact={(route as any)?.priceImpact || 0}
        />
        {!defaulExpanded ? (
          <CardIconButton onClick={handleExpand} size="small">
            {cardExpanded ? (
              <ExpandLess fontSize="inherit" />
            ) : (
              <ExpandMore fontSize="inherit" />
            )}
          </CardIconButton>
        ) : null}
      </TokenContainer>

      <Collapse timeout={225} in={cardExpanded} mountOnEnter unmountOnExit>
        {route?.steps?.map((step) => (
          <StepActions key={step.id} step={step} mt={2} />
        ))}
        {/* <RouteCardEssentialsExpanded route={route} /> */}
      </Collapse>

      <RouteCardEssentials route={route} />

      {route?.fromChainId === MOVE_CHAIN_ID && account?.isConnected && (
        <Box
          display="flex"
          alignItems="center"
          justifyContent={'space-between'}
          flex={1}
          mt={1}
        >
          <TokenPnLTypography>📊 PnL</TokenPnLTypography>

          <Box display="flex" alignItems="center">
            <Typography
              fontSize={14}
              color={
                Number(dataPnl.pnl) === 0
                  ? 'text.primary'
                  : Number(dataPnl.pnl) < 0
                    ? '#f05252'
                    : '#00A878'
              }
              fontWeight={600}
              lineHeight={1}
              marginRight={0.6}
            >
              {Math.abs(Number(dataPnl.pnl)) < 0.1 ? (
                `< ${Number(dataPnl.pnl) < 0 ? '-' : ''}$0.1`
              ) : (
                <>
                  {t(`format.currency`, {
                    value: Number(dataPnl.pnl),
                  })}
                </>
              )}
            </Typography>

            {/* <Typography
              fontSize={14}
              color={
                Number(dataPnl.percent) === 0
                  ? 'text.primary'
                  : Number(dataPnl.percent) < 0
                    ? '#f05252'
                    : '#00A878'
              }
              fontWeight={600}
              lineHeight={1}
            >
              (
              {Math.abs(Number(dataPnl.percent)) < 0.1 ? (
                `< ${Number(dataPnl.percent) < 0 ? '-' : ''}0.1%`
              ) : (
                <>{Number(dataPnl.percent).toFixed(2)}%</>
              )}
              )
            </Typography> */}
          </Box>
        </Box>
      )}
    </Box>
  );

  return subvariant === 'refuel' || variant === 'cardless' ? (
    cardContent
  ) : (
    <Card
      type={active ? 'selected' : 'default'}
      selectionColor="secondary"
      indented
      {...other}
    >
      {cardContent}
    </Card>
  );
};
