// useWithdraw.tsx
import { useCallback } from "react"
import { Address } from "brahma-console-kit"
import { useAccount, useWalletClient } from "wagmi"

import { dispatchToast } from "@/components/shared/components"
import { TAsset } from "@/types"
import useAutomationAgentStore from "../../store"
import { GNOSIS_SAFE_ABI } from "../../constants"
import { basePublicClient } from "../../utils"

type UseWithdrawProps = {
  targetToken: TAsset
  allocatedToken: TAsset
  subAccountAddress: Address
  closeExitModal?: () => void
}

const useWithdraw = ({
  targetToken,
  allocatedToken,
  subAccountAddress,
  closeExitModal,
}: UseWithdrawProps) => {
  const { address } = useAccount()
  const { data: signer } = useWalletClient()
  const { isWithdrawLoading, withdrawAmount } = useAutomationAgentStore()

  const handleWithdrawAmount = useCallback(async () => {
    if (!address || !signer) {
      dispatchToast({
        id: "error-missing-wallet",
        type: "error",
        title: "Wallet not connected",
        description: { value: "Please connect your wallet and try again." },
      })
      return
    }

    try {
      const readResponse = await basePublicClient.readContract({
        address: subAccountAddress,
        abi: GNOSIS_SAFE_ABI,
        functionName: "getModulesPaginated",
        args: ["0x0000000000000000000000000000000000000001", BigInt(2)],
      })

      const consoleAddress =
        readResponse.length > 0 &&
        readResponse[0].length > 1 &&
        readResponse[0][1]
          ? readResponse[0][1]
          : null

      if (!consoleAddress) {
        dispatchToast({
          id: "error-missing-console",
          type: "error",
          title: "Console Address Missing",
          description: {
            value:
              "Console address not found. Please ensure the console is properly set up.",
          },
        })
        return
      }

      await withdrawAmount(
        address,
        signer,
        subAccountAddress,
        consoleAddress,
        targetToken,
        allocatedToken,
        closeExitModal,
      )
    } catch (error: any) {
      dispatchToast({
        id: "withdraw-error",
        type: "error",
        title: "Withdrawal Failed",
        description: {
          value: error?.message || "An unexpected error occurred.",
        },
      })
    }
  }, [
    address,
    signer,
    subAccountAddress,
    targetToken,
    allocatedToken,
    closeExitModal,
    withdrawAmount,
  ])

  return { handleWithdrawAmount, isWithdrawLoading }
}

export default useWithdraw
