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 TagManager = ({ clickableNames = false, activeTagName = '', onTagClick = null }) => {
    const restBase = appData.restBase || '/wp-json/manfi-expense-tracker/v1/';
    const isGlobalManager = Boolean(appData.canManageExpenses);
    const [tags, setTags] = useState([]);
    const [newTag, setNewTag] = useState('');
    const [error, setError] = useState('');

    const loadTags = () => {
        requestJson(`${restBase}tags`)
            .then((data) => setTags(Array.isArray(data) ? data : []))
            .catch((requestError) => setError(requestError.message || __('Failed to load tags.', 'manfi-expense-tracker')));
    };

    useEffect(() => {
        loadTags();
    }, []);

    const addTag = () => {
        if (!newTag.trim()) {
            setError(__('Tag name cannot be empty.', 'manfi-expense-tracker'));
            return;
        }

        setError('');

        requestJson(`${restBase}tags`, {
            method: 'POST',
            body: JSON.stringify({
                tag_name: newTag.trim(),
                is_global: isGlobalManager,
            }),
        })
            .then(() => {
                setNewTag('');
                loadTags();
            })
            .catch((requestError) => setError(requestError.message || __('Failed to add tag.', 'manfi-expense-tracker')));
    };

    const deleteTag = (id) => {
        setError('');

        requestJson(`${restBase}tags/${id}`, { method: 'DELETE' })
            .then(() => setTags((current) => current.filter((tag) => tag.id !== id)))
            .catch((requestError) => setError(requestError.message || __('Failed to delete tag.', 'manfi-expense-tracker')));
    };

    const handleTagClick = (tag) => {
        if (clickableNames && typeof onTagClick === 'function') {
            onTagClick(tag);
        }
    };

    return (
        <div className="manfiet-card">
            <h3 className="manfiet-card-title">{__('Expense Tags', 'manfi-expense-tracker')}</h3>
            {error && <p className="manfiet-alert manfiet-alert-error">{error}</p>}

            <div className="manfiet-form-row manfiet-mb-14">
                <input
                    type="text"
                    className="manfiet-input manfiet-flex-input"
                    placeholder={__('Enter tag name', 'manfi-expense-tracker')}
                    value={newTag}
                    onChange={(event) => setNewTag(event.target.value)}
                />
                <button type="button" className="manfiet-button manfiet-button-primary" onClick={addTag}>
                    {__('Add Tag', 'manfi-expense-tracker')}
                </button>
            </div>

            <div className="manfiet-tag-list">
                {tags.length > 0 ? (
                    tags.map((tag) => {
                        const isActive = activeTagName === tag.tag_name;
                        return (
                            <span key={tag.id} className={`manfiet-tag-chip-row ${isActive ? 'is-active' : ''}`}>
                                {clickableNames ? (
                                    <button
                                        type="button"
                                        className={`manfiet-inline-link manfiet-tag-name-link ${isActive ? 'is-active' : ''}`}
                                        onClick={() => handleTagClick(tag)}
                                    >
                                        {tag.tag_name}
                                    </button>
                                ) : (
                                    <span className="manfiet-tag-chip">{tag.tag_name}</span>
                                )}
                                <button
                                    type="button"
                                    className="manfiet-tag-remove"
                                    onClick={() => deleteTag(tag.id)}
                                    title={__('Remove tag', 'manfi-expense-tracker')}
                                    aria-label={__('Remove tag', 'manfi-expense-tracker')}
                                >
                                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M9 3L3 9M3 3L9 9" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                                    </svg>
                                </button>
                            </span>
                        );
                    })
                ) : (
                    <span className="manfiet-text-muted">{__('No tags added yet.', 'manfi-expense-tracker')}</span>
                )}
            </div>
        </div>
    );
};

export default TagManager;
