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

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 AdminDashboard = () => {
    const [expenses, setExpenses] = useState([]);
    const [totalSpent, setTotalSpent] = useState(0);
    const [activeFilters, setActiveFilters] = useState({ category: '', startDate: '', endDate: '', tagName: '', search: '' });
    const restBase = appData.restBase || '/wp-json/manfi-expense-tracker/v1/';

    const fetchExpenses = (filters = activeFilters) => {
        const params = new URLSearchParams();
        if (filters.category) params.set('category', filters.category);
        if (filters.startDate && filters.endDate) {
            params.set('start_date', filters.startDate);
            params.set('end_date', filters.endDate);
        }
        if (filters.tagName) params.set('tag_name', filters.tagName);

        const query = params.toString() ? `?${params.toString()}` : '';

        requestJson(`${restBase}expenses${query}`)
            .then((data) => setExpenses(Array.isArray(data) ? data : []))
            .catch((error) => {
                console.error(__('Error fetching expenses:', 'manfi-expense-tracker'), error);
                setExpenses([]);
            });
    };

    useEffect(() => {
        fetchExpenses(activeFilters);

        const handleExpenseAdded = () => {
            fetchExpenses(activeFilters);
        };

        window.addEventListener('manfiet-expense-added', handleExpenseAdded);
        return () => window.removeEventListener('manfiet-expense-added', handleExpenseAdded);
    }, [activeFilters.category, activeFilters.startDate, activeFilters.endDate, activeFilters.tagName]);

    const filteredExpenses = useMemo(() => {
        if (!activeFilters.search) {
            return expenses;
        }
        const searchLower = activeFilters.search.toLowerCase();
        return expenses.filter((expense) => {
            const categoryMatch = String(expense.category || '').toLowerCase().includes(searchLower);
            const amountMatch = String(expense.amount || '').includes(searchLower);
            const dateMatch = String(expense.date || '').includes(searchLower);
            const recurringMatch = String(expense.recurring_interval || '').toLowerCase().includes(searchLower);
            const tagsMatch = (Array.isArray(expense.tags) ? expense.tags : [])
                .some((tag) => String(tag || '').toLowerCase().includes(searchLower));

            return categoryMatch || amountMatch || dateMatch || recurringMatch || tagsMatch;
        });
    }, [expenses, activeFilters.search]);

    useEffect(() => {
        const total = filteredExpenses.reduce((sum, expense) => sum + parseFloat(expense.amount || 0), 0);
        setTotalSpent(total);
    }, [filteredExpenses]);

    const exportUrls = appData.exportUrls || {};
    const canExport = Boolean(appData.canManageExpenses);

    return (
        <div className="manfiet-page-shell manfiet-page-shell-wide manfiet-admin-dashboard-shell">
            <div className="manfiet-page-hero">
                <div className="left-section">
                    <h1 className="manfiet-page-title">{__('Admin Expense Dashboard', 'manfi-expense-tracker')}</h1>
                    <p className="manfiet-page-subtitle">{__('Track and manage all expenses', 'manfi-expense-tracker')}</p>
                </div>
            </div>

            <div className="manfiet-stats-grid manfiet-mb-16">
                <div className="manfiet-card manfiet-stat-card">
                    <div className="manfiet-stat-label">{__('Total Expenses', 'manfi-expense-tracker')}</div>
                    <div className="manfiet-stat-value">{filteredExpenses.length}</div>
                </div>
                <div className="manfiet-card manfiet-stat-card">
                    <div className="manfiet-stat-label">{__('Total Spent', 'manfi-expense-tracker')}</div>
                    <div className="manfiet-stat-value">{appData.currencySymbol || '$'}{totalSpent.toFixed(2)}</div>
                </div>
                <div className="manfiet-card manfiet-stat-card">
                    <div className="manfiet-stat-label">{__('Average Expense', 'manfi-expense-tracker')}</div>
                    <div className="manfiet-stat-value">{appData.currencySymbol || '$'}{filteredExpenses.length > 0 ? (totalSpent / filteredExpenses.length).toFixed(2) : '0.00'}</div>
                </div>
            </div>

            {canExport && (
                <div className="manfiet-card manfiet-mb-16">
                    <h3 className="manfiet-card-title">{__('Export Full Report', 'manfi-expense-tracker')}</h3>
                    <div className="manfiet-form-row">
                        <button type="button" className="manfiet-button manfiet-button-primary" onClick={() => { window.location.href = exportUrls.csv; }}>
                            {__('Export Full Report (CSV)', 'manfi-expense-tracker')}
                        </button>
                        <button type="button" className="manfiet-button manfiet-button-info" onClick={() => { window.location.href = exportUrls.excel; }}>
                            {__('Export Full Report (Excel)', 'manfi-expense-tracker')}
                        </button>
                        <button type="button" className="manfiet-button manfiet-button-danger" onClick={() => { window.location.href = exportUrls.pdf; }}>
                            {__('Export Full Report (PDF)', 'manfi-expense-tracker')}
                        </button>
                    </div>
                </div>
            )}

            <div className="manfiet-card">
                <div className="manfiet-card-header-with-filters">
                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexShrink: 0 }}>
                        <h3 className="manfiet-card-title" style={{ margin: 0 }}>{__('All Expenses', 'manfi-expense-tracker')}</h3>
                        <a
                            href={appData.addExpenseUrl || '#'}
                            className="manfiet-btn manfiet-btn-primary"
                            style={{ textDecoration: 'none', whiteSpace: 'nowrap', fontSize: '13px', padding: '6px 14px' }}
                        >
                            + {__('Add Expense', 'manfi-expense-tracker')}
                        </a>
                    </div>
                    <div className="manfiet-header-filters">
                        <ExpenseFilter
                            activeFilters={activeFilters}
                            onFilter={(newFilters) => setActiveFilters(newFilters)}
                            onClear={() => setActiveFilters({ category: '', startDate: '', endDate: '', tagName: '', search: '' })}
                            compact={true}
                        />
                    </div>
                </div>
                <ExpenseList expenses={filteredExpenses} onExpenseUpdated={() => fetchExpenses(activeFilters)} />
            </div>
        </div>
    );
};

export default AdminDashboard;
