import { useCallback, useEffect } from "react"

import {
  ActionIconWrapper,
  Button,
  ContentWrapper,
  CustomInput,
  FlexContainer,
  GrayBoundaryBlackWrapper,
  TooltipBox,
  Typography,
} from "@/components/shared/components"
import SlideInAnimationWrapper from "@/components/shared/components/SlideInAnimationWrapper"
import { TooltipIcon } from "@/icons"
import SendIcon from "@/icons/SendIcon"
import { useThemeContext } from "@/providers/themeProvider"
import { isNotZero } from "@/utils"

import { ChatMessage } from "../../hooks/useAiChat"
import ChatLayout from "../ChatLayout"
import ClaimBrahmaBadgeCard from "@/icons/ClaimBrahmaBadgeCard"
import { Address } from "@/components/shared/types"
import ExploreBrahmaAccountModal from "../../ExploreBrahmaAccountModal"
import useBoolean from "@/hooks/useBoolean"

type AiLayoutProps = {
  topSlot: React.ReactNode
  buttonText: string
  buttonDisabled: boolean
  buttonAction: () => void
  handleSubmit: (customInput?: string) => void
  messages: ChatMessage[]
  input: string
  setInput: (input: string) => void
  isChatDisabled: boolean
  loading?: boolean
  hideChat?: boolean
  actionButtonInfo?: string
  buttonTooltip?: string
  tokenAmount: string
  consoleAddress?: Address | null
}

export default function AiLayout({
  topSlot,
  buttonText,
  buttonAction,
  buttonDisabled,
  handleSubmit,
  messages,
  input,
  setInput,
  isChatDisabled,
  hideChat = false,
  actionButtonInfo,
  buttonTooltip = "",
  loading,
  tokenAmount,
  consoleAddress,
}: AiLayoutProps) {
  const { theme } = useThemeContext()
  const {
    setTrue: openExploreModal,
    setFalse: closeExploreModal,
    value: isExploreModalOpen,
  } = useBoolean()
  const submitUserInput = useCallback(() => {
    if (isChatDisabled) return
    handleSubmit()
  }, [isChatDisabled, handleSubmit])

  useEffect(() => {
    const handleKeyPress = (event: KeyboardEvent) => {
      if (event.key === "Enter") {
        submitUserInput()
      }
    }
    window.addEventListener("keydown", handleKeyPress)
    return () => {
      window.removeEventListener("keydown", handleKeyPress)
    }
  }, [submitUserInput])

  const submitUserChoicePrompts = useCallback(
    (customInput?: string) => {
      if (loading) return
      handleSubmit(customInput)
    },
    [loading, handleSubmit],
  )

  const isFirstMessage = messages.length === 1
  const isExploreBrahmaAccountModalOpen = consoleAddress && isExploreModalOpen
  return (
    <>
      {isExploreBrahmaAccountModalOpen && (
        <ExploreBrahmaAccountModal
          consoleAddress={consoleAddress}
          closeModal={closeExploreModal}
        />
      )}
      <FlexContainer
        flexDirection="column"
        gap={3.2}
        width={100}
        justifyContent="center"
      >
        <GrayBoundaryBlackWrapper>
          {topSlot}
          {!hideChat && (
            <>
              <ContentWrapper padding="0.4rem">
                <ChatLayout
                  loading={!!loading}
                  messages={messages}
                  onChoicePromptClick={(prompt) =>
                    submitUserChoicePrompts(prompt)
                  }
                />
              </ContentWrapper>
              <ContentWrapper padding="1.2rem">
                <CustomInput
                  accentColor="white"
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  placeholder={
                    isNotZero(tokenAmount) && isFirstMessage
                      ? "Click “I want to deposit” to set up your agent."
                      : "Enter a deposit amount to get started"
                  }
                  disabled={isChatDisabled}
                  icon={
                    <ActionIconWrapper
                      size="M"
                      disabled={isChatDisabled}
                      onClick={() => submitUserInput()}
                    >
                      {loading ? (
                        <FlexContainer
                          padding="0.4rem"
                          borderRadius={10}
                          flex={false}
                          borderColor={theme.colors.gray500}
                        >
                          <FlexContainer
                            borderRadius={0.2}
                            flex={false}
                            bgColor={theme.colors.gray500}
                            style={{
                              minHeight: "1rem",
                              minWidth: "1rem",
                            }}
                          />
                        </FlexContainer>
                      ) : (
                        <SendIcon />
                      )}
                    </ActionIconWrapper>
                  }
                />
              </ContentWrapper>
            </>
          )}

          <ContentWrapper padding="0.8rem">
            {buttonTooltip ? (
              <TooltipBox content={buttonTooltip}>
                <Button
                  disabled={buttonDisabled}
                  buttonSize="L"
                  onClick={buttonAction}
                  buttonType="white"
                >
                  {buttonText}
                </Button>
              </TooltipBox>
            ) : (
              <Button
                disabled={buttonDisabled}
                buttonSize="L"
                onClick={buttonAction}
                buttonType="white"
              >
                {buttonText}
              </Button>
            )}
          </ContentWrapper>

          {actionButtonInfo && (
            <SlideInAnimationWrapper
              key={actionButtonInfo}
              direction="left"
              width={100}
            >
              <FlexContainer
                justifyContent="center"
                padding="0.8rem"
                width={100}
                alignItems="center"
              >
                <TooltipIcon color={theme.colors.gray100} />
                <Typography color={theme.colors.gray100} type="BODY_MEDIUM_XS">
                  {actionButtonInfo}
                </Typography>
              </FlexContainer>
            </SlideInAnimationWrapper>
          )}
        </GrayBoundaryBlackWrapper>

        {consoleAddress && (
          <GrayBoundaryBlackWrapper>
            <ContentWrapper padding="0.4rem 0.4rem 1.2rem 0.4rem">
              <FlexContainer gap={0.8} flexDirection="column">
                <ClaimBrahmaBadgeCard />
                <Typography
                  style={{ padding: "0 0.8rem" }}
                  type="BODY_MEDIUM_S"
                  color={theme.colors.gray400}
                >
                  You received a Badge & additional rewards on your Brahma
                  Account for activating Morpho Agent.
                </Typography>
              </FlexContainer>
            </ContentWrapper>
            <ContentWrapper padding="0.8rem">
              <Button
                onClick={openExploreModal}
                buttonSize="L"
                buttonType="white"
              >
                Explore Brahma Rewards
              </Button>
            </ContentWrapper>
          </GrayBoundaryBlackWrapper>
        )}
        {/* <InformationBar accent="warning">
        AI is not AGI (Yet), Please be direct with the prompts. You can
        customise APY, Curators, rebalancing and Liquidity.
      </InformationBar> */}
      </FlexContainer>
    </>
  )
}
