import React, { useMemo, useState } from "react";
import {
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import { useNavigation } from "@react-navigation/native";
import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
import type { ChatStackParamList } from "../../navigation/types";
import { useSession } from "../../state/session-context";
import { useI18n } from "../../i18n";
import { useTheme } from "../../theme";
import type { AppTheme } from "../../theme";
import EmpOverlay from "../../components/EmpOverlay";

export default function ChatNewScreen() {
  const manager = useSession();
  const navigation = useNavigation<NativeStackNavigationProp<ChatStackParamList>>();
  const { t } = useI18n();
  const theme = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);
  const placeholderColor = theme.colors.placeholder;
  const [mode, setMode] = useState<"direct" | "group">("direct");
  const [groupName, setGroupName] = useState("");
  const [selected, setSelected] = useState<string[]>([]);

  const options = useMemo(
    () => manager.session?.players.filter((player) => player.id !== manager.me?.id) ?? [],
    [manager.session, manager.me],
  );

  function toggleMember(id: string) {
    if (mode === "direct") {
      setSelected([id]);
      return;
    }
    setSelected((prev) =>
      prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id],
    );
  }

  if (!manager.session || !manager.me) {
    return (
      <View style={styles.container}>
        <Text style={styles.helper}>{t("common.loading")}</Text>
      </View>
    );
  }
  const showEmp = manager.session.blackoutActive && !manager.isBanker;

  return (
    <View style={styles.wrapper}>
      <ScrollView style={styles.scroll} contentContainerStyle={styles.container}>
        <Text style={styles.title}>{t("chat.newTitle")}</Text>

        <View style={styles.toggleRow}>
          <TouchableOpacity
            style={[styles.toggleButton, mode === "direct" ? styles.toggleActive : null]}
            onPress={() => {
              setMode("direct");
              setSelected([]);
            }}
          >
            <Text style={[styles.toggleText, mode === "direct" ? styles.toggleTextActive : null]}>
              {t("chat.direct")}
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.toggleButton, mode === "group" ? styles.toggleActive : null]}
            onPress={() => {
              setMode("group");
              setSelected([]);
            }}
          >
            <Text style={[styles.toggleText, mode === "group" ? styles.toggleTextActive : null]}>
              {t("chat.group")}
            </Text>
          </TouchableOpacity>
        </View>

        {mode === "group" && (
          <TextInput
            style={styles.input}
            placeholder={t("chat.groupName")}
            placeholderTextColor={placeholderColor}
            value={groupName}
            onChangeText={setGroupName}
          />
        )}

        <Text style={styles.sectionTitle}>{t("chat.choosePlayers")}</Text>
        {options.map((player) => {
          const active = selected.includes(player.id);
          return (
            <TouchableOpacity
              key={player.id}
              style={[styles.memberRow, active ? styles.memberActive : null]}
              onPress={() => toggleMember(player.id)}
            >
              <Text style={styles.memberName}>{player.name}</Text>
              <Text style={styles.memberMeta}>
                {player.role === "banker"
                  ? t("common.banker")
                  : player.isDummy
                  ? t("common.dummy")
                  : t("common.player")}
              </Text>
            </TouchableOpacity>
          );
        })}

        <TouchableOpacity
          style={styles.button}
          onPress={() => {
            if (showEmp) return;
            if (mode === "direct" && selected.length !== 1) return;
            if (mode === "group" && (!groupName.trim() || selected.length === 0)) return;
            manager.sendMessage({
              type: "group_create",
              sessionId: manager.sessionId,
              playerId: manager.me?.id,
              name: mode === "direct" ? t("chat.direct") : groupName.trim(),
              memberIds: selected,
            });
            navigation.goBack();
          }}
        >
          <Text style={styles.buttonText}>{t("chat.startChat")}</Text>
        </TouchableOpacity>
      </ScrollView>
      <EmpOverlay visible={showEmp} reason={manager.session.blackoutReason} />
    </View>
  );
}

const createStyles = (theme: AppTheme) =>
  StyleSheet.create({
    wrapper: {
      flex: 1,
      position: "relative",
    },
    scroll: {
      flex: 1,
      backgroundColor: theme.colors.background,
    },
    container: {
      padding: 20,
      gap: 12,
    },
    title: {
      fontSize: 20,
      fontWeight: "700",
      color: theme.colors.text,
    },
    toggleRow: {
      flexDirection: "row",
      gap: 8,
    },
    toggleButton: {
      flex: 1,
      paddingVertical: 10,
      borderRadius: 999,
      borderWidth: 1,
      borderColor: theme.colors.border,
      alignItems: "center",
      backgroundColor: theme.colors.surface,
    },
    toggleActive: {
      backgroundColor: theme.colors.primary,
      borderColor: theme.colors.primary,
    },
    toggleText: {
      color: theme.colors.text,
      fontWeight: "600",
    },
    toggleTextActive: {
      color: theme.colors.primaryText,
    },
    input: {
      borderWidth: 1,
      borderColor: theme.colors.border,
      backgroundColor: theme.colors.inputBackground,
      color: theme.colors.inputText,
      borderRadius: 12,
      paddingHorizontal: 12,
      paddingVertical: 10,
    },
    sectionTitle: {
      fontWeight: "600",
      marginTop: 8,
      color: theme.colors.text,
    },
    memberRow: {
      backgroundColor: theme.colors.surface,
      padding: 12,
      borderRadius: 12,
      flexDirection: "row",
      justifyContent: "space-between",
      alignItems: "center",
    },
    memberActive: {
      borderWidth: 1,
      borderColor: theme.colors.primary,
    },
    memberName: {
      fontWeight: "600",
      color: theme.colors.text,
    },
    memberMeta: {
      fontSize: 12,
      color: theme.colors.textMuted,
    },
    button: {
      backgroundColor: theme.colors.primary,
      paddingVertical: 12,
      borderRadius: 999,
      alignItems: "center",
      marginTop: 12,
    },
    buttonText: {
      color: theme.colors.primaryText,
      fontWeight: "600",
    },
    helper: {
      color: theme.colors.textMuted,
    },
  });
