import { Component, type ErrorInfo, type ReactNode } from "react";

interface Props {
	children: ReactNode;
	viewName: string;
}

interface State {
	hasError: boolean;
	error: Error | null;
}

export class ErrorBoundary extends Component<Props, State> {
	constructor(props: Props) {
		super(props);
		this.state = { hasError: false, error: null };
	}

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

	componentDidCatch(error: Error, info: ErrorInfo): void {
		console.error("[ErrorBoundary]", this.props.viewName, error, info);
	}

	render(): ReactNode {
		if (this.state.hasError) {
			return (
				<div className="flex h-full w-full items-center justify-center p-8">
					<div className="flex max-w-md flex-col gap-4 rounded-md border border-border bg-card p-6 text-center shadow-sm">
						<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
							{this.props.viewName}
						</p>
						<p className="text-sm font-semibold text-foreground">
							Something went wrong in this view
						</p>
						{this.state.error && (
							<p className="rounded bg-accent px-3 py-2 text-left font-mono text-xs text-muted-foreground">
								{this.state.error.message}
							</p>
						)}
						<button
							type="button"
							className="mt-2 rounded-md border border-border bg-background px-4 py-2 text-sm font-medium text-foreground transition-colors hover:bg-accent"
							onClick={() => this.setState({ hasError: false, error: null })}
						>
							Reload view
						</button>
					</div>
				</div>
			);
		}

		return this.props.children;
	}
}
