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(async (response) => {
        const data = await response.json().catch(() => ({}));

        if (!response.ok) {
            throw new Error(data.message || 'Request failed');
        }

        return data;
    });
};

const ExpenseFilter = ({ onFilter, activeFilters, onClear, compact = false }) => {
    const restBase = appData.restBase || '/wp-json/manfi-expense-tracker/v1/';
    const [categories, setCategories] = useState([]);
    const [tags, setTags] = useState([]);
    const [selectedMonth, setSelectedMonth] = useState('');
    const [filters, setFilters] = useState({
        category: activeFilters?.category || '',
        tagName: activeFilters?.tagName || '',
        startDate: activeFilters?.startDate || '',
        endDate: activeFilters?.endDate || '',
        search: activeFilters?.search || '',
    });

    useEffect(() => {
        Promise.all([
            requestJson(`${restBase}categories`),
            requestJson(`${restBase}tags`).catch(() => []),
        ])
            .then(([categoryData, tagData]) => {
                setCategories(Array.isArray(categoryData) ? categoryData : []);
                setTags(Array.isArray(tagData) ? tagData : []);
            })
            .catch((err) => console.error('Failed to load filter metadata:', err));
    }, []);

    // Keep state synced if activeFilters changes from parent (e.g. clicking tag on dashboard)
    useEffect(() => {
        setFilters((prev) => ({
            ...prev,
            category: activeFilters?.category || '',
            tagName: activeFilters?.tagName || '',
            startDate: activeFilters?.startDate || '',
            endDate: activeFilters?.endDate || '',
            search: activeFilters?.search || '',
        }));

        // Reset selected month dropdown if dates don't match it
        if (!activeFilters?.startDate && !activeFilters?.endDate) {
            setSelectedMonth('');
        }
    }, [activeFilters]);

    // Generate last 12 months options
    const getMonthOptions = () => {
        const options = [];
        const date = new Date();
        for (let i = 0; i < 12; i++) {
            const year = date.getFullYear();
            const month = date.getMonth();
            const monthVal = `${year}-${String(month + 1).padStart(2, '0')}`;
            const label = date.toLocaleDateString('default', { month: 'long', year: 'numeric' });
            options.push({ value: monthVal, label });
            date.setMonth(date.getMonth() - 1);
        }
        return options;
    };

    const handleMonthChange = (e) => {
        const val = e.target.value;
        setSelectedMonth(val);

        let start = '';
        let end = '';
        if (val) {
            const [year, month] = val.split('-').map(Number);
            start = `${year}-${String(month).padStart(2, '0')}-01`;
            const lastDay = new Date(year, month, 0).getDate();
            end = `${year}-${String(month).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`;
        }

        const newFilters = { ...filters, startDate: start, endDate: end };
        setFilters(newFilters);
        onFilter(newFilters);
    };

    const applyFilters = () => {
        onFilter(filters);
    };

    const handleClear = () => {
        const resetFilters = { category: '', tagName: '', startDate: '', endDate: '', search: '' };
        setFilters(resetFilters);
        setSelectedMonth('');
        if (typeof onClear === 'function') {
            onClear();
        } else {
            onFilter(resetFilters);
        }
    };

    if (compact) {
        return (
            <div className="manfiet-filters-inline">
                <input
                    type="text"
                    value={filters.search}
                    onChange={(e) => {
                        const newFilters = { ...filters, search: e.target.value };
                        setFilters(newFilters);
                        onFilter(newFilters);
                    }}
                    placeholder={__('Search expenses...', 'manfi-expense-tracker')}
                    className="manfiet-input manfiet-input-sm"
                    style={{ width: '160px' }}
                />

                <select
                    value={filters.category}
                    onChange={(e) => {
                        const newFilters = { ...filters, category: e.target.value };
                        setFilters(newFilters);
                        onFilter(newFilters);
                    }}
                    className="manfiet-input manfiet-input-sm"
                    style={{ width: '150px' }}
                >
                    <option value="">{__('All Categories', 'manfi-expense-tracker')}</option>
                    {categories.map((cat) => (
                        <option key={cat.id} value={cat.path_name || cat.category_name}>
                            {cat.display_name || cat.path_name || cat.category_name}
                        </option>
                    ))}
                </select>

                <select
                    value={filters.tagName}
                    onChange={(e) => {
                        const newFilters = { ...filters, tagName: e.target.value };
                        setFilters(newFilters);
                        onFilter(newFilters);
                    }}
                    className="manfiet-input manfiet-input-sm"
                    style={{ width: '130px' }}
                >
                    <option value="">{__('All Tags', 'manfi-expense-tracker')}</option>
                    {tags.map((tag) => (
                        <option key={tag.id} value={tag.tag_name}>
                            {tag.tag_name}
                        </option>
                    ))}
                </select>

                <select
                    value={selectedMonth}
                    onChange={handleMonthChange}
                    className="manfiet-input manfiet-input-sm"
                    style={{ width: '140px' }}
                >
                    <option value="">{__('Select Month', 'manfi-expense-tracker')}</option>
                    {getMonthOptions().map((opt) => (
                        <option key={opt.value} value={opt.value}>
                            {opt.label}
                        </option>
                    ))}
                </select>

                <div className="manfiet-date-inputs-inline" style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                    <input
                        type="date"
                        value={filters.startDate}
                        onChange={(e) => {
                            const newFilters = { ...filters, startDate: e.target.value };
                            setFilters(newFilters);
                            setSelectedMonth('');
                            onFilter(newFilters);
                        }}
                        className="manfiet-input manfiet-input-sm"
                        style={{ width: '125px', padding: '4px 6px' }}
                    />
                    <span style={{ fontSize: '11px', color: '#64748b' }}>-</span>
                    <input
                        type="date"
                        value={filters.endDate}
                        onChange={(e) => {
                            const newFilters = { ...filters, endDate: e.target.value };
                            setFilters(newFilters);
                            setSelectedMonth('');
                            onFilter(newFilters);
                        }}
                        className="manfiet-input manfiet-input-sm"
                        style={{ width: '125px', padding: '4px 6px' }}
                    />
                </div>

                {(filters.category || filters.tagName || filters.startDate || filters.endDate || filters.search) && (
                    <button
                        type="button"
                        onClick={handleClear}
                        className="manfiet-button manfiet-button-secondary manfiet-button-sm"
                        style={{ padding: '4px 10px', height: '30px', minHeight: 'auto' }}
                    >
                        {__('Clear', 'manfi-expense-tracker')}
                    </button>
                )}
            </div>
        );
    }

    return (
        <div className="manfiet-form-stack">
            <div className="manfiet-field">
                <label className="manfiet-label">{__('Search', 'manfi-expense-tracker')}</label>
                <input
                    type="text"
                    value={filters.search}
                    onChange={(e) => setFilters({ ...filters, search: e.target.value })}
                    placeholder={__('Search expenses...', 'manfi-expense-tracker')}
                    className="manfiet-input"
                />
            </div>

            <div className="manfiet-field">
                <label className="manfiet-label">{__('Category', 'manfi-expense-tracker')}</label>
                <select
                    value={filters.category}
                    onChange={(e) => setFilters({ ...filters, category: e.target.value })}
                    className="manfiet-input"
                >
                    <option value="">{__('All Categories', 'manfi-expense-tracker')}</option>
                    {categories.map((cat) => (
                        <option key={cat.id} value={cat.path_name || cat.category_name}>
                            {cat.display_name || cat.path_name || cat.category_name}
                        </option>
                    ))}
                </select>
            </div>

            <div className="manfiet-field">
                <label className="manfiet-label">{__('Tag', 'manfi-expense-tracker')}</label>
                <select
                    value={filters.tagName}
                    onChange={(e) => setFilters({ ...filters, tagName: e.target.value })}
                    className="manfiet-input"
                >
                    <option value="">{__('All Tags', 'manfi-expense-tracker')}</option>
                    {tags.map((tag) => (
                        <option key={tag.id} value={tag.tag_name}>
                            {tag.tag_name}
                        </option>
                    ))}
                </select>
            </div>

            <div className="manfiet-field">
                <label className="manfiet-label">{__('Filter by Month', 'manfi-expense-tracker')}</label>
                <select
                    value={selectedMonth}
                    onChange={handleMonthChange}
                    className="manfiet-input"
                >
                    <option value="">{__('Select Month', 'manfi-expense-tracker')}</option>
                    {getMonthOptions().map((opt) => (
                        <option key={opt.value} value={opt.value}>
                            {opt.label}
                        </option>
                    ))}
                </select>
            </div>

            <div className="manfiet-field-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
                <div className="manfiet-field">
                    <label className="manfiet-label">{__('Start Date', 'manfi-expense-tracker')}</label>
                    <input
                        type="date"
                        value={filters.startDate}
                        onChange={(e) => {
                            setFilters({ ...filters, startDate: e.target.value });
                            setSelectedMonth('');
                        }}
                        className="manfiet-input"
                    />
                </div>

                <div className="manfiet-field">
                    <label className="manfiet-label">{__('End Date', 'manfi-expense-tracker')}</label>
                    <input
                        type="date"
                        value={filters.endDate}
                        onChange={(e) => {
                            setFilters({ ...filters, endDate: e.target.value });
                            setSelectedMonth('');
                        }}
                        className="manfiet-input"
                    />
                </div>
            </div>

            <div className="manfiet-form-actions" style={{ display: 'flex', gap: '8px', marginTop: '10px' }}>
                <button
                    type="button"
                    onClick={applyFilters}
                    className="manfiet-button manfiet-button-primary"
                    style={{ flex: 1 }}
                >
                    {__('Filter', 'manfi-expense-tracker')}
                </button>
                <button
                    type="button"
                    onClick={handleClear}
                    className="manfiet-button manfiet-button-secondary"
                    style={{ flex: 1 }}
                >
                    {__('Clear', 'manfi-expense-tracker')}
                </button>
            </div>
        </div>
    );
};

export default ExpenseFilter;
