import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import ExpenseForm from './ExpenseForm';
import ExpenseList from './ExpenseList';
import TagManager from './TagManager';

const appData = window.manfietExpenseTrackerData || {};

const UserDashboard = () => {
    const [expenses, setExpenses] = useState([]);
    const restBase = appData.restBase || '/wp-json/manfi-expense-tracker/v1/';

    const fetchExpenses = () => {
        fetch(`${restBase}expenses`, {
            credentials: 'same-origin',
            headers: appData.restNonce ? { 'X-WP-Nonce': appData.restNonce } : {},
        })
            .then(response => response.json())
            .then(data => setExpenses(data))
            .catch(error => console.error(__('Error fetching expenses:', 'manfi-expense-tracker'), error));
    };

    useEffect(() => {
        fetchExpenses();
    }, []);

    return (
        <div className="manfiet-page-shell manfiet-page-shell-wide manfiet-user-dashboard-shell">
            <div className="manfiet-page-hero">
                <div className="left-section">
                    <h1 className="manfiet-page-title">{__('My Expenses', 'manfi-expense-tracker')}</h1>
                    <p className="manfiet-page-subtitle">{__('Track and manage your personal expenses', 'manfi-expense-tracker')}</p>
                </div>
            </div>
            <TagManager />
            <ExpenseForm onExpenseAdded={fetchExpenses} />
            <ExpenseList expenses={expenses} onExpenseUpdated={fetchExpenses} />
        </div>
    );
};

export default UserDashboard;
