import React, { useMemo } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useI18n } from "../i18n";
import { useTheme, type AppTheme } from "../theme";
import type { SessionConnectionState } from "../state/connection";

type ConnectionBannerProps = {
  connectionState: SessionConnectionState;
  reconnectAttempt: number;
  visible: boolean;
  onRetry: () => void;
};

export default function ConnectionBanner({
  connectionState,
  reconnectAttempt,
  visible,
  onRetry,
}: ConnectionBannerProps) {
  const { t } = useI18n();
  const theme = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);
  const insets = useSafeAreaInsets();

  if (!visible) {
    return null;
  }

  const title =
    connectionState === "connecting"
      ? t("connection.connecting")
      : t("connection.reconnecting");
  const detail = t("connection.reconnectingDetail", {
    count: reconnectAttempt || 1,
  });

  return (
    <View
      pointerEvents="box-none"
      style={[styles.wrapper, { top: insets.top + 8 }]}
    >
      <View style={styles.banner}>
        <View style={styles.copy}>
          <Text style={styles.title}>{title}</Text>
          <Text style={styles.detail}>{detail}</Text>
        </View>
        <TouchableOpacity style={styles.button} onPress={onRetry}>
          <Text style={styles.buttonText}>{t("common.retryNow")}</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

const createStyles = (theme: AppTheme) =>
  StyleSheet.create({
    wrapper: {
      position: "absolute",
      left: 12,
      right: 12,
      zIndex: 20,
    },
    banner: {
      borderRadius: 16,
      paddingHorizontal: 14,
      paddingVertical: 12,
      backgroundColor: theme.colors.headerBackground,
      borderWidth: 1,
      borderColor: theme.colors.border,
      flexDirection: "row",
      alignItems: "center",
      gap: 12,
      shadowColor: "#000",
      shadowOpacity: 0.12,
      shadowRadius: 10,
      shadowOffset: { width: 0, height: 4 },
      elevation: 4,
    },
    copy: {
      flex: 1,
      gap: 2,
    },
    title: {
      color: theme.colors.text,
      fontWeight: "700",
    },
    detail: {
      color: theme.colors.textMuted,
      fontSize: 12,
    },
    button: {
      borderRadius: 999,
      backgroundColor: theme.colors.primary,
      paddingHorizontal: 12,
      paddingVertical: 10,
    },
    buttonText: {
      color: theme.colors.primaryText,
      fontWeight: "600",
    },
  });
