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

const appData = window.manfietExpenseTrackerData || {};

const requestJson = (url, options = {}) => {
    const headers = {
        'Content-Type': 'application/json',
        ...(options.headers || {}),
    };

    if (appData.restNonce) {
        headers['X-WP-Nonce'] = appData.restNonce;
    }

    return fetch(url, {
        credentials: 'same-origin',
        ...options,
        headers,
    }).then((response) => {
        if (!response.ok) {
            throw new Error('Request failed');
        }

        return response.json();
    });
};

const BudgetDashboard = () => {
    const [budgets, setBudgets] = useState({ week: 0, month: 0, year: 0 });
    const [spent, setSpent] = useState({ week: 0, month: 0, year: 0 });
    const [usage, setUsage] = useState({ week: 0, month: 0, year: 0 });
    const [loading, setLoading] = useState(true);
    const [message, setMessage] = useState('');
    const [error, setError] = useState('');
    const restBase = appData.restBase || '/wp-json/manfi-expense-tracker/v1/';

    const loadBudgetData = () => {
        requestJson(`${restBase}budget`)
            .then(data => {
                setBudgets(data.budgets || { week: 0, month: 0, year: 0 });
                setSpent(data.spent || { week: 0, month: 0, year: 0 });
                setUsage(data.usage || { week: 0, month: 0, year: 0 });
                setLoading(false);
            })
            .catch(() => {
                setError(__('Error fetching budget data.', 'manfi-expense-tracker'));
                setLoading(false);
            });
    };

    useEffect(() => {
        loadBudgetData();

        const refreshBudget = () => {
            setLoading(true);
            loadBudgetData();
        };

        window.addEventListener('manfiet-expense-added', refreshBudget);

        return () => {
            window.removeEventListener('manfiet-expense-added', refreshBudget);
        };
    }, []);

    const updateBudget = () => {
        setMessage('');
        setError('');

        requestJson(`${restBase}budget`, {
            method: 'POST',
            body: JSON.stringify({ budgets })
        })
        .then(() => {
            setMessage(__('Budget updated successfully.', 'manfi-expense-tracker'));
            loadBudgetData();
        })
        .catch((requestError) => {
            setError(requestError.message || __('Error updating budget.', 'manfi-expense-tracker'));
        });
    };

    const updatePeriodBudget = (period, value) => {
        setBudgets((current) => ({
            ...current,
            [period]: Number(value),
        }));
    };

    const periodLabel = {
        week: __('Weekly', 'manfi-expense-tracker'),
        month: __('Monthly', 'manfi-expense-tracker'),
        year: __('Yearly', 'manfi-expense-tracker'),
    };

    const progressColor = (value) => {
        if (value >= 100) {
            return '#dc2626';
        }

        if (value >= 70) {
            return '#d97706';
        }

        return '#16a34a';
    };

    const formatMoney = (value) => `${appData.currencySymbol || '$'}${Number(value || 0).toFixed(2)}`;

    return (
        <div className="manfiet-page-shell">
            <div className="manfiet-page-hero">
                <div className="left-section">
                    <h2 className="manfiet-page-title">{__('Budget Management', 'manfi-expense-tracker')}</h2>
                    <p className="manfiet-page-subtitle">{__('Set weekly, monthly, and yearly budgets. Alerts are shown after 70% usage.', 'manfi-expense-tracker')}</p>
                </div>
            </div>

            <div className="manfiet-card">
                {message && <p className="manfiet-alert manfiet-alert-success">{message}</p>}
                {error && <p className="manfiet-alert manfiet-alert-error">{error}</p>}

                {loading ? <p>{__('Loading...', 'manfi-expense-tracker')}</p> : (
                <div className="manfiet-table-scroll">
                    <table className="manfiet-table">
                        <thead>
                            <tr>
                                <th>{__('Period', 'manfi-expense-tracker')}</th>
                                <th className="manfiet-align-right">{__('Budget', 'manfi-expense-tracker')}</th>
                                <th className="manfiet-align-right">{__('Spent', 'manfi-expense-tracker')}</th>
                                <th className="manfiet-align-right">{__('Usage %', 'manfi-expense-tracker')}</th>
                                <th>{__('Progress', 'manfi-expense-tracker')}</th>
                            </tr>
                        </thead>
                        <tbody>
                            {['week', 'month', 'year'].map((period) => {
                                const usageValue = Number(usage[period] || 0);
                                const progressWidth = Math.min(usageValue, 100);

                                return (
                                    <tr key={period}>
                                        <td className="manfiet-font-semibold">{periodLabel[period]}</td>
                                        <td className="manfiet-align-right">
                                            <input
                                                type="number"
                                                min="1"
                                                value={budgets[period] || 0}
                                                onChange={(e) => updatePeriodBudget(period, e.target.value)}
                                                className="manfiet-budget-input"
                                            />
                                        </td>
                                        <td className="manfiet-align-right">{formatMoney(spent[period])}</td>
                                        <td className="manfiet-align-right manfiet-font-semibold">{usageValue.toFixed(2)}%</td>
                                        <td>
                                            <div className="manfiet-progress-track">
                                                <div
                                                    className="manfiet-progress-bar"
                                                    style={{
                                                        width: `${progressWidth}%`,
                                                        backgroundColor: progressColor(usageValue),
                                                    }}
                                                />
                                            </div>
                                        </td>
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>

                    <button onClick={updateBudget} className="manfiet-button manfiet-button-primary">{__('Save Budgets', 'manfi-expense-tracker')}</button>
                </div>
            )}
            </div>
        </div>
    );
};

export default BudgetDashboard;
