import {useEffect, useState} from 'react'
import {Link} from 'react-router-dom'

import BreadcrumbCom from '../breadcrumb/BreadcrumbCom'
import TablePaginatedWrapper from '../tableWrapper/TablePaginatedWrapper'
import Icons from '../Icons'
import {getLoans} from '../../services/siteServices'
import getDateFromDateString from '../../helpers/GetDateFromDateString';
import Avatar from '../../assets/loans.png'
import RouteLinks from '../../RouteLinks';
import formatNumber from '../../helpers/formatNumber'

export default function LoansCom() {

    const [page, setPage] = useState(1)
    const [allLoans, setAllLoans] = useState({loading: true, error: '', data: {}})

    const [willFilter, setWillFilter] = useState(false)
    const [filter, setFilter] = useState({type: '', id: ''})
    const handleFilter = ({target: {name, value}}) => {
        setFilter(prev => ({...prev, [name]: value}))
    }

    const handleFilterByParams = () => {
        if (filter.type && !filter.id) {
            return
        } else if (!filter.type) {
            setPage(1)
            setWillFilter(prev => !prev)
            setFilter({type: '', id: ''})
        } else {
            setPage(1)
            setWillFilter(prev => !prev)
        }
    }

    const loans = allLoans?.data?.loans // LOANS LIST
    const pagination = allLoans?.data?.pagination
    const isFetching = allLoans?.loading
    const isError = allLoans?.error

    useEffect(() => {
        setAllLoans(prev => ({...prev, loading: true}))
        const payload = filter?.type ? {[filter?.type]: filter.id} : {}
        getLoans({...payload, page}).then(res => {
            if (res?.status != 200) {
                setAllLoans(prev => ({...prev, loading: false}))
                return
            }
            setAllLoans({loading: false, error: '', data: res?.data})
        }).catch(err => {
            setAllLoans({loading: false, error: 'error occurred', data: {}})
            console.log('ERR', err)
        })
    }, [page, willFilter])

    return (
        <div className='w-full flex flex-col gap-8'>
            <BreadcrumbCom title='Loans' paths={['Dashboard', 'Loans']}/>

            <div className='box bg-white dark:bg-black-box text-black-body dark:text-white-body'>
                {isError ?
                    <p className='text-red-500'>{allLoans?.error}</p>
                    :
                    <>
                        {/* filter section */}
                        <div className='px-2 py-2 mb-4 flex flex-col sm:flex-row flex-wrap sm:items-center gap-2'>
                            <Icons name='filter' className='text-3xl'/>
                            <div className='w-full sm:max-w-48'>
                                <select name='type' value={filter?.type} className='h-10 w-full p-2 rounded-md'
                                        onChange={handleFilter}>
                                    <option value=''>All</option>
                                    <option value='transaction_id'>Transaction ID</option>
                                    <option value='account_id'>Account ID</option>
                                </select>
                            </div>
                            <div className='w-full sm:max-w-48'>
                                <input name='id' value={filter?.id} disabled={!filter.type}
                                       className={`h-10 w-full p-2 rounded-md outline-none border border-black-aside ${!filter.type && 'opacity-30'}`}
                                       onChange={handleFilter}/>
                            </div>
                            <button onClick={handleFilterByParams} disabled={filter.type && !filter.id}
                                    className={`h-10 bg-primary px-2 py-1 rounded-md text-white font-medium sm:self-end ${(filter.type && !filter.id) && 'opacity-50'}`}>Submit
                            </button>
                        </div>
                        {/* end of filter section */}

                        <TablePaginatedWrapper data={loans} isFetching={isFetching} setPage={setPage}
                                               itemsPerPage={pagination?.limit} pagination={pagination}>
                            {({data}) => (
                                <>
                                    <table className="table-auto py-2 w-full text-sm">
                                        <thead className="py-2 text-sm text-slate-500 text-left">
                                        <tr>
                                            <th scope="col" className="px-2 py-2">
                                                Name
                                            </th>
                                            <th scope="col" className="px-2 text-right">
                                                Loan Amount
                                            </th>
                                            <th scope="col" className="px-2 text-right">
                                                Product/Tenor
                                            </th>
                                            <th scope="col" className="px-2 text-right">
                                                Repay/Install Amount
                                            </th>
                                            <th scope="col" className="px-2 text-right">
                                                Added
                                            </th>
                                            <th scope="col" className="px-2 text-right">
                                                Action
                                            </th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        {(data && data.length > 0) ? data?.map((item, index) => (
                                                <tr key={index} className="py-2 border-t border-dashed border-slate-300">
                                                    <td className="px-2 py-2">
                                                        <div
                                                            className='w-full min-w-48 flex items-center gap-2 whitespace-nowrap'>
                                                            <img className="w-10 h-10 rounded-md" src={Avatar}
                                                                 alt="Jese image"/>
                                                            <div className="text-left">
                                                                <div
                                                                    className="text-base font-semibold">{item?.account_id || ''}</div>
                                                                <div
                                                                    className="font-normal text-gray-500">{item?.id} : {item?.transaction_id}</div>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td className="px-2">
                                                        <div className="text-right">
                                                            {/* <div className="text-base font-semibold">{formatNumber(item?.initial_loan_amount)}</div> */}
                                                            <div
                                                                className="font-semibold text-green-500">#{formatNumber(item?.initial_loan_amount)}</div>
                                                        </div>
                                                    </td>
                                                    <td className="px-2">
                                                        <div className="text-right">
                                                            <div
                                                                className="font-normal text-gray-500">{formatNumber(item?.product_id)}</div>
                                                            <div className="font-normal text-red-500">{item?.tenor} days
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td className="px-2">
                                                        <div className="text-right">
                                                            <div
                                                                className="font-normal text-gray-500">{formatNumber(item?.repayment_amount)}</div>
                                                            <div
                                                                className="font-normal text-gray-500">{formatNumber(item?.installment_amount)}</div>
                                                        </div>
                                                    </td>
                                                    <td className="px-2">
                                                        <div className="text-right">
                                                            <div
                                                                className="font-normal text-gray-500">{getDateFromDateString(item?.created_at)}</div>
                                                        </div>
                                                    </td>
                                                    <td className="px-2 text-right">
                                                        <div className='flex items-center justify-end gap-3 md:gap-4'>
                                                            <div
                                                                className='p-2 flex justify-center items-center text-slate-500 bg-white-body dark:text-white-body dark:bg-black-body rounded-md'>
                                                                <Link to={RouteLinks.transaction_details_page}
                                                                      state={{transactionID: item?.transaction_id}}>
                                                                    <Icons name='eye'/>
                                                                </Link>
                                                            </div>
                                                        </div>
                                                    </td>
                                                </tr>
                                            ))
                                            :
                                            <tr className="py-2 border-t border-dashed border-slate-300">
                                                <td className="px-3 py-2" colSpan={6}>
                                                    <div className="flex justify-center items-center">
                                                        No Record Found
                                                    </div>
                                                </td>
                                            </tr>
                                        }
                                        </tbody>
                                    </table>
                                </>
                            )}
                        </TablePaginatedWrapper>
                    </>
                }
            </div>
        </div>
    )
}