import React from 'react';
import tw from 'twin.macro';

type Props = {
    children: React.ReactNode;
    fallbackTitle?: string;
};

type State = {
    error: Error | null;
};

/**
 * Wraps a tab/subtree so one component crash does not nuke the whole panel.
 * The reset button forces React to re-instantiate children — usually enough
 * for transient errors (race conditions on stale state, missing API field).
 */
export default class FirewallErrorBoundary extends React.Component<Props, State> {
    state: State = { error: null };

    static getDerivedStateFromError(error: Error): State {
        return { error };
    }

    componentDidCatch(error: Error, info: React.ErrorInfo) {
        // eslint-disable-next-line no-console
        console.error('[firewall] subtree crashed:', error, info);
    }

    private reset = () => this.setState({ error: null });

    render() {
        if (!this.state.error) return this.props.children;

        const title = this.props.fallbackTitle ?? 'This section failed to render';
        return (
            <div
                css={tw`rounded-lg p-4 mb-4 bg-red-900/25 border border-red-700/40`}
                role="alert"
            >
                <p css={tw`text-sm font-semibold text-red-300 mb-1`}>{title}</p>
                <p css={tw`text-xs text-red-200/80 mb-3 font-mono`}>{this.state.error.message}</p>
                <button
                    type="button"
                    onClick={this.reset}
                    css={tw`text-xs px-3 py-1.5 rounded bg-red-700/40 hover:bg-red-700/70 text-red-100 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/60`}
                >
                    Retry
                </button>
            </div>
        );
    }
}
