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 ExpenseForm = ({ onExpenseAdded, hideTitle = false }) => {
    const restBase = appData.restBase || '/wp-json/manfi-expense-tracker/v1/';
    const [categories, setCategories] = useState([]);
    const [tags, setTags] = useState([]);
    const [formData, setFormData] = useState({
        category: '',
        new_category: '',
        amount: '',
        date: new Date().toISOString().slice(0, 10),
        recurring_interval: '',
        tags: [],
        remark: '',
    });
    const [error, setError] = useState('');
    const [successMessage, setSuccessMessage] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);

    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);

                if (safeCategories.length && !formData.category) {
                    setFormData((current) => ({
                        ...current,
                        category: String(safeCategories[0].id),
                    }));
                }
            })
            .catch(() => {
                setError(__('Failed to load categories.', 'manfi-expense-tracker'));
            });
    }, []);

    const updateField = (field, value) => {
        setFormData((current) => ({
            ...current,
            [field]: value,
        }));
    };

    const handleSubmit = (event) => {
        event.preventDefault();

        const categoryValue = formData.category === '__new__'
            ? formData.new_category.trim()
            : formData.category.trim();

        if (!categoryValue) {
            setError(__('Category is required.', 'manfi-expense-tracker'));
            return;
        }

        if (!formData.amount || parseFloat(formData.amount) <= 0) {
            setError(__('Amount must be greater than zero.', 'manfi-expense-tracker'));
            return;
        }

        if (!formData.date) {
            setError(__('Date is required.', 'manfi-expense-tracker'));
            return;
        }

        setIsSubmitting(true);
        setError('');
        setSuccessMessage('');

        requestJson(`${restBase}expenses`, {
            method: 'POST',
            body: JSON.stringify({
                category: formData.category === '__new__' ? categoryValue : undefined,
                category_id: formData.category === '__new__' ? undefined : Number(formData.category),
                amount: formData.amount,
                date: formData.date,
                recurring_interval: formData.recurring_interval,
                tags: tags
                    .filter((tag) => formData.tags.includes(String(tag.id)))
                    .map((tag) => tag.tag_name),
                remark: formData.remark ? formData.remark.trim() : '',
            }),
        })
            .then((response) => {
                if (!categories.some((category) => category.category_name === categoryValue)) {
                    setCategories((current) => ([
                        ...current,
                        {
                            id: response?.category_id || `new-${categoryValue}`,
                            category_name: categoryValue,
                            display_name: categoryValue,
                            path_name: categoryValue,
                            parent_id: 0,
                            is_global: Boolean(appData.canManageExpenses),
                        },
                    ]));
                }

                setFormData((current) => ({
                    ...current,
                    category: response?.category_id ? String(response.category_id) : current.category,
                    new_category: '',
                    amount: '',
                    recurring_interval: '',
                    tags: [],
                    remark: '',
                }));
                setSuccessMessage(__('Expense added successfully.', 'manfi-expense-tracker'));

                if (typeof onExpenseAdded === 'function') {
                    onExpenseAdded();
                }

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

    const isFrontend = appData.pageView === 'frontend';

    if (!isFrontend) {
        return (
            <form onSubmit={handleSubmit} className="manfiet-form-stack">
                {!hideTitle && <h3 className="manfiet-section-title">{__('Add Expense', 'manfi-expense-tracker')}</h3>}
                {error && <p className="manfiet-alert manfiet-alert-error">{error}</p>}
                {successMessage && <p className="manfiet-alert manfiet-alert-success">{successMessage}</p>}

                <div className="manfiet-form-grid">
                    <div className="manfiet-field">
                        <label htmlFor="manfiet-expense-category" className="manfiet-label">{__('Category', 'manfi-expense-tracker')}</label>
                        <select
                            id="manfiet-expense-category"
                            value={formData.category}
                            onChange={(event) => updateField('category', event.target.value)}
                            className="manfiet-input"
                        >
                            <option value="">{__('Select a category', 'manfi-expense-tracker')}</option>
                            {categories.map((category) => (
                                <option key={category.id} value={String(category.id)}>
                                    {category.display_name || category.path_name || category.category_name}
                                </option>
                            ))}
                            <option value="__new__">{__('Add new category', 'manfi-expense-tracker')}</option>
                        </select>
                    </div>

                    {formData.category === '__new__' && (
                        <div className="manfiet-field">
                            <label htmlFor="manfiet-expense-new-category" className="manfiet-label">{__('New Category Name', 'manfi-expense-tracker')}</label>
                            <input
                                id="manfiet-expense-new-category"
                                type="text"
                                value={formData.new_category}
                                onChange={(event) => updateField('new_category', event.target.value)}
                                placeholder={__('Enter a new category name', 'manfi-expense-tracker')}
                                className="manfiet-input"
                            />
                        </div>
                    )}

                    <div className="manfiet-field">
                        <label htmlFor="manfiet-expense-amount" className="manfiet-label">{__('Amount', 'manfi-expense-tracker')} ({appData.currencySymbol || '$'})</label>
                        <input
                            id="manfiet-expense-amount"
                            type="number"
                            min="0.01"
                            step="0.01"
                            value={formData.amount}
                            onChange={(event) => updateField('amount', event.target.value)}
                            placeholder="0.00"
                            className="manfiet-input"
                        />
                    </div>

                    <div className="manfiet-field">
                        <label htmlFor="manfiet-expense-date" className="manfiet-label">{__('Date', 'manfi-expense-tracker')}</label>
                        <input
                            id="manfiet-expense-date"
                            type="date"
                            value={formData.date}
                            onChange={(event) => updateField('date', event.target.value)}
                            className="manfiet-input"
                        />
                    </div>

                    <div className="manfiet-field">
                        <label htmlFor="manfiet-expense-recurring" className="manfiet-label">{__('Recurring Interval', 'manfi-expense-tracker')}</label>
                        <select
                            id="manfiet-expense-recurring"
                            value={formData.recurring_interval}
                            onChange={(event) => updateField('recurring_interval', event.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>
                    </div>

                    <div className="manfiet-field">
                        <label htmlFor="manfiet-expense-tags" className="manfiet-label">{__('Tags', 'manfi-expense-tracker')}</label>
                        <select
                            id="manfiet-expense-tags"
                            multiple
                            value={formData.tags}
                            onChange={(event) => {
                                const selected = Array.from(event.target.selectedOptions).map((option) => option.value);
                                updateField('tags', selected);
                            }}
                            className="manfiet-input manfiet-input-multi"
                        >
                            {tags.map((tag) => (
                                <option key={tag.id} value={String(tag.id)}>
                                    {tag.tag_name}
                                </option>
                            ))}
                        </select>
                    </div>

                    <div className="manfiet-field" style={{ gridColumn: 'span 2' }}>
                        <label htmlFor="manfiet-expense-remark" className="manfiet-label">{__('Remark', 'manfi-expense-tracker')}</label>
                        <textarea
                            id="manfiet-expense-remark"
                            value={formData.remark}
                            onChange={(event) => updateField('remark', event.target.value)}
                            placeholder={__('Optional notes...', 'manfi-expense-tracker')}
                            className="manfiet-input"
                            rows={3}
                        />
                    </div>
                </div>

                <button type="submit" disabled={isSubmitting} className="manfiet-button manfiet-button-primary">
                    {isSubmitting ? __('Saving...', 'manfi-expense-tracker') : __('Save Expense', 'manfi-expense-tracker')}
                </button>
            </form>
        );
    }

    return (
        <div className="manfiet-card manfiet-expense-form-card">
            <form onSubmit={handleSubmit}>
                {!hideTitle && (
                    <h3 className="manfiet-section-title">
                        {__('Add New Expense', 'manfi-expense-tracker')}
                    </h3>
                )}
                
                {error && <p className="manfiet-alert manfiet-alert-error">{error}</p>}
                {successMessage && <p className="manfiet-alert manfiet-alert-success">{successMessage}</p>}

                <div className="manfiet-expense-form-layout">
                    {/* Left Column: Core Fields */}
                    <div className="manfiet-expense-primary-fields">
                        <div className="manfiet-field">
                            <label htmlFor="manfiet-expense-category" className="manfiet-label">{__('Category', 'manfi-expense-tracker')}</label>
                            <select
                                id="manfiet-expense-category"
                                value={formData.category}
                                onChange={(event) => updateField('category', event.target.value)}
                                className="manfiet-input"
                            >
                                <option value="">{__('Select a category', 'manfi-expense-tracker')}</option>
                                {categories.map((category) => (
                                    <option key={category.id} value={String(category.id)}>
                                        {category.display_name || category.path_name || category.category_name}
                                    </option>
                                ))}
                                <option value="__new__">{__('Add new category', 'manfi-expense-tracker')}</option>
                            </select>
                        </div>

                        {formData.category === '__new__' && (
                            <div className="manfiet-field" style={{ gridColumn: 'span 2' }}>
                                <label htmlFor="manfiet-expense-new-category" className="manfiet-label">{__('New Category Name', 'manfi-expense-tracker')}</label>
                                <input
                                    id="manfiet-expense-new-category"
                                    type="text"
                                    value={formData.new_category}
                                    onChange={(event) => updateField('new_category', event.target.value)}
                                    placeholder={__('Enter a new category name', 'manfi-expense-tracker')}
                                    className="manfiet-input"
                                />
                            </div>
                        )}

                        <div className="manfiet-field">
                            <label htmlFor="manfiet-expense-amount" className="manfiet-label">{__('Amount', 'manfi-expense-tracker')} ({appData.currencySymbol || '$'})</label>
                            <input
                                id="manfiet-expense-amount"
                                type="number"
                                min="0.01"
                                step="0.01"
                                value={formData.amount}
                                onChange={(event) => updateField('amount', event.target.value)}
                                placeholder="0.00"
                                className="manfiet-input"
                            />
                        </div>

                        <div className="manfiet-field">
                            <label htmlFor="manfiet-expense-date" className="manfiet-label">{__('Date', 'manfi-expense-tracker')}</label>
                            <input
                                id="manfiet-expense-date"
                                type="date"
                                value={formData.date}
                                onChange={(event) => updateField('date', event.target.value)}
                                className="manfiet-input"
                            />
                        </div>

                        <div className="manfiet-field">
                            <label htmlFor="manfiet-expense-recurring" className="manfiet-label">{__('Recurring Interval', 'manfi-expense-tracker')}</label>
                            <select
                                id="manfiet-expense-recurring"
                                value={formData.recurring_interval}
                                onChange={(event) => updateField('recurring_interval', event.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>
                        </div>

                        <div className="manfiet-field" style={{ gridColumn: 'span 2' }}>
                            <label htmlFor="manfiet-expense-remark" className="manfiet-label">{__('Remark', 'manfi-expense-tracker')}</label>
                            <textarea
                                id="manfiet-expense-remark"
                                value={formData.remark}
                                onChange={(event) => updateField('remark', event.target.value)}
                                placeholder={__('Optional notes...', 'manfi-expense-tracker')}
                                className="manfiet-input"
                                rows={2}
                            />
                        </div>
                    </div>

                    {/* Right Column: Tags Chips Selector */}
                    <div className="manfiet-field">
                        <label className="manfiet-label">{__('Select Tags', 'manfi-expense-tracker')}</label>
                        <div className="manfiet-tag-chips-wrapper">
                            {tags.length === 0 ? (
                                <p style={{ fontSize: '13px', color: '#94a3b8', margin: 0, fontStyle: 'italic' }}>
                                    {__('No tags created yet.', 'manfi-expense-tracker')}
                                </p>
                            ) : (
                                <div className="manfiet-tag-chips">
                                    {tags.map((tag) => {
                                        const isSelected = formData.tags.includes(String(tag.id));
                                        return (
                                            <button
                                                key={tag.id}
                                                type="button"
                                                onClick={() => {
                                                    const newTags = isSelected
                                                        ? formData.tags.filter((t) => t !== String(tag.id))
                                                        : [...formData.tags, String(tag.id)];
                                                    updateField('tags', newTags);
                                                }}
                                                className={`manfiet-tag-chip ${isSelected ? 'manfiet-tag-chip-selected' : ''}`}
                                            >
                                                {tag.tag_name}
                                                {isSelected && <span className="manfiet-tag-chip-check">✓</span>}
                                            </button>
                                        );
                                    })}
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                <div className="manfiet-form-actions">
                    <button type="submit" disabled={isSubmitting} className="manfiet-btn-save-expense">
                        {isSubmitting ? __('Saving...', 'manfi-expense-tracker') : __('Save Expense', 'manfi-expense-tracker')}
                    </button>
                </div>
            </form>
        </div>
    );
};

export default ExpenseForm;