import { Address } from "brahma-console-kit"
import { erc20Abi } from "viem"
import styled, { css } from "styled-components"
import { useReadContract } from "wagmi"

import {
  Button,
  FlexContainer,
  OverlappingIcons,
  Typography,
} from "@/components/shared/components"
import useBoolean from "@/hooks/useBoolean"
import { customMedia, Theme } from "@/lib"
import { useThemeContext } from "@/providers/themeProvider"
import { TAsset } from "@/types"
import { formatAmountWithOptions, formatUnits } from "@/utils"
import { AutomationAgent } from "../../types"
import CompletionBar from "../CompletionBar"
import { DetailsModal } from "../DetailsModal"
import ExitModal from "../ExitModal"
import { useIsMobile } from "@/hooks/use-is-mobile"
import TextWithTooltip from "@/components/shared/components/TextWithTooltip"

const TokenTitle = styled(Typography)`
  ${({ theme }) => css`
    color: ${theme.colors.gray100};
    font-size: 24px;
    font-style: normal;
    font-weight: 500;
    line-height: 28px;

    ${customMedia.lessThan("small")`
      font-size: 20px;
    `}
  `}
`

const getVariantProperties = (
  variant: AutomationAgent,
  theme: Theme,
  targetToken: TAsset,
  allocatedToken: TAsset,
  maxAllocatedAmount: string,
  automationType: "ACTIVE" | "HISTORY",
) => {
  const actionLabel =
    variant === "SURGE"
      ? automationType === "ACTIVE"
        ? "Buy"
        : "Bought"
      : automationType === "ACTIVE"
        ? "Sell"
        : "Sold"

  return {
    colorTheme: variant === "SURGE" ? theme.colors.success : theme.colors.error,
    actionLabel: actionLabel,
    tradeLogTitle: variant === "SURGE" ? "Surge trade log" : "Purge trade log",
    allocationLabel: variant === "SURGE" ? "Allocated" : "Sold",
    titleText:
      variant === "SURGE"
        ? `${actionLabel} ${targetToken.name} for ${maxAllocatedAmount} ${allocatedToken.name}`
        : `${actionLabel} ${maxAllocatedAmount} ${allocatedToken.name} for ${targetToken.name}`,
    exitModalText: {
      buttonText: `Yes, stop ${variant === "SURGE" ? "Surge" : "Purge"}`,
      title: `Are you sure you want to stop ${variant === "SURGE" ? "Surge" : "Purge"} Agent?`,
    },
  }
}

type AutomationHistoryItemProps = {
  automationId: string
  variant: AutomationAgent
  targetToken: TAsset
  allocatedToken: TAsset
  maxAllocatedAmount: string
  maxPerTradeAmount: string
  minPerTradeAmount: string
  subAccountAddress: Address
  feeAmount: string
  createdAt: string
  totalDuration: string
  automationType: "ACTIVE" | "HISTORY"
}

export default function AutomationHistoryItem({
  automationId,
  variant,
  targetToken,
  allocatedToken,
  maxAllocatedAmount,
  maxPerTradeAmount,
  minPerTradeAmount,
  subAccountAddress,
  automationType,
  createdAt,
  totalDuration,
  feeAmount,
}: AutomationHistoryItemProps) {
  const { theme } = useThemeContext()

  const isMobile = useIsMobile()

  const { data } = useReadContract({
    abi: erc20Abi,
    address: allocatedToken.address,
    functionName: "balanceOf",
    args: [subAccountAddress],
  })

  const remainingBalance = parseFloat(
    formatUnits(data ?? BigInt(0), allocatedToken.decimals),
  )
  const maxAllocatedAmountWithoutFees =
    parseFloat(maxAllocatedAmount) - parseFloat(feeAmount)
  const allocatedAmount = maxAllocatedAmountWithoutFees - remainingBalance
  const percentageDone = Math.abs(
    Math.round((allocatedAmount / maxAllocatedAmountWithoutFees) * 100),
  )

  const {
    setTrue: openDetailsModal,
    setFalse: closeDetailsModal,
    value: isDetailsModalOpen,
  } = useBoolean()

  const {
    setTrue: openExitModal,
    setFalse: closeExitModal,
    value: isExitModalOpen,
  } = useBoolean()

  const {
    colorTheme,
    actionLabel,
    tradeLogTitle,
    allocationLabel,
    titleText,
    exitModalText,
  } = getVariantProperties(
    variant,
    theme,
    targetToken,
    allocatedToken,
    formatAmountWithOptions(maxAllocatedAmountWithoutFees, {
      maximumFractionDigits: 8,
    }),
    automationType,
  )

  return (
    <>
      {isDetailsModalOpen && (
        <DetailsModal
          variant={variant}
          createdAt={createdAt}
          feeAmount={feeAmount}
          titleText={titleText}
          colorTheme={colorTheme}
          actionLabel={actionLabel}
          targetToken={targetToken}
          onClose={closeDetailsModal}
          onStopClick={openExitModal}
          automationId={automationId}
          totalDuration={totalDuration}
          tradeLogTitle={tradeLogTitle}
          allocatedToken={allocatedToken}
          automationType={automationType}
          percentageDone={percentageDone}
          allocationLabel={allocationLabel}
          minPerTradeAmount={minPerTradeAmount}
          maxPerTradeAmount={maxPerTradeAmount}
          subAccountAddress={subAccountAddress}
          maxAllocatedAmount={maxAllocatedAmount}
          allocatedAmount={allocatedAmount.toFixed(8)}
          remainingBalance={remainingBalance.toFixed(8)}
          maxAllocatedAmountWithoutFees={maxAllocatedAmountWithoutFees.toString()}
        />
      )}
      {isExitModalOpen && (
        <ExitModal
          title={exitModalText.title}
          buttonText={exitModalText.buttonText}
          targetToken={targetToken}
          allocatedToken={allocatedToken}
          subAccountAddress={subAccountAddress}
          closeExitModal={closeExitModal}
        />
      )}
      <FlexContainer flexDirection="column" gap={1.6} width={100}>
        <FlexContainer flexDirection="column" gap={2} width={100}>
          <FlexContainer gap={0.8} alignItems="center">
            <OverlappingIcons
              iconSize={isMobile ? 36 : 48}
              icons={[targetToken.logo, allocatedToken.logo]}
            />
            <TokenTitle>{titleText}</TokenTitle>
          </FlexContainer>

          <FlexContainer flexDirection="column" gap={1.2} width={100}>
            <CompletionBar percentage={percentageDone} color={colorTheme} />
            <FlexContainer
              gap={0.4}
              style={{ flexWrap: "wrap" }}
              justifyContent="space-between"
              width={100}
            >
              <Typography
                type={isMobile ? "TITLE_XS" : "TITLE_S"}
                color={colorTheme}
              >
                {percentageDone}% Completed
              </Typography>
              <FlexContainer flex={false} gap={0.8}>
                <Typography
                  type={isMobile ? "TITLE_XS" : "TITLE_S"}
                  color={theme.colors.gray500}
                >
                  {allocationLabel}
                </Typography>
                <TextWithTooltip
                  type={isMobile ? "TITLE_XS" : "TITLE_S"}
                  color={theme.colors.gray100}
                  text={`${formatAmountWithOptions(allocatedAmount, {
                    maximumFractionDigits: 8,
                  })}/${formatAmountWithOptions(maxAllocatedAmountWithoutFees, {
                    maximumFractionDigits: 8,
                  })} ${allocatedToken.name}`}
                  tooltipText={
                    <FlexContainer flexDirection="column">
                      <Typography type="BODY_MEDIUM_XS">
                        Total Amount :{" "}
                        {formatAmountWithOptions(maxAllocatedAmount, {
                          maximumFractionDigits: 8,
                        })}{" "}
                        {allocatedToken.name}
                      </Typography>
                      <Typography type="BODY_MEDIUM_XS">
                        Remaining Balance:{" "}
                        {formatAmountWithOptions(remainingBalance, {
                          maximumFractionDigits: 8,
                        })}{" "}
                        {allocatedToken.name}
                      </Typography>
                      <Typography type="BODY_MEDIUM_XS">
                        Fees:{" "}
                        {formatAmountWithOptions(feeAmount, {
                          maximumFractionDigits: 8,
                        })}{" "}
                        {allocatedToken.name}
                      </Typography>
                    </FlexContainer>
                  }
                />
              </FlexContainer>
            </FlexContainer>
          </FlexContainer>
        </FlexContainer>

        <Button
          buttonSize="L"
          buttonType="secondary"
          onClick={openDetailsModal}
        >
          Open details
        </Button>
      </FlexContainer>
    </>
  )
}
