import React, { useEffect, useState } from 'react';
import { __, sprintf } 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 TagDropdownSelector = ({ allTags, selectedTagIds, onChange }) => {
    const [isOpen, setIsOpen] = useState(false);
    const containerRef = React.useRef(null);

    useEffect(() => {
        const handleClickOutside = (event) => {
            if (containerRef.current && !containerRef.current.contains(event.target)) {
                setIsOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const toggleTag = (tagId) => {
        const idStr = String(tagId);
        const isSelected = selectedTagIds.includes(idStr);
        const newSelected = isSelected
            ? selectedTagIds.filter((id) => id !== idStr)
            : [...selectedTagIds, idStr];
        onChange(newSelected);
    };

    const selectedTagsList = allTags.filter((t) => selectedTagIds.includes(String(t.id)));
    const triggerText = selectedTagsList.length === 0
        ? __('Select Tags', 'manfi-expense-tracker')
        : selectedTagsList.length === 1
        ? selectedTagsList[0].tag_name
        : sprintf(__('%d tags selected', 'manfi-expense-tracker'), selectedTagsList.length);

    return (
        <div className="manfiet-tag-dropdown-container" ref={containerRef} style={{ position: 'relative' }}>
            <button
                type="button"
                className="manfiet-input manfiet-tag-dropdown-trigger"
                onClick={() => setIsOpen(!isOpen)}
                style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    background: '#ffffff',
                    cursor: 'pointer',
                    textAlign: 'left',
                    width: '100%',
                    minWidth: '150px'
                }}
            >
                <span style={{ textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap', maxWidth: '120px' }}>
                    {triggerText}
                </span>
                <span style={{ fontSize: '10px', marginLeft: '6px', color: '#64748b' }}>▼</span>
            </button>

            {isOpen && (
                <div
                    className="manfiet-tag-dropdown-menu"
                    style={{
                        position: 'absolute',
                        top: '100%',
                        left: 0,
                        zIndex: 9999,
                        background: '#ffffff',
                        border: '1px solid #cbd5e1',
                        borderRadius: '8px',
                        boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                        padding: '8px',
                        maxHeight: '200px',
                        overflowY: 'auto',
                        minWidth: '180px',
                        marginTop: '4px'
                    }}
                >
                    {allTags.length === 0 ? (
                        <p style={{ margin: 0, fontSize: '12px', color: '#94a3b8', fontStyle: 'italic' }}>
                            {__('No tags found', 'manfi-expense-tracker')}
                        </p>
                    ) : (
                        allTags.map((tag) => {
                            const isSelected = selectedTagIds.includes(String(tag.id));
                            return (
                                <label
                                    key={tag.id}
                                    style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        padding: '4px 6px',
                                        fontSize: '13px',
                                        cursor: 'pointer',
                                        userSelect: 'none',
                                        gap: '6px',
                                        borderRadius: '4px',
                                        background: isSelected ? '#f1f5f9' : 'transparent',
                                        fontWeight: isSelected ? '600' : 'normal',
                                        margin: '2px 0',
                                        width: '100%'
                                    }}
                                >
                                    <input
                                        type="checkbox"
                                        checked={isSelected}
                                        onChange={() => toggleTag(tag.id)}
                                        style={{ margin: 0 }}
                                    />
                                    {tag.tag_name}
                                </label>
                            );
                        })
                    )}
                </div>
            )}
        </div>
    );
};

const AddExpensePage = () => {
    const restBase = appData.restBase || '/wp-json/manfi-expense-tracker/v1/';
    const [categories, setCategories] = useState([]);
    const [tags, setTags] = useState([]);
    const [loading, setLoading] = useState(true);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [error, setError] = useState('');
    const [successMessage, setSuccessMessage] = useState('');
    const [validationTriggered, setValidationTriggered] = useState(false);

    // Initial state has 3 blank rows
    const createEmptyRow = () => ({
        category_id_or_new: '',
        new_category: '',
        amount: '',
        date: new Date().toISOString().slice(0, 10),
        recurring_interval: '',
        tags: [],
        remark: ''
    });

    const [rows, setRows] = useState([createEmptyRow(), createEmptyRow(), createEmptyRow()]);

    useEffect(() => {
        Promise.all([
            requestJson(`${restBase}categories`),
            requestJson(`${restBase}tags`).catch(() => []),
        ])
            .then(([categoryData, tagData]) => {
                const safeCategories = Array.isArray(categoryData) ? categoryData : [];
                const safeTags = Array.isArray(tagData) ? tagData : [];
                setCategories(safeCategories);
                setTags(safeTags);

                // Auto-fill category on default rows if possible
                if (safeCategories.length) {
                    setRows((current) =>
                        current.map((row) => ({
                            ...row,
                            category_id_or_new: row.category_id_or_new || String(safeCategories[0].id)
                        }))
                    );
                }
            })
            .catch(() => {
                setError(__('Failed to load initial form categories.', 'manfi-expense-tracker'));
            })
            .finally(() => {
                setLoading(false);
            });
    }, []);

    const handleAddRow = () => {
        const defaultCatId = categories.length > 0 ? String(categories[0].id) : '';
        setRows((current) => [
            ...current,
            {
                ...createEmptyRow(),
                category_id_or_new: defaultCatId
            }
        ]);
    };

    const handleRemoveRow = (indexToRemove) => {
        if (rows.length <= 1) return;
        setRows((current) => current.filter((_, idx) => idx !== indexToRemove));
    };

    const handleUpdateRowField = (index, field, value) => {
        setRows((current) =>
            current.map((row, idx) => (idx === index ? { ...row, [field]: value } : row))
        );
    };

    const getRowError = (row) => {
        const errors = [];
        const categoryValue = row.category_id_or_new === '__new__' ? row.new_category.trim() : row.category_id_or_new;
        if (!categoryValue) {
            errors.push(__('Category is required', 'manfi-expense-tracker'));
        }
        if (!row.amount || parseFloat(row.amount) <= 0) {
            errors.push(__('Amount must be greater than zero', 'manfi-expense-tracker'));
        }
        if (!row.date) {
            errors.push(__('Date is required', 'manfi-expense-tracker'));
        }
        return errors;
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        setValidationTriggered(true);
        setError('');
        setSuccessMessage('');

        // Validate all rows
        const validationErrors = [];
        rows.forEach((row, index) => {
            const rowErrs = getRowError(row);
            if (rowErrs.length > 0) {
                validationErrors.push(
                    sprintf(__('Row %d: ', 'manfi-expense-tracker'), index + 1) + rowErrs.join(', ')
                );
            }
        });

        if (validationErrors.length > 0) {
            setError(validationErrors.join(' | '));
            return;
        }

        setIsSubmitting(true);

        const payload = {
            expenses: rows.map((row) => ({
                category: row.category_id_or_new === '__new__' ? row.new_category.trim() : undefined,
                category_id: row.category_id_or_new === '__new__' ? undefined : Number(row.category_id_or_new),
                amount: parseFloat(row.amount),
                date: row.date,
                recurring_interval: row.recurring_interval,
                tags: tags
                    .filter((t) => row.tags.includes(String(t.id)))
                    .map((t) => t.tag_name),
                remark: row.remark ? row.remark.trim() : ''
            }))
        };

        requestJson(`${restBase}expenses/batch`, {
            method: 'POST',
            body: JSON.stringify(payload)
        })
            .then((res) => {
                setSuccessMessage(res.message || __('Expenses saved successfully.', 'manfi-expense-tracker'));
                setValidationTriggered(false);

                // Re-fetch categories in case new ones were added
                requestJson(`${restBase}categories`)
                    .then((newCatData) => {
                        const safeCats = Array.isArray(newCatData) ? newCatData : [];
                        setCategories(safeCats);
                        const defaultCatId = safeCats.length > 0 ? String(safeCats[0].id) : '';

                        // Reset to default 3 blank rows
                        setRows([
                            { ...createEmptyRow(), category_id_or_new: defaultCatId },
                            { ...createEmptyRow(), category_id_or_new: defaultCatId },
                            { ...createEmptyRow(), category_id_or_new: defaultCatId }
                        ]);
                    })
                    .catch(() => {
                        const defaultCatId = categories.length > 0 ? String(categories[0].id) : '';
                        setRows([
                            { ...createEmptyRow(), category_id_or_new: defaultCatId },
                            { ...createEmptyRow(), category_id_or_new: defaultCatId },
                            { ...createEmptyRow(), category_id_or_new: defaultCatId }
                        ]);
                    });

                window.dispatchEvent(new CustomEvent('manfiet-expense-added'));
            })
            .catch((err) => {
                setError(err.message || __('Failed to save expenses batch.', 'manfi-expense-tracker'));
            })
            .finally(() => {
                setIsSubmitting(false);
            });
    };

    if (loading) {
        return (
            <div className="manfiet-page-shell" style={{ padding: '40px', textAlign: 'center' }}>
                <p>{__('Loading form settings...', 'manfi-expense-tracker')}</p>
            </div>
        );
    }

    return (
        <div className="manfiet-page-shell">
            <div className="manfiet-page-hero">
                <div className="left-section">
                    <h2 className="manfiet-page-title">{__('Add Expenses', 'manfi-expense-tracker')}</h2>
                    <p className="manfiet-page-subtitle">{__('Add multiple expense records at the same time', 'manfi-expense-tracker')}</p>
                </div>
            </div>

            <div className="manfiet-card" style={{ padding: '24px' }}>
                {error && (
                    <div className="manfiet-alert manfiet-alert-error" style={{ marginBottom: '16px' }}>
                        <strong>{__('Please check the following errors:', 'manfi-expense-tracker')}</strong>
                        <ul style={{ margin: '6px 0 0 16px', padding: 0 }}>
                            {error.split(' | ').map((msg, i) => (
                                <li key={i}>{msg}</li>
                            ))}
                        </ul>
                    </div>
                )}
                {successMessage && (
                    <p className="manfiet-alert manfiet-alert-success" style={{ marginBottom: '16px' }}>
                        {successMessage}
                    </p>
                )}

                <form onSubmit={handleSubmit}>
                    <div className="manfiet-batch-table-wrapper">
                        <table className="manfiet-batch-table">
                            <thead>
                                <tr>
                                    <th style={{ width: '40px' }}>#</th>
                                    <th>{__('Category', 'manfi-expense-tracker')}</th>
                                    <th style={{ width: '150px' }}>{__('Amount', 'manfi-expense-tracker')} ({appData.currencySymbol || '$'})</th>
                                    <th style={{ width: '160px' }}>{__('Date', 'manfi-expense-tracker')}</th>
                                    <th style={{ width: '150px' }}>{__('Recurring Interval', 'manfi-expense-tracker')}</th>
                                    <th style={{ width: '180px' }}>{__('Tags', 'manfi-expense-tracker')}</th>
                                    <th style={{ width: '60px', textAlign: 'center' }}></th>
                                </tr>
                            </thead>
                            <tbody>
                                {rows.map((row, index) => {
                                    const categoryValue = row.category_id_or_new === '__new__' ? row.new_category.trim() : row.category_id_or_new;
                                    const isCategoryInvalid = validationTriggered && !categoryValue;
                                    const isAmountInvalid = validationTriggered && (!row.amount || parseFloat(row.amount) <= 0);
                                    const isDateInvalid = validationTriggered && !row.date;

                                    return (
                                        <React.Fragment key={index}>
                                            <tr style={{ background: '#ffffff' }}>
                                                <td style={{ borderBottom: 'none', verticalAlign: 'middle', fontWeight: 'bold', color: '#64748b', fontSize: '13px' }}>
                                                    {index + 1}
                                                </td>
                                                <td style={{ borderBottom: 'none' }}>
                                                    <select
                                                        value={row.category_id_or_new}
                                                        onChange={(e) => handleUpdateRowField(index, 'category_id_or_new', e.target.value)}
                                                        className={`manfiet-input ${isCategoryInvalid ? 'manfiet-input-error' : ''}`}
                                                    >
                                                        <option value="">{__('Select category', 'manfi-expense-tracker')}</option>
                                                        {categories.map((c) => (
                                                            <option key={c.id} value={String(c.id)}>
                                                                {c.display_name || c.category_name}
                                                            </option>
                                                        ))}
                                                        <option value="__new__">{__('+ ' + __('Add new category', 'manfi-expense-tracker'))}</option>
                                                    </select>
                                                    {row.category_id_or_new === '__new__' && (
                                                        <input
                                                            type="text"
                                                            placeholder={__('Enter new category name', 'manfi-expense-tracker')}
                                                            value={row.new_category}
                                                            onChange={(e) => handleUpdateRowField(index, 'new_category', e.target.value)}
                                                            className={`manfiet-input ${isCategoryInvalid ? 'manfiet-input-error' : ''}`}
                                                            style={{ marginTop: '6px' }}
                                                        />
                                                    )}
                                                </td>
                                                <td style={{ borderBottom: 'none' }}>
                                                    <input
                                                        type="number"
                                                        min="0.01"
                                                        step="0.01"
                                                        placeholder="0.00"
                                                        value={row.amount}
                                                        onChange={(e) => handleUpdateRowField(index, 'amount', e.target.value)}
                                                        className={`manfiet-input ${isAmountInvalid ? 'manfiet-input-error' : ''}`}
                                                    />
                                                </td>
                                                <td style={{ borderBottom: 'none' }}>
                                                    <input
                                                        type="date"
                                                        value={row.date}
                                                        onChange={(e) => handleUpdateRowField(index, 'date', e.target.value)}
                                                        className={`manfiet-input ${isDateInvalid ? 'manfiet-input-error' : ''}`}
                                                    />
                                                </td>
                                                <td style={{ borderBottom: 'none' }}>
                                                    <select
                                                        value={row.recurring_interval}
                                                        onChange={(e) => handleUpdateRowField(index, 'recurring_interval', e.target.value)}
                                                        className="manfiet-input"
                                                    >
                                                        <option value="">{__('One-time', 'manfi-expense-tracker')}</option>
                                                        <option value="day">{__('Daily', 'manfi-expense-tracker')}</option>
                                                        <option value="week">{__('Weekly', 'manfi-expense-tracker')}</option>
                                                        <option value="month">{__('Monthly', 'manfi-expense-tracker')}</option>
                                                        <option value="year">{__('Yearly', 'manfi-expense-tracker')}</option>
                                                    </select>
                                                </td>
                                                <td style={{ borderBottom: 'none' }}>
                                                    <TagDropdownSelector
                                                        allTags={tags}
                                                        selectedTagIds={row.tags}
                                                        onChange={(selectedIds) => handleUpdateRowField(index, 'tags', selectedIds)}
                                                    />
                                                </td>
                                                <td style={{ borderBottom: 'none', textAlign: 'center', verticalAlign: 'middle' }}>
                                                    <button
                                                        type="button"
                                                        onClick={() => handleRemoveRow(index)}
                                                        disabled={rows.length <= 1}
                                                        className="manfiet-btn-remove-row"
                                                        title={__('Delete row', 'manfi-expense-tracker')}
                                                    >
                                                        🗑️
                                                    </button>
                                                </td>
                                            </tr>
                                            <tr style={{ background: '#ffffff' }}>
                                                <td style={{ paddingTop: '0px', paddingBottom: '16px' }}></td>
                                                <td colSpan="5" style={{ paddingTop: '0px', paddingBottom: '16px' }}>
                                                    <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                                                        <span style={{ fontSize: '11px', fontWeight: '600', color: '#64748b' }}>
                                                            {__('Remark / Note (Optional)', 'manfi-expense-tracker')}
                                                        </span>
                                                        <textarea
                                                            placeholder={__('Enter optional remark or notes for this item...', 'manfi-expense-tracker')}
                                                            value={row.remark || ''}
                                                            onChange={(e) => handleUpdateRowField(index, 'remark', e.target.value)}
                                                            className="manfiet-input"
                                                            rows={2}
                                                            style={{ resize: 'vertical', minHeight: '60px', fontFamily: 'inherit' }}
                                                        />
                                                    </div>
                                                </td>
                                                <td style={{ paddingTop: '0px', paddingBottom: '16px' }}></td>
                                            </tr>
                                        </React.Fragment>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>

                    <div className="manfiet-batch-actions">
                        <button
                            type="button"
                            onClick={handleAddRow}
                            className="manfiet-btn-add-row"
                        >
                            ➕ {__('Add Expense Row', 'manfi-expense-tracker')}
                        </button>
                        <button
                            type="submit"
                            disabled={isSubmitting}
                            className="manfiet-btn-save-batch"
                        >
                            {isSubmitting ? __('Saving...', 'manfi-expense-tracker') : __('Save Expenses', 'manfi-expense-tracker')}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default AddExpensePage;
