// type AutomationHistoryItemsViewProps = {}

import AutomationHistoryItem from "../AutomationHistoryItem"
import { FlexContainer, Typography } from "@/components/shared/components"
import { AutomationAgentSubscription } from "../../types"
import { formatAmountWithOptions, formatUnits } from "@/utils"
import { useThemeContext } from "@/providers/themeProvider"
import useConfigStore from "@/components/shared/store"
import { Address } from "@/components/shared/types"
import { lowercaseKeys } from "../../utils"

type AutomationHistoryItemsViewProps = {
  automations: AutomationAgentSubscription[]
  automationsLoading: boolean
}

export default function AutomationHistoryItemsView({
  automations,
  automationsLoading,
}: AutomationHistoryItemsViewProps) {
  const { theme } = useThemeContext()
  const { assets } = useConfigStore()

  if (automationsLoading)
    return (
      <FlexContainer
        width={100}
        justifyContent="center"
        style={{ maxWidth: "56rem" }}
      >
        <Typography type="BODY_MEDIUM_M" color={theme.colors.gray600}>
          Loading ...
        </Typography>
      </FlexContainer>
    )

  if (!automations.length)
    return (
      <FlexContainer
        width={100}
        justifyContent="center"
        style={{ maxWidth: "56rem" }}
      >
        <Typography type="BODY_MEDIUM_M" color={theme.colors.gray600}>
          No Agentic Transactions found
        </Typography>
      </FlexContainer>
    )

  const sortedAutomations = automations.sort((a, b) => {
    return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
  })

  return (
    <FlexContainer
      gap={8}
      width={100}
      style={{ maxWidth: "56rem" }}
      flexDirection="column"
    >
      {sortedAutomations.map((automation) => {
        const {
          id,
          subAccountAddress,
          tokenLimits,
          feeAmount,
          status,
          createdAt,
          metadata: {
            perIterationAmountMin,
            buyToken: buyTokenAddress,
            orderType,
            sellToken: sellTokenAddress,
            totalAmountIn,
            duration: durationInSeconds,
          },
        } = automation

        const totalDurationInHours = formatAmountWithOptions(
          parseFloat(durationInSeconds ?? "0") / 3600,
          {
            maximumFractionDigits: 2,
          },
        )

        const targetToken = assets.find(
          (_asset) =>
            _asset.address.toLowerCase() === buyTokenAddress.toLowerCase(),
        )

        const allocatedToken = assets.find(
          (_asset) =>
            _asset.address.toLowerCase() === sellTokenAddress.toLowerCase(),
        )

        if (!targetToken || !allocatedToken) {
          console.log("Token not found, returning null")
          return null
        }

        const maxAllocatedAmount = parseFloat(
          formatUnits(totalAmountIn, allocatedToken.decimals),
        ).toFixed(8)

        const formattedTokenLimit = lowercaseKeys(tokenLimits)
        const maxPerTradeAmount = parseFloat(
          formattedTokenLimit[
            (allocatedToken.address || "").toLowerCase() as Address
          ],
        ).toFixed(8)
        const minPerTradeAmount = perIterationAmountMin ?? "0"

        const fees = formatUnits(feeAmount, allocatedToken.decimals)

        const variant = orderType === "BUY" ? "SURGE" : "PURGE"

        return (
          <AutomationHistoryItem
            key={id}
            automationType={status === 2 ? "ACTIVE" : "HISTORY"}
            variant={variant}
            automationId={id}
            createdAt={createdAt}
            targetToken={targetToken}
            allocatedToken={allocatedToken}
            maxAllocatedAmount={maxAllocatedAmount}
            maxPerTradeAmount={maxPerTradeAmount}
            minPerTradeAmount={minPerTradeAmount}
            subAccountAddress={subAccountAddress}
            totalDuration={totalDurationInHours}
            feeAmount={fees}
          />
        )
      })}
    </FlexContainer>
  )
}
