import { useState, useEffect, useRef, useContext } from 'react';
import BudgetPeriodTransTable from './BudgetPeriodTransTable';
import Lock from '../resources/Lock.svg';
import OpenLock from '../resources/OpenLock.svg';
import './BudgetPeriodCard.scss';
import { BudgetContext } from '../data/context/BudgetContext';

const BudgetPeriodCard = ({periodData, isActive}) => {
    const cardRef = useRef(),
        context = useContext(BudgetContext),
        [bankBalance, setBankBalance] = useState(0),
        [projectedLeftover, setProjectedLeftover] = useState(0),
        paidBills = periodData.bills.filter((bill) => bill.paid),
        unpaidBills = periodData.bills.filter((bill) => !bill.paid),
        [incomes, setIncomes] = useState(periodData.income),
        [paidIncomes, setPaidIncomes] = useState([]),
        [unpaidIncomes, setUnpaidIncomes] = useState([]),
        moveTransItemAction = (row) => {
            const data = row.cells[2].data
            context.api.updateBillPaid(periodData.id, data.id);
        };

    useEffect(() => {
        if(isActive) {
            cardRef.current.scrollIntoView({inline: "start"});
            cardRef.current.parentElement.scrollBy(-40, 0);
        }
    }, []);
    useEffect(() => { setPaidIncomes(incomes.filter((income) => income.paid)); }, [incomes]);
    useEffect(() => { setUnpaidIncomes(incomes.filter((income) => !income.paid)); }, [incomes]);
    useEffect(() => {
        setBankBalance(
            periodData.startingAmount - 
            paidBills.reduce((prev, bill) => { return prev + bill.amount; }, 0.0) + 
            paidIncomes.reduce((prev, income) => { return prev + income.amount; }, 0.0)
        );
    }, [paidBills, paidIncomes]);
    useEffect(() => {
        setProjectedLeftover(
            bankBalance - 
            unpaidBills.reduce((prev, bill) => { return prev + bill.amount; }, 0.0) + 
            unpaidIncomes.reduce((prev, income) => { return prev + income.amount; }, 0.0)
        );
    }, [bankBalance, unpaidBills, unpaidIncomes]);

    return (
        <div ref={cardRef} className='budget-period-card'>
            <div className='card-header'>
                <span className={'lock'}>
                    <img src={ periodData.locked ? Lock : OpenLock } alt="lock" />
                </span>
            </div>
            <div className='card-body'>
                <div className='dates'>
                    <span className='dates-start'>{periodData.startDate.toDateString().split(' ').slice(1).join(' ')}</span>
                    <span> - </span>
                    <span className='dates-end'>{ periodData.endDate.toDateString().split(' ').slice(1).join(' ')}</span> 
                </div>
                <div className='bank-current'>
                    <span className='bank-current-label'>Current Balance</span>
                    <span className='bank-current-value'>{ '$' + parseFloat(bankBalance).toFixed(2) }</span>
                </div>
                <div className='bank-projected'>
                    <span className='bank-projected-label'>Projected Leftover</span>
                    <span className='bank-projected-value'>{ '$' + parseFloat(projectedLeftover).toFixed(2) }</span>
                </div>
                <BudgetPeriodTransTable title={'Unpaid'} transList={ unpaidBills } actionHandler={moveTransItemAction} isBill />
                <BudgetPeriodTransTable title={'Paid'} transList={ paidBills } actionHandler={moveTransItemAction} isBill  />
                <BudgetPeriodTransTable title={'Income'} transList={ incomes } isPaid />
            </div>
        </div>
    );
};

export default BudgetPeriodCard;