import React, { useCallback, useMemo } from "react";
import { Alert, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { useI18n } from "../i18n";
import { useSession } from "../state/session-context";
import { useTheme } from "../theme";
import type { AppTheme } from "../theme";

type ExitGameButtonProps = {
  mode?: "header" | "full";
};

export default function ExitGameButton({ mode = "header" }: ExitGameButtonProps) {
  const { t } = useI18n();
  const manager = useSession();
  const theme = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);

  const handlePress = useCallback(() => {
    Alert.alert(t("session.exitPrompt"), t("session.exitMessage"), [
      { text: t("common.cancel"), style: "cancel" },
      {
        text: t("common.exit"),
        style: "destructive",
        onPress: () => manager.leaveSession(),
      },
    ]);
  }, [manager, t]);

  if (!manager.sessionId) return null;

  if (mode === "full") {
    return (
      <TouchableOpacity style={styles.fullButton} onPress={handlePress}>
        <Text style={styles.fullButtonText}>{t("session.exit")}</Text>
      </TouchableOpacity>
    );
  }

  return (
    <TouchableOpacity style={styles.headerButton} onPress={handlePress}>
      <View style={styles.headerPill}>
        <Text style={styles.headerText}>{t("session.exit")}</Text>
      </View>
    </TouchableOpacity>
  );
}

const createStyles = (theme: AppTheme) =>
  StyleSheet.create({
    headerButton: {
      paddingHorizontal: 8,
      paddingVertical: 6,
    },
    headerPill: {
      borderRadius: 999,
      borderWidth: 1,
      borderColor: theme.colors.danger,
      paddingHorizontal: 10,
      paddingVertical: 4,
    },
    headerText: {
      color: theme.colors.danger,
      fontSize: 12,
      fontWeight: "600",
    },
    fullButton: {
      borderRadius: 999,
      borderWidth: 1,
      borderColor: theme.colors.danger,
      paddingVertical: 12,
      alignItems: "center",
      backgroundColor: theme.colors.surface,
      marginTop: 8,
    },
    fullButtonText: {
      color: theme.colors.danger,
      fontWeight: "600",
    },
  });
