import React, { useEffect, useState } from 'react'
import { useLocation, useNavigate, Link } from 'react-router-dom'
import { useQuery } from "@tanstack/react-query";

import { IoIosArrowBack, IoIosArrowForward } from "react-icons/io";

import myLinks from '../myLinks'
import queryKeys from '../services/queryKeys';
import { getProducts } from '../services/siteServices';
import Pin from './loan_screen/Pin';
import Offers from './loan_screen/Offers';
import LoanPin from './loan_screen/LoanPin';
import SelectedOffer from './loan_screen/SelectedOffer';
import GetLoan from './loan_screen/GetLoan';
import TermsAndConditions from './loan_screen/TermsAndConditions';
import LoanDetails from './loan_screen/LoanDetails';

export default function GetLoanScreens() {

  let screens = {
    products: 'products-screen',
    terms_conditions: 'terms_conditions',
    getLoan: 'get-loan',
    pin: 'pin-screen',
    loan_details: 'loan_details',
    offers: 'offers-screen',
    selected_offer: 'selected-offer-screen',
    loan_pin: 'loan-pin-screen'
  }
  
  const {state} = useLocation()
  const navigate = useNavigate()

  const [step, setStep] = useState({
    details: {},
    screen: [],
    activeUser: state.user
  })

  const handleStep = (detailsToAdd, screen) => {
    setStep(prev => ({...prev, details: {...prev.details, ...detailsToAdd}, screen: [...prev.screen, screen]}))
  }

  const {data, isFetching, isError, error} = useQuery({
      queryKey: queryKeys.products,
      queryFn: () => getProducts()
  })

  const products = data?.data?.product_data?.products // PRODUCTS LIST

  const handleBackBtn = () => {
    if(step?.screen?.length <= 0 || step?.screen[step.screen.length -1 ] == screens.loan_pin){
      setStep({details: {}, screen: []})
      return navigate(myLinks.home, {state:{proceed:'true'}})
    }
    setStep(prev => ({...prev, screen: prev.screen.slice(0, -1)}))
  }

  useEffect(()=>{
    if(!state?.user){
      return navigate(myLinks.getStarted, {replace:true})
    }
  },[])

  return (
    <div className={`flex flex-col items-center justify-center`}>
        <div className='relative flex flex-col gap-4 w-[80%] sm:w-[400px] h-[600px] bg-white rounded-xl p-4 sm:p-8 shadow'>
            <div className="relative pb-3 card-title w-full border-b-2 flex gap-4 items-center">
              <div className='absolute left-2 top-1/2 -translate-y-1/2 p-1 cursor-pointer' onClick={handleBackBtn}>
                <IoIosArrowBack className='text-3xl sm:text-5xl font-bold text-orange-500 cursor-pointer' />
              </div>
              <div className='w-full text-center'>
                <h1 className="mb-[1px] text-2xl font-bold">{state?.user.name}</h1>
                <span className={`text-base font-bold p-1 rounded`}>BVN: {state?.user.bvn}</span>
              </div>
            </div>
            {!step?.screen?.length || step?.screen[step.screen.length -1 ] == screens.products ?
              <>
                <div className='mt-3 flex flex-col gap-3'>
                  {isFetching ? 
                    <>
                        <div className="w-full py-4">
                          <p className='text-slate-800 text-center'>Loading...</p>
                        </div>
                    </>
                    : isError ?
                    <div className="w-full py-4">
                      <p className='text-red-500 text-center'>{error.message}</p>
                    </div>
                    :
                    <>
                      {products && products.map(product => {
                        let isDisabled = product.active == '0' ? true : false
                        return (
                          <button 
                            key={product?.cid} 
                            disabled={isDisabled} 
                            onClick={()=>handleStep(product, screens.getLoan)} 
                            className={`w-full flex gap-2 justify-between items-center p-2 bg-purple-800 text-base sm:text-xl text-white font-bold rounded ${isDisabled && 'opacity-50'}`} 
                          >
                            <span>{product?.description}</span>
                            <IoIosArrowForward />
                          </button>
                        )
                      }
                      )}
                    </>
                  }
                  {/* <button 
                      onClick={()=>handleStep({}, screens.getLoan)} 
                      className={`w-full flex gap-2 justify-between items-center p-2 bg-purple-800 text-base sm:text-xl text-white font-bold rounded`} 
                    >
                      <span>{'product?.description'}</span>
                      <IoIosArrowForward />
                    </button> */}
                </div>
                {/* {products &&
                <div className='mt-3 w-full h-full flex flex-col justify-end'>
                  <button onClick={()=>console.log('working')} className='w-full p-3 bg-orange-500 text-lg sm:text-2xl text-white font-bold rounded'>Pay Loan</button>
                </div>
                } */}
              </>
              : step?.screen[step.screen.length -1 ] == screens.getLoan ?
              <>
                <GetLoan step={step} handleStep={handleStep} screens={screens} />
              </>
              :step?.screen[step.screen.length -1 ] == screens.terms_conditions ?
              <>
                <TermsAndConditions step={step} handleStep={handleStep} screens={screens} />
              </>
              :step?.screen[step.screen.length -1 ] == screens.pin ?
              <>
                <Pin step={step} handleStep={handleStep} screens={screens} />
              </>
              : step?.screen[step.screen.length -1 ] == screens.offers ?
              <>
                <Offers step={step} handleStep={handleStep} screens={screens} />
              </>
              : step?.screen[step.screen.length -1 ] == screens.selected_offer ?
              <>
                <SelectedOffer step={step} handleStep={handleStep} screens={screens} />
              </>
              :  step?.screen[step.screen.length -1 ] == screens.loan_details?
              <>
                <LoanDetails step={step} handleStep={handleStep} screens={screens} />
              </>
              :step?.screen[step.screen.length -1 ] == screens.loan_pin ?
              <>
                <LoanPin step={step} handleStep={handleStep} screens={screens} />
              </>
              : null
            }

            <div className='absolute left-0 bottom-1 w-full flex justify-center items-center'>
              <Link to={myLinks.home} className='font-semibold text-center border-b border-transparent hover:border-purple-400'>Back to <span className='text-purple-400 '>Home</span></Link>
            </div>


        </div>
    </div>
  )
}
