import React, {useEffect, useState} from 'react'
import { Link } from 'react-router-dom'
import RecentActivityTable from './WalletComponent/RecentActivityTable'
import LoadingSpinner from '../Spinners/LoadingSpinner'

import usersService from '../../services/UsersService'

function TransferFund({payment, wallet}) {
    const apiCall = new usersService()

    let [newFee, setNewFee] = useState(false)

    let [recepients, setRecipients] = useState({ // FOR COUPON HISTORY
        loading: true,
        data: [],
        error: false
    })

    let [sendMoneyFee, setSendMoneyFee] = useState({fee: 0, total: 0}) // HOLD THE VALUE FOR SEND MONEY FEE

    //STATE FOR CONTROLLED INPUTS
    let [inputs, setInputs] = useState({
        amount: '0',
        recipient: '',
        comment: ''
    })

    //FUNCTION TO GET RECIPIENT LIST
    const getRecipients = ()=>{
        apiCall.getRecipient().then((res)=>{
            if(res.data.internal_return < 0){ // success but no data
                setRecipients(prev => ({...prev, loading: false}))
                return
            }
            setRecipients(prev => ({...prev, loading: false, data: res.data.result_list}))
        }).catch((error)=>{
            setRecipients(prev => ({...prev, loading: false, error: true}))
        })
    }

    //FUNCTION TO GET SEND MONEY FEE
    const getSendMoneyFee = ()=>{
        let {amount} = inputs
        if(Number(amount) <= 0 || amount=='' || isNaN(amount)){
            setSendMoneyFee({fee: 0, total: 0})
            return
        }
        apiCall.getSendMoneyFee(Number(amount)).then((res)=>{
            setSendMoneyFee({fee: res.data.processing_fee, total: res.data.total_amount})
        }).catch((error)=>{
            setSendMoneyFee({fee: 0, total: 0})
        })
    }


    // FUNCTION TO HANDLE INPUT CHANGE
    const handleChange = ({target:{name, value}}) => {
        setInputs(prev => ({...prev, [name]:value}))
    }

    //FUNCTION TO HANDLE SUBMIT
    const handleSubmit = (e) => {
        e.preventDefault();

        //valid inputs before submitting. Just for texting remove later. check amoutn to be number
    
        setInputs({
            amount: '0',
            recipient: '',
            comment: ''
        })
    }

    useEffect(()=>{
        getRecipients()
        getSendMoneyFee()
    },[newFee])
    return (
        <div className="content-wrapper w-full lg:flex xl:space-x-8 lg:space-x-4 bottomMargin">
            <div className="lg:w-1/2 w-full mb-10 lg:mb-0">
                <div className="add-fund w-full md:p-8 p-4 bg-white dark:bg-dark-white rounded-2xl shadow">
                   <form className='transfer-fund-info' onSubmit={handleSubmit}>
                        {wallet.loading ?
                        <LoadingSpinner size='8' color='sky-blue' />
                        :
                        wallet.data.length ? 
                        <h2 className='my-4 py-2 text-slate-900 dark:text-white text-xl lg:text-2xl font-medium'>
                        {wallet.data.map(item => {
                            if(item.description == 'Naira'){
                                return `Withdraw from Naira Wallet : ${item.symbol}${(item.amount*1).toFixed(2)}`
                            }
                        })}
                        </h2>
                        :
                        wallet.error ? 
                        <h2 className='my-4 py-2 text-slate-900 dark:text-white text-xl lg:text-2xl font-medium'>Opps! An Error Occured</h2>
                        :
                        <h2 className='my-4 py-2 text-slate-900 dark:text-white text-xl lg:text-2xl font-medium'>No Wallet Information Found!</h2>
                        }
                        <div className='my-3 md:flex items-center justify-between space-x-2'>
                            <div className='transfer-input w-full md:w-1/2'>
                                <label className='w-full text-slate-600 text-lg'>Amount <span className='text-red-500'>*</span></label>
                                <input className='w-full p-3 text-lg text-right bg-slate-100 rounded-md outline-0 placeholder:text-slate-500 placeholder:text-lg' 
                                    value={inputs.amount} 
                                    name='amount' 
                                    type="text" 
                                    placeholder='Amount' 
                                    required
                                    onChange={handleChange}
                                    onMouseEnter={()=>{setNewFee(false)}}
                                    onMouseLeave={()=>{setNewFee(true)}}
                                    />
                            </div>
                            <div className='transfer-input w-full md:w-1/2'>
                                <label className='w-full text-slate-600 text-lg'>Fee <span className='text-red-500'>*</span></label>
                                <input className='w-full p-3 text-lg text-right bg-slate-100 opacity-50 rounded-md outline-0 placeholder:text-slate-500 placeholder:text-lg' 
                                    value={sendMoneyFee.fee} 
                                    name='fee' 
                                    type="text" 
                                    placeholder='Fee' 
                                    required
                                    disabled
                                    />
                            </div>
                        </div>

                        <div className='my-3 md:flex items-center justify-end space-x-2'>
                            <div className='transfer-input w-full md:w-1/2'>
                                <label className='w-full text-slate-600 text-lg'>Total <span className='text-red-500'>*</span></label>
                                <input className='w-full p-3 text-lg text-right bg-slate-100 opacity-50 rounded-md outline-0 placeholder:text-slate-500 placeholder:text-lg' 
                                    value={sendMoneyFee.total} 
                                    name='total' 
                                    type="text" 
                                    placeholder='Total' 
                                    required
                                    disabled
                                    />
                            </div>
                        </div>

                        <div className='relative my-3 md:flex items-center'>
                            <div className='transfer-input w-full'>
                                <div className='flex items-center justify-start'>
                                    <label className='text-slate-600 text-lg'>Recipient 
                                        <span className='text-red-500 mx-2'>*</span> 
                                        <span title='Transfer Recipient' className={`text-white text-sm bg-slate-500 w-1 h-1 rounded-full px-3 py-1 cursor-pointer`}>!</span>
                                    </label>
                                    <Link to='add-recipient' className='mx-1 text-base text-white p-3 bg-[orange] rounded-md hover:opacity-80'>Add New</Link>
                                </div>
                                <select className='mt-2 w-full p-3 text-lg bg-white rounded-md border border-slate-300 outline-0' value={inputs.recipient} name='recipient' onChange={handleChange}>
                                    {recepients.loading ?
                                     <option className='text-slate-500 text-lg' value="">Loading...</option>
                                     :
                                     recepients.data.length ?
                                     <> 
                                     <option className='text-slate-500 text-lg' value="">Select...</option>
                                     {recepients.data.map((item, index)=>(
                                        <option key={index} value={item.account_no} className='text-slate-500 text-lg'>{item.recipient}</option>
                                     ))}
                                     </>
                                     :
                                     recepients.error ?
                                     <option className='text-slate-500 text-lg' value="">Could'nt Load, try again!</option>
                                     :
                                     <option className='text-slate-500 text-lg' value="">No Recipient Found! Click Add to Add</option>
                                    }
                                </select>
                            </div>
                        </div>

                        <div className='my-3 md:flex items-center'>
                            <div className='transfer-input w-full'>
                                <label className='w-full text-slate-600 text-lg'>Comment <span className='text-red-500'>*</span></label>
                                <input className='w-full p-3 text-lg bg-slate-100 rounded-md outline-0 placeholder:text-slate-500 placeholder:text-lg' 
                                    value={inputs.comment} 
                                    name='comment' 
                                    type="text" 
                                    placeholder='Comment' 
                                    required
                                    onChange={handleChange}
                                    />
                            </div>
                        </div>

                        <div className='transfer-fund-btn flex justify-end items-center py-4'>
                            <button className='text-lg text-white bg-sky-blue px-4 py-2 hover:opacity-90 rounded-md'>Continue</button>
                        </div>
                   </form>
                </div>
            </div>
    
            <div className="lg:w-1/2 w-full mb-10 lg:mb-0">
                <div className="wallet w-full  md:p-8 p-4 h-full max-h-[600px] bg-white dark:bg-dark-white overflow-y-auto rounded-2xl shadow">
                    <h2 className='text-slate-900 dark:text-white text-xl lg:text-2xl font-medium'>Recent Activity</h2>
                    <p className='text-base text-slate-500 dark:text-white'>Activity Report</p>
                    {payment.loading ?
                    <LoadingSpinner size='16' color='sky-blue' />
                    :
                    <RecentActivityTable  payment={payment}/>
                    }
                </div>
            </div>
        </div>
      )
}

export default TransferFund