import React, { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import Label from '../../Label'
import InputText from '../../InputText'
import { repayLoan } from '../../../services/siteServices'

export default function PinRepayment({step, handleStep, screens}) {

    console.log('step', step.activeUser, step.details)

    const [isSuccess, setIsSuccess] = useState(false)

    const [error, setError] = useState('')

    const [pin, setPin] = useState('')

    const handlePinChange = ({target:{value}}) => {
        setError('')
        setPin(value)
    }

    const proceed = useMutation({
        mutationFn: () => {
            let fields = {pin, loan_id:step.details.selected_loan_id, customerID:step.activeUser.customerid}
            if(!fields.pin){
                throw ({message:'Please enter pin'})
            }

            if(fields.pin.length != 4){
                throw ({message:'Pin must be 4 digits'})
            }
            return repayLoan(fields)
        },
        onError: (error) => {
            setError(error.message)
            setTimeout(()=>{setError('')},3000)
        },
        onSuccess: (res) => {
            setIsSuccess(true)
            handleStep({...step}, screens.finished)
        }
    })

    return (
        <>
        {!isSuccess ?
            <div className='mt-3 flex flex-col gap-4'>
                <div className='text-input font-semibold w-full flex flex-col gap-4 justify-center items-center'>
                    <p className='text-center text-base md:text-xl'>{`Your loan amount due is ${step.details.selectedAmount}`}</p>
                    <Label name='Enter your 4 Digit pin' htmlfor='pin' />
                    <InputText id='pin' name='pin' type='text' value={pin} handleChange={handlePinChange} />
                    <button onClick={()=>{proceed.mutate()}} disabled={proceed.isPending} className='p-3 bg-purple-800 text-base sm:text-xl text-white font-bold rounded'>{proceed.isPending ? 'loading...' : 'Continue'}</button>
                </div>
            </div>
        :
            <div className='mt-3 flex flex-col gap-4'>
                <div className='text-input font-semibold w-full flex flex-col gap-4 justify-center items-center'>
                    <p className='text-center text-base md:text-xl'>Your loan repayment is being processed. You will receive a confirmation SMS shortly.</p>
                </div>
            </div>
        }

        {error &&
        <>
            <div className="w-full text-center p-2">
            <p className='text-red-500 text-sm'>{error}</p>
        </div>
        </>
        }

        </>
    )
}
