import React, { useRef, useState } from 'react'
import { View } from 'react-native'
import { AddTopUp } from './component/'
import { Header, Button } from '../../../commonComponents'
import styles from './styles'
import { useSelector, useDispatch } from 'react-redux'
import {
  walletData,
  withdrawData,
  withdrawRequestData,
} from '../../../api/store/action'
import { notificationHelper } from '../../../commonComponents'
import appColors from '../../../theme/appColors'
import { WithdrawDataInterface } from '../../../api/interface/walletInterface'
import { useNavigation } from '@react-navigation/native'
import { AppDispatch } from '../../../api/store'

export function TopupWallet() {
  const { translateData } = useSelector((state: any) => state.setting)
  const dispatch = useDispatch<AppDispatch>()
  const { selfDriver } = useSelector((state: any) => state.account)
  const [loader, setLoader] = useState<boolean>(false)
  const navigation = useNavigation()
  const formRef = useRef<{
    getValues: () => { withdrawAmount: string; description: string }
  }>(null)

  const handleWithdraw = async () => {
    if (!formRef.current) return

    if (
      selfDriver?.payment_account?.default === null ||
      selfDriver?.payment_account?.default === undefined
    ) {
      notificationHelper(
        '',
        translateData?.bankdetailseer,
        'error',
      )
      return
    }

    const { withdrawAmount, description } = formRef.current.getValues()
    setLoader(true)
    let payload: WithdrawDataInterface | any = {
      amount: Number(withdrawAmount),
      message: description,
      payment_type: selfDriver?.payment_account?.default,
    }

    dispatch(withdrawData(payload))
      .unwrap()
      .then((res: any) => {
        setLoader(false)
        if (['success', 'pending', 'completed'].includes(res.status)) {
          setLoader(false)
          dispatch(walletData())
          dispatch(withdrawRequestData())
          notificationHelper('', translateData.withdrawSuccessful, 'success')
          navigation.goBack()
        } else {
          setLoader(false)
          notificationHelper(
            '',
            res.message || translateData.somethingwentwrong,
            'error',
          )
        }
      })
      .catch(error => {
        setLoader(false)
      })
  }

  return (
    <View style={styles.main}>
      <Header title={translateData.topupWallet} />

      <View style={styles.listView}>
        <AddTopUp ref={formRef} />
      </View>

      <View style={styles.button}>
        <Button
          backgroundColor={appColors.primary}
          color={appColors.white}
          title={translateData.addTopupBalance}
          margin={0}
          onPress={handleWithdraw}
          loading={loader}
        />
      </View>
    </View>
  )
}
