import React, { useState, useEffect, useContext } from 'react';
import { pb } from '../../lib/pocketbase';
import { LanguageContext } from '../../contexts/LanguageContext';

const BalanceCard = ({ balance: propBalance, userId }) => {
    const { t } = useContext(LanguageContext);
    // If balance prop is provided (from App.jsx), use it.
    // If userId is provided (supervisor view), fetch it.

    const [fetchedBalance, setFetchedBalance] = useState(null);

    useEffect(() => {
        if (userId) {
            const fetchBalance = async () => {
                try {
                    const records = await pb.collection('time_entries').getFullList({
                        filter: `is_banked = true && user = "${userId}"`,
                        requestKey: null
                    });
                    const total = records.reduce((acc, curr) => acc + (curr.calculated_hours || 0), 0);
                    setFetchedBalance(total);
                } catch (err) {
                    console.error("Error fetching balance for user", userId, err);
                }
            };
            fetchBalance();
        }
    }, [userId]);

    const displayBalance = userId ? (fetchedBalance || 0) : (propBalance || 0);

    return (
        <div className="bg-gradient-to-r from-indigo-500 to-purple-600 p-6 rounded-lg shadow-md text-white">
            <h3 className="text-lg font-semibold opacity-90 mb-1">
                {userId ? t('balance.employee_title') : t('balance.title')}
            </h3>
            <div className="text-4xl font-bold">{displayBalance.toFixed(2)} <span className="text-sm font-normal opacity-75">hrs</span></div>
            <p className="text-xs mt-2 opacity-75">{t('balance.available')}</p>
        </div>
    );
};

export default BalanceCard;
