import { useAccount } from "wagmi"
import { Address } from "brahma-console-kit"
import styled, { css } from "styled-components"
import { useEffect, useMemo, useState } from "react"

import {
  Button,
  FlexContainer,
  FormattedAmount,
  InfoLinkTag,
  Modal,
  OverlappingIcons,
  Typography,
} from "@/components/shared/components"
import { CloseIcon } from "@/icons"
import { useThemeContext } from "@/providers/themeProvider"
import { TAsset } from "@/types"
import { AutomationAgent, Trade } from "../../types"
import CompletionBar from "../CompletionBar"
import TradesView from "../TradesView"
import { fetchTrades } from "../../utils"
import { useIsMobile } from "@/hooks/use-is-mobile"
import TextWithTooltip from "@/components/shared/components/TextWithTooltip"
import { formatAmountWithOptions, parseUnits, truncateString } from "@/utils"
import { getBaseChainScanLink } from "@/components/morphoStrategy/utils"
import { BASE_CHAIN_ID } from "@/constants"
import { customMedia } from "@/lib"
import useWithdraw from "../hooks/useWithdraw"

type DetailsModalProps = {
  automationId: string
  variant: AutomationAgent
  targetToken: TAsset
  allocatedToken: TAsset
  percentageDone: number
  allocatedAmount: string
  maxAllocatedAmount: string
  maxPerTradeAmount: string
  onStopClick: () => void
  onClose: () => void
  tradeLogTitle: string
  actionLabel: string
  titleText: string
  allocationLabel: string
  colorTheme: string
  remainingBalance: string
  maxAllocatedAmountWithoutFees: string
  feeAmount: string
  createdAt: string
  totalDuration: string
  minPerTradeAmount: string
  subAccountAddress: Address
  automationType: "ACTIVE" | "HISTORY"
}

export function DetailsModal({
  automationId,
  variant,
  targetToken,
  allocatedToken,
  allocatedAmount,
  percentageDone,
  maxAllocatedAmount,
  minPerTradeAmount,
  maxPerTradeAmount,
  feeAmount,
  maxAllocatedAmountWithoutFees,
  onClose,
  onStopClick,
  tradeLogTitle,
  actionLabel,
  titleText,
  allocationLabel,
  colorTheme,
  remainingBalance,
  subAccountAddress,
  automationType,
  createdAt,
  totalDuration,
}: DetailsModalProps) {
  const { address: eoa } = useAccount()
  const { theme } = useThemeContext()

  const [trades, setTrades] = useState<{
    data: Trade[]
    loading: boolean
  }>({
    data: [],
    loading: false,
  })

  const sentToWalletAmount = useMemo(() => {
    return trades.data.reduce(
      (sum, trade) => sum + parseFloat(trade.sentToWalletAmount),
      0,
    )
  }, [trades])

  const isMobile = useIsMobile()

  const { handleWithdrawAmount, isWithdrawLoading } = useWithdraw({
    targetToken,
    allocatedToken,
    subAccountAddress,
  })

  const isRemainingBalanceLessThanMinPerTradeAmount =
    parseUnits(remainingBalance, allocatedToken.decimals) <
      BigInt(minPerTradeAmount) && automationType === "ACTIVE"

  useEffect(() => {
    if (!eoa) return

    const loadTrades = async () => {
      setTrades({ data: [], loading: true })
      try {
        const fetchedTrades = await fetchTrades(
          automationId,
          targetToken,
          allocatedToken,
          eoa,
          subAccountAddress,
        )
        setTrades({ data: fetchedTrades, loading: false })
      } catch (error) {
        console.error("Error fetching trades:", error)
        setTrades({ data: [], loading: false })
      } finally {
        setTrades((prevTrades) => ({ ...prevTrades, loading: false }))
      }
    }

    loadTrades()
  }, [automationId, targetToken, allocatedToken, subAccountAddress, eoa])

  return (
    <Modal
      bgOpacity={1}
      overlay={true}
      isOpen
      top={isMobile ? 8 : 16}
      isCenterAligned={false}
    >
      <FlexContainer
        gap={3.2}
        style={{ maxWidth: "56rem" }}
        padding="0rem 2rem"
        flexDirection="column"
        width={100}
        flex={false}
      >
        <FlexContainer
          justifyContent="space-between"
          alignItems="center"
          width={100}
          flex={false}
        >
          <Typography type={isMobile ? "TITLE_L" : "TITLE_XXL"}>
            {tradeLogTitle}
          </Typography>
          <FlexContainer flex={false} cursor="pointer" onClick={onClose}>
            <CloseIcon height={isMobile ? 24 : 40} width={isMobile ? 24 : 40} />
          </FlexContainer>
        </FlexContainer>

        <FlexContainer
          flex={false}
          gap={1.6}
          flexDirection="column"
          width={100}
        >
          <Typography
            type={isMobile ? "TITLE_XS" : "TITLE_S"}
            color={theme.colors.gray400}
          >
            {actionLabel}
          </Typography>
          <FlexContainer gap={0.8} alignItems="center" width={100}>
            <OverlappingIcons
              iconSize={isMobile ? 36 : 48}
              icons={[targetToken.logo, allocatedToken.logo]}
            />
            <TokenTitle>{titleText}</TokenTitle>
          </FlexContainer>
        </FlexContainer>

        <FlexContainer
          flex={false}
          gap={1.6}
          flexDirection="column"
          width={100}
        >
          <FlexContainer
            justifyContent="space-between"
            width={100}
            style={{ flexWrap: "wrap" }}
            gap={0.8}
          >
            <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>

          <CompletionBar percentage={percentageDone} color={colorTheme} />

          <FlexContainer
            style={{ flexWrap: "wrap" }}
            justifyContent="space-between"
            width={100}
            gap={0.8}
          >
            <FlexContainer alignItems="center" flex={false} gap={0.8}>
              <Typography
                type={isMobile ? "TITLE_XS" : "TITLE_S"}
                color={theme.colors.gray500}
              >
                Remaining Balance
              </Typography>
              <Typography
                type={isMobile ? "TITLE_XS" : "TITLE_S"}
                color={theme.colors.gray100}
              >
                {formatAmountWithOptions(remainingBalance, {
                  maximumFractionDigits: 8,
                })}{" "}
                {allocatedToken.name}
              </Typography>
            </FlexContainer>

            <FlexContainer alignItems="center" flex={false} gap={0.8}>
              <Typography
                type={isMobile ? "TITLE_XS" : "TITLE_S"}
                color={theme.colors.gray500}
              >
                Sent to your wallet
              </Typography>
              <FlexContainer alignItems="center" gap={0.2}>
                <FormattedAmount
                  amount={sentToWalletAmount}
                  typographyOptions={{
                    type: isMobile ? "TITLE_XS" : "TITLE_S",
                    color: theme.colors.gray100,
                  }}
                />
                <Typography
                  type={isMobile ? "TITLE_XS" : "TITLE_S"}
                  color={theme.colors.gray100}
                >
                  {targetToken.name}
                </Typography>
              </FlexContainer>
            </FlexContainer>
          </FlexContainer>
        </FlexContainer>

        <DetailBox
          variant={variant}
          createdAt={createdAt}
          totalDuration={totalDuration}
          allocatedToken={allocatedToken}
          automationType={
            isRemainingBalanceLessThanMinPerTradeAmount
              ? "HISTORY"
              : automationType
          }
          perTradeAmount={maxPerTradeAmount}
        />

        <FlexContainer
          alignItems="center"
          justifyContent="space-between"
          width={100}
          flex={false}
          gap={0.8}
          style={{
            paddingBottom: "2rem",
            borderBottom: `1px solid ${theme.colors.gray700}`,
          }}
        >
          <Typography type={"TITLE_XS"} color={theme.colors.gray400}>
            Agent Address
          </Typography>
          <InfoLinkTag
            toolTipContent={subAccountAddress}
            content={truncateString(subAccountAddress)}
            link={getBaseChainScanLink(
              subAccountAddress,
              BASE_CHAIN_ID,
              "address",
            )}
            textToCopy={getBaseChainScanLink(
              subAccountAddress,
              BASE_CHAIN_ID,
              "address",
            )}
          />
        </FlexContainer>

        <TradesView trades={trades.data} loading={trades.loading} />

        {automationType === "ACTIVE" && (
          <>
            <FlexContainer gap={1.2} flexDirection="column">
              <Typography type="TITLE_S" color={theme.colors.gray200}>
                {isRemainingBalanceLessThanMinPerTradeAmount
                  ? "Agentic transaction is complete"
                  : "Agent is in progress"}
              </Typography>

              <Typography type="BODY_S" color={theme.colors.gray400}>
                {isRemainingBalanceLessThanMinPerTradeAmount
                  ? "The swapped asset has been sent to your wallet, but there’s a small amount left. Please complete the last step manually. Any remaining funds will be returned to your wallet. After closing the agent, the log will be saved in your history."
                  : "The agent is still running trades, but you can stop it anytime to settle the balances. Both assets will be sent to your wallet. After closing the agent, the log will be saved in your history."}
              </Typography>
            </FlexContainer>
            <FlexContainer flex={false} width={100} padding="0 0 6.4rem 0">
              <Button
                buttonType={
                  isRemainingBalanceLessThanMinPerTradeAmount
                    ? "white"
                    : "danger"
                }
                buttonSize="L"
                disabled={
                  isRemainingBalanceLessThanMinPerTradeAmount &&
                  isWithdrawLoading
                }
                onClick={
                  isRemainingBalanceLessThanMinPerTradeAmount
                    ? handleWithdrawAmount
                    : onStopClick
                }
              >
                {isRemainingBalanceLessThanMinPerTradeAmount
                  ? isWithdrawLoading
                    ? "Claiming remaining balances ..."
                    : "Close and Claim balances"
                  : "Stop Agent and Withdraw"}
              </Button>
            </FlexContainer>
          </>
        )}
      </FlexContainer>
    </Modal>
  )
}

function DetailBox({
  variant,
  createdAt,
  totalDuration,
  perTradeAmount,
  allocatedToken,
  automationType,
}: {
  variant: AutomationAgent
  createdAt: string
  totalDuration: string
  perTradeAmount: string
  allocatedToken: TAsset
  automationType: "ACTIVE" | "HISTORY"
}) {
  const { theme } = useThemeContext()
  const tradeTypeLabel = variant === "SURGE" ? "buy" : "sell"
  const isMobile = useIsMobile()

  const createdAtDate = new Date(createdAt)

  const currentTime = new Date()

  const elapsedTimeInHours =
    Math.abs(currentTime.getTime() - createdAtDate.getTime()) / (1000 * 3600)

  return (
    <FlexContainer
      padding={isMobile ? "1.6rem" : "1.6rem 2.4rem"}
      justifyContent="space-between"
      borderRadius={0.8}
      borderColor={theme.colors.gray700}
      width={100}
      flex={false}
    >
      <FlexContainer flex={false} flexDirection="column" gap={0.8}>
        <Typography type="TITLE_XS" color={theme.colors.gray400}>
          Max {tradeTypeLabel} per trade
        </Typography>
        <TokenTitle>
          {formatAmountWithOptions(perTradeAmount, {
            maximumFractionDigits: 8,
          })}{" "}
          {allocatedToken.name}
        </TokenTitle>
      </FlexContainer>

      <FlexContainer flex={false} flexDirection="column" gap={0.8}>
        <Typography type="TITLE_XS" color={theme.colors.gray400}>
          Duration
        </Typography>
        <TokenTitle>
          {automationType === "HISTORY"
            ? totalDuration
            : elapsedTimeInHours.toFixed(2)}
          /{totalDuration}{" "}
          <span style={{ color: theme.colors.gray500 }}>H</span>
        </TokenTitle>
      </FlexContainer>
    </FlexContainer>
  )
}

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;
      line-height: 24px;
    `}
  `}
`
