import React, { useState } from 'react';
import { View, ActivityIndicator } from 'react-native';
import { WebView } from 'react-native-webview';
import { trpc } from '@/src/trpc-client';
import { useGetEssentialConsts } from '@/src/api-hooks/essential-consts.api';
import { theme, MyText, MyTouchableOpacity } from 'common-ui';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';

interface WebViewWrapperProps {
  children: React.ReactNode;
}

export default function WebViewWrapper({ children }: WebViewWrapperProps) {
  const { data: constsData, isLoading } = useGetEssentialConsts();
  const [isClosed, setIsClosed] = useState(false);

  if (isLoading) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: theme.colors.gray1 }}>
        <ActivityIndicator size="large" color={theme.colors.brand500} />
        <MyText style={{ color: theme.colors.gray500, marginTop: 16 }}>Loading...</MyText>
      </View>
    );
  }

  const webviewHtml = constsData?.webviewHtml;
  const isWebviewClosable = constsData?.isWebviewClosable;

  if (webviewHtml && !isClosed) {
    return (
      <View style={{ flex: 1 }}>
        <WebView
          source={{ html: webviewHtml }}
          style={{ flex: 1 }}
          javaScriptEnabled={true}
          domStorageEnabled={true}
          startInLoadingState={true}
          scalesPageToFit={true}
        />
        {isWebviewClosable && (
          <View style={{ position: 'absolute', top: 40, right: 20 }}>
            <MyTouchableOpacity
              onPress={() => setIsClosed(true)}
              style={{
                backgroundColor: 'rgba(0,0,0,0.5)',
                borderRadius: 20,
                padding: 8,
              }}
            >
              <MaterialIcons name="close" size={24} color="white" />
            </MyTouchableOpacity>
          </View>
        )}
      </View>
    );
  }

  return <>{children}</>;
}