import { useEffect, useMemo } from "react"

import {
  Button,
  ContentWrapper,
  FlexContainer,
  GrayBoundaryBlackWrapper,
  InfoLinkTag,
  LogoViewer,
  Modal,
  Typography,
} from "@/components/shared/components"
import CloseButtonBox from "@/components/shared/components/CloseButtonBox"
import { useThemeContext } from "@/providers/themeProvider"

import TextWithTooltip from "@/components/shared/components/TextWithTooltip"
import { OpenInNewIcon, TickIcon, TooltipIcon } from "@/icons"
import * as S from "./style"
import {
  getBaseChainScanLink,
  getFormattedDate,
  getNextExecutionTime,
} from "../utils"
import { openInNewTab, sliceDecimalString, truncateString } from "@/utils"
import { MorphoYieldUserPosition } from "../types"
import { frequencyOptions } from "../constants"
import { MorphoScannerLottie } from "@/components/shared/assets"
import LottieReader from "@/components/shared/components/LottieReader"
import { TAsset } from "@/types"
import { BASE_CHAIN_ID } from "@/constants"

type WithdrawModalProps = {
  isOpen: boolean
  withdrawModalSuccessData: null | {
    asset: TAsset
    amount: string
    txHash: string
  }

  userPositionData: MorphoYieldUserPosition
  state: "IDLE" | "LOADING" | "SUCCESS"
  onClose: () => void
  onWithdrawClick: () => void
}

export default function WithdrawModal({
  isOpen,
  onClose,
  userPositionData,
  onWithdrawClick,
  state = "IDLE",
  withdrawModalSuccessData,
}: WithdrawModalProps) {
  const { theme } = useThemeContext()
  useEffect(() => {
    const handleKeyPress = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        onClose()
      }
    }
    window.addEventListener("keydown", handleKeyPress)
    return () => {
      window.removeEventListener("keydown", handleKeyPress)
    }
  }, [onClose])

  const tokenAmount = userPositionData?.tokenData.amount
  const tokenName = userPositionData?.tokenData.asset.name
  const tokenLogo = userPositionData?.tokenData.asset.logo
  const tokenAmountAndName = `${sliceDecimalString(tokenAmount || "", 8)} ${tokenName}`

  const sucessTokenAmount = withdrawModalSuccessData?.amount
  const sucessTokenName = withdrawModalSuccessData?.asset.name
  const sucessTokenLogo = withdrawModalSuccessData?.asset.logo

  const sucessTokenAmountAndName = `${sliceDecimalString(sucessTokenAmount || "", 8)} ${sucessTokenName}`

  const closeModal = () => {
    if (state === "LOADING") return
    onClose()
  }

  const renderState = useMemo(() => {
    switch (state) {
      case "IDLE": {
        if (!userPositionData) {
          return <></>
        }
        return <IdleState userPositionData={userPositionData} />
      }
      case "LOADING":
        return <LoadingState asset={tokenAmountAndName} logo={tokenLogo} />
      case "SUCCESS":
        return (
          <SucessState
            asset={sucessTokenAmountAndName}
            logo={sucessTokenLogo || ""}
            txHash={withdrawModalSuccessData?.txHash || ""}
          />
        )
    }
  }, [
    state,
    sucessTokenAmountAndName,
    sucessTokenLogo,
    tokenAmountAndName,
    tokenLogo,
    userPositionData,
    withdrawModalSuccessData?.txHash,
  ])

  return (
    <Modal isOpen={isOpen} onClickOutside={closeModal}>
      <S.ModalSection>
        <FlexContainer justifyContent="space-between">
          <Typography type="TITLE_S" color={theme.colors.gray100}>
            Withdrawal from Agent Account
          </Typography>
          <CloseButtonBox
            disabled={state === "LOADING"}
            closeButtonClick={closeModal}
          />
        </FlexContainer>
        {renderState}

        {state === "IDLE" && (
          <GrayBoundaryBlackWrapper padding="0.4rem">
            <FlexContainer
              padding="0.8rem"
              width={100}
              alignItems="center"
              flexDirection="column"
            >
              <TextWithTooltip
                text={`The above amount will be sent to your connected wallet`}
                color={theme.colors.gray100}
                type="BODY_MEDIUM_XS"
              />
              <TextWithTooltip
                text={`Reward tokens will be claimable in the next update`}
                color={theme.colors.gray100}
                type="BODY_MEDIUM_XS"
              />
            </FlexContainer>

            <ContentWrapper padding="1.6rem">
              <Button
                onClick={onWithdrawClick}
                buttonType="white"
                buttonSize="L"
                //   disabled={!isDepositDone}
              >
                Withdraw
              </Button>
            </ContentWrapper>
          </GrayBoundaryBlackWrapper>
        )}
      </S.ModalSection>
    </Modal>
  )
}

function IdleState({
  userPositionData,
}: {
  userPositionData: MorphoYieldUserPosition
}) {
  const { theme } = useThemeContext()

  const {
    duration,
    subAccountAddress,
    chainId,
    tokenData: { amount, asset },
    createdAt,
    metadata,
    vaultPositionData,
  } = userPositionData

  const nextExecutionTime = getNextExecutionTime(createdAt, Number(duration))

  const frequencyItem = frequencyOptions.find(
    (frequncy) => frequncy.value === metadata.every.toString(),
  )
  console.log({ vaultPositionData })
  return (
    <GrayBoundaryBlackWrapper padding="0.4rem">
      <ContentWrapper padding="1.2rem">
        <FlexContainer flexDirection="column" gap={0.4}>
          <Typography type="TITLE_XS" color={theme.colors.gray200}>
            Withdrawing
          </Typography>

          <FlexContainer justifyContent="space-between">
            <FlexContainer gap={0.8} alignItems="center">
              <LogoViewer size={32} logo={asset.logo} />
              <Typography type="TITLE_XL" color={theme.colors.white}>
                {sliceDecimalString(amount, 8)}
              </Typography>
            </FlexContainer>
          </FlexContainer>
        </FlexContainer>
      </ContentWrapper>

      <ContentWrapper padding="1.2rem">
        <FlexContainer gap={1.2} flexDirection="column" width={100}>
          {vaultPositionData?.vault && (
            <FlexContainer
              justifyContent="space-between"
              alignItems="center"
              width={100}
              cursor="pointer"
              onClick={() =>
                openInNewTab(
                  getBaseChainScanLink(
                    vaultPositionData.vault.address,
                    BASE_CHAIN_ID,
                    "address",
                  ),
                )
              }
            >
              <Typography type="BODY_S" color={theme.colors.gray200}>
                Vault Allocated
              </Typography>
              <FlexContainer flex={false} alignItems="center" gap={0.2}>
                <Typography type="BODY_MEDIUM_S" color={theme.colors.gray200}>
                  {vaultPositionData?.vaultName || "--"}
                </Typography>
                <OpenInNewIcon color={theme.colors.gray200} />
              </FlexContainer>
            </FlexContainer>
          )}
          <FlexContainer
            justifyContent="space-between"
            alignItems="center"
            width={100}
          >
            <Typography type="BODY_S" color={theme.colors.gray200}>
              Rebalance frequency
            </Typography>
            <Typography type="BODY_MEDIUM_S" color={theme.colors.gray200}>
              {frequencyItem?.label || "--"}
            </Typography>
          </FlexContainer>

          <FlexContainer justifyContent="space-between" width={100}>
            <Typography type="BODY_S" color={theme.colors.gray200}>
              Expected rebalance
            </Typography>
            <Typography type="BODY_MEDIUM_S" color={theme.colors.gray200}>
              {getFormattedDate(nextExecutionTime, {
                year: "numeric",
                month: "short",
                day: "numeric",
              })}
            </Typography>
          </FlexContainer>

          <FlexContainer justifyContent="space-between" width={100}>
            <Typography type="BODY_S" color={theme.colors.gray200}>
              Agent contract
            </Typography>
            <InfoLinkTag
              content={truncateString(subAccountAddress, 3, 3)}
              link={getBaseChainScanLink(subAccountAddress, chainId)}
              textToCopy={subAccountAddress}
            />
          </FlexContainer>
        </FlexContainer>
      </ContentWrapper>
    </GrayBoundaryBlackWrapper>
  )
}

function LoadingState({ asset, logo }: { logo: string; asset: string }) {
  const { theme } = useThemeContext()
  return (
    <GrayBoundaryBlackWrapper>
      <FlexContainer
        style={{ minHeight: "16.4rem" }}
        justifyContent="center"
        alignItems="center"
        flexDirection="column"
        gap={1.2}
        width={100}
        padding="4rem 0 2.8rem 0"
      >
        <FlexContainer justifyContent="center" width={100}>
          <span style={{ width: "19.5rem", height: "12.1rem" }}>
            <LottieReader loop animationData={MorphoScannerLottie} />
          </span>
        </FlexContainer>
        <FlexContainer gap={0.4} alignItems="center">
          <Typography type="BODY_M" color={theme.colors.gray400}>
            Withdrawing
          </Typography>
          <FlexContainer alignItems="center" gap={0.2} flex={false}>
            <LogoViewer logo={logo} />
            <Typography type="TITLE_S" color={theme.colors.gray100}>
              {asset}
            </Typography>
          </FlexContainer>

          <Typography type="BODY_M" color={theme.colors.gray400}>
            from Automation
          </Typography>
        </FlexContainer>
      </FlexContainer>
      <ContentWrapper>
        <FlexContainer width={100}>
          <TooltipIcon color={theme.colors.gray200} />
          <Typography type="BODY_S" color={theme.colors.gray200}>
            This can take up to 2 minutes for the transaction to settle.
          </Typography>
        </FlexContainer>
      </ContentWrapper>
    </GrayBoundaryBlackWrapper>
  )
}

function SucessState({
  asset,
  logo,
  txHash,
}: {
  logo: string
  asset: string
  txHash: string
}) {
  const { theme } = useThemeContext()
  return (
    <GrayBoundaryBlackWrapper>
      <FlexContainer
        style={{ minHeight: "16.4rem" }}
        justifyContent="center"
        alignItems="center"
        flexDirection="column"
        gap={1.2}
        width={100}
      >
        <FlexContainer
          flex={false}
          borderRadius={10}
          bgColor={theme.colors.success}
          borderColor={theme.colors.black}
          style={{ minHeight: "5.6rem", minWidth: "5.6rem" }}
          alignItems="center"
          justifyContent="center"
        >
          <TickIcon height={40} width={40} color={theme.colors.black} />
        </FlexContainer>

        <Typography type="TITLE_L" color={theme.colors.success}>
          Withdrawal Successful
        </Typography>
      </FlexContainer>
      <ContentWrapper>
        <FlexContainer justifyContent="space-between" width={100}>
          <Typography type="BODY_S" color={theme.colors.gray200}>
            Withdrawal Amount
          </Typography>
          <FlexContainer alignItems="center" gap={0.2} flex={false}>
            <LogoViewer logo={logo} />
            <Typography type="BODY_MEDIUM_S" color={theme.colors.gray200}>
              {asset}
            </Typography>
          </FlexContainer>
        </FlexContainer>

        <FlexContainer justifyContent="space-between" width={100}>
          <Typography type="BODY_S" color={theme.colors.gray200}>
            Transaction Hash
          </Typography>
          <InfoLinkTag
            content={truncateString(txHash, 3, 3)}
            link={getBaseChainScanLink(txHash, BASE_CHAIN_ID, "tx")}
            textToCopy={txHash}
          />
        </FlexContainer>
      </ContentWrapper>
    </GrayBoundaryBlackWrapper>
  )
}
