import React from "react";
import { Text, TouchableOpacity, View } from "react-native";
import { COLORS } from "@/lib/constants";

interface Props {
  children: React.ReactNode;
  screenName: string;
}

interface State {
  error: Error | null;
}

export class ScreenErrorBoundary extends React.Component<Props, State> {
  state: State = { error: null };

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

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

    return (
      <View className="flex-1 items-center justify-center bg-neutral-50 dark:bg-neutral-950 px-8">
        <Text selectable className="text-xl font-bold text-neutral-900 dark:text-white">
          {this.props.screenName} hit a snag
        </Text>
        <Text
          selectable
          className="mt-2 text-center text-sm text-neutral-500 dark:text-neutral-400"
        >
          This screen could not be rendered. The rest of Codexbar is still available.
        </Text>
        <TouchableOpacity
          onPress={() => this.setState({ error: null })}
          className="mt-5 rounded-xl px-4 py-3"
          style={{ backgroundColor: COLORS.codex }}
        >
          <Text className="text-sm font-semibold text-white">Try again</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
