import React, { useState } from 'react';
import { useAppDispatch, useAppState } from '../state';

export function EventsPanel() {
    const dispatch = useAppDispatch();
    const { design, selectedWidgetId, vscode } = useAppState();
    const [eventType, setEventType] = useState('command');
    const [eventName, setEventName] = useState('onClick');
    const [eventCode, setEventCode] = useState('print("clicked")');

    const w = design.widgets.find((x) => x.id === selectedWidgetId);
    const widgetEvents = (id: string | undefined) =>
        (design.events || []).filter((e) => e.widget === id);

    const add = () => {
        if (!w) {
            vscode.postMessage({
                type: 'showError',
                text: 'Select a widget to add events to',
            });
            return;
        }
        if (!eventType || !eventName || !eventCode) {
            vscode.postMessage({
                type: 'showError',
                text: 'Please fill in all fields: event type, name, and code',
            });
            return;
        }
        dispatch({
            type: 'addEvent',
            payload: {
                widget: w.id,
                type: eventType,
                name: eventName,
                code: eventCode,
            },
        });
        vscode.postMessage({
            type: 'showInfo',
            text: `Event added: ${eventType} -> ${eventName}`,
        });
    };

    const remove = (type: string) => {
        if (!w) return;
        dispatch({ type: 'removeEvent', payload: { widget: w.id, type } });
        vscode.postMessage({ type: 'showInfo', text: 'Event removed' });
    };

    return (
        <div className="events-panel">
            <h3>Events & Commands</h3>
            <div id="eventsContent">
                {!w ? (
                    <p>Select a widget to configure events</p>
                ) : (
                    <div className="event-section">
                        <div className="event-controls">
                            <label className="property-label">
                                Event Type:
                            </label>
                            <input
                                className="event-type-select"
                                type="text"
                                value={eventType}
                                onChange={(e) => setEventType(e.target.value)}
                            />
                            <label className="property-label">
                                Handler Name:
                            </label>
                            <input
                                className="event-handler-input"
                                type="text"
                                value={eventName}
                                onChange={(e) => setEventName(e.target.value)}
                            />
                            <label className="property-label">
                                Handler Code:
                            </label>
                            <textarea
                                className="event-handler-input"
                                value={eventCode}
                                onChange={(e) => setEventCode(e.target.value)}
                            />
                        </div>
                        <div className="event-buttons">
                            <button className="event-btn primary" onClick={add}>
                                Add Event
                            </button>
                        </div>
                        <div className="event-list">
                            <h4>Configured Events</h4>
                            {widgetEvents(w.id).length === 0 ? (
                                <p>No events added yet.</p>
                            ) : (
                                widgetEvents(w.id).map((ev) => (
                                    <div
                                        className="event-item"
                                        key={`${ev.widget}-${ev.type}`}
                                    >
                                        <div className="event-info">
                                            <span className="event-name">
                                                {ev.name}
                                            </span>{' '}
                                            <span className="event-handler">
                                                {ev.type}
                                            </span>
                                            <div className="event-code">
                                                {ev.code}
                                            </div>
                                        </div>
                                        <div className="event-actions">
                                            <button
                                                className="event-btn secondary"
                                                onClick={() => remove(ev.type)}
                                            >
                                                Remove
                                            </button>
                                        </div>
                                    </div>
                                ))
                            )}
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
