import { useMemo, useState } from "react"

import {
  FlexContainer,
  HrLine,
  LogoViewer,
  Typography,
} from "@/components/shared/components"
import TextWithTooltip from "@/components/shared/components/TextWithTooltip"
import { useThemeContext } from "@/providers/themeProvider"
import SliderComponent from "./SliderComponent"
import { formatAmountWithOptions } from "@/utils"
import { useIsMobile } from "@/hooks/use-is-mobile"

export type AmountSliderProps = {
  amount: string
  logo: string
  symbol: string
  assetPrice: number
  onMaxTradeAmountSet: (amount: number) => void
}

export default function AmountSlider({
  amount,
  logo,
  symbol,
  assetPrice,
  onMaxTradeAmountSet,
}: AmountSliderProps) {
  const { theme } = useThemeContext()
  const isMobile = useIsMobile()
  const parsedAmount = parseFloat(amount)
  const maxTradeSize = parsedAmount * 0.35

  const minTradeSize = useMemo(() => {
    const twoPercentOfAmount = parsedAmount * 0.02
    if (assetPrice === 0) return twoPercentOfAmount
    const twoDollarEquivalentAmount = 2 / assetPrice
    return Math.max(twoDollarEquivalentAmount, parsedAmount * 0.02) // max between $2 and 2% of total amount
  }, [assetPrice, parsedAmount])

  const minSliderValue = useMemo(() => {
    return (minTradeSize / maxTradeSize) * 100 // Convert to percentage (0-100)
  }, [minTradeSize, maxTradeSize])

  const [sliderValue, setSliderValue] = useState(100)

  const amountFromSlider = useMemo(() => {
    const sliderAmount = (sliderValue / 100) * maxTradeSize
    onMaxTradeAmountSet(sliderAmount)
    return sliderAmount
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sliderValue, maxTradeSize])
  // reason: onMaxTradeAmountSet causes infinite rerenders

  const handleSliderChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = Number(event.target.value)
    // Only allow values >= minSliderValue
    if (newValue >= minSliderValue) {
      setSliderValue(newValue)
    } else {
      setSliderValue(minSliderValue)
    }
  }

  const titleType = isMobile ? "TITLE_S" : "TITLE_L"
  return (
    <FlexContainer
      width={100}
      borderRadius={0.8}
      borderColor={theme.colors.gray700}
      flexDirection="column"
    >
      <FlexContainer
        padding="1.6rem 2rem"
        justifyContent="space-between"
        width={100}
      >
        <Typography type={titleType} color={theme.colors.gray200}>
          Allocated Amount
        </Typography>

        <FlexContainer flex={false} gap={0.8}>
          <LogoViewer size={28} logo={logo} />
          <TextWithTooltip
            text={formatAmountWithOptions(amount, {
              maximumFractionDigits: 6,
            })}
            tooltipText={
              assetPrice
                ? `$${formatAmountWithOptions(parsedAmount * assetPrice, {
                    maximumFractionDigits: 6,
                  })}`
                : undefined
            }
            type={titleType}
            color={theme.colors.gray200}
          />
        </FlexContainer>
      </FlexContainer>
      <HrLine />
      <FlexContainer
        padding="1.6rem 2rem"
        gap={1.6}
        width={100}
        flexDirection="column"
      >
        <FlexContainer
          padding="1.2rem 0"
          justifyContent="space-between"
          width={100}
        >
          <TextWithTooltip
            type={titleType}
            color={theme.colors.gray200}
            text={`Max Trade Size (${symbol})`}
            tooltipText="The maximum asset amount per trade, restricted to 50% of the total agent value."
          />
          <TextWithTooltip
            text={formatAmountWithOptions(amountFromSlider, {
              maximumFractionDigits: 6,
            })}
            tooltipText={
              assetPrice
                ? `$${formatAmountWithOptions(amountFromSlider * assetPrice)}`
                : undefined
            }
            type={titleType}
            color={theme.colors.gray200}
          />
        </FlexContainer>

        <FlexContainer width={100}>
          <SliderComponent
            sliderValue={sliderValue}
            minSliderValue={minSliderValue}
            handleSliderChange={handleSliderChange}
          />
        </FlexContainer>

        <FlexContainer justifyContent="space-between" width={100}>
          <TextWithTooltip
            type="TITLE_XS"
            color={theme.colors.gray400}
            text="Min Trade Size"
            tooltipText="The minimum threshold for agent to execute trades, depending on total agent size and duration."
          />
          <TextWithTooltip
            text={`${formatAmountWithOptions(minTradeSize, {
              maximumFractionDigits: 6,
            })} ${symbol}`}
            tooltipText={
              assetPrice ? `$${minTradeSize * assetPrice}` : undefined
            }
            type="TITLE_XS"
            color={theme.colors.gray400}
          />
        </FlexContainer>
      </FlexContainer>
    </FlexContainer>
  )
}
