import { Stack, useLocalSearchParams } from "expo-router";
import {
  ActivityIndicator,
  SafeAreaView,
  View,
  Text,
  StyleSheet,
  KeyboardAvoidingView,
  Platform,
} from "react-native";
import { Channel, MessageInput, MessageList, useChatContext } from "stream-chat-expo";
import { MessageCircle, Users, Smile } from "lucide-react-native";
import { useEffect, useState } from "react";
import { useHeaderHeight } from "@react-navigation/elements";
import { useThemeColor } from "@/hooks/useThemeColor";
import { useColorScheme } from "@/hooks/useColorScheme";

export default function ChannelScreen() {
  const { cid } = useLocalSearchParams<{ cid: string }>();
  const [type, id] = cid.split(":");
  const { client } = useChatContext();
  const channel = client.channel(type, id);
  const [hasMessages, setHasMessages] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const colorScheme = useColorScheme();

  const headerHeight = useHeaderHeight();

  // Theme-aware colors
  const backgroundColor = useThemeColor({ light: "#f8fafc", dark: "#111827" }, "background");
  const textColor = useThemeColor({ light: "#1f2937", dark: "#f9fafb" }, "text");
  const subtitleColor = useThemeColor({ light: "#6b7280", dark: "#9ca3af" }, "text");
  const iconColor = useThemeColor({ light: "#d1d5db", dark: "#6b7280" }, "icon");
  const iconSecondaryColor = useThemeColor({ light: "#e5e7eb", dark: "#4b5563" }, "icon");

  useEffect(() => {
    if (channel) {
      const checkMessages = async () => {
        try {
          // Get channel state to check for messages
          await channel.watch();
          const messages = channel.state.messages || [];
          setHasMessages(messages.length > 0);
        } catch (error) {
        } finally {
          setIsLoading(false);
        }
      };

      checkMessages();

      // Listen for new messages
      const handleNewMessage = () => {
        setHasMessages(true);
      };

      channel.on("message.new", handleNewMessage);

      return () => {
        channel.off("message.new", handleNewMessage);
      };
    }
  }, [channel]);

  if (!channel) {
    return <ActivityIndicator />;
  }

  const EmptyState = () => (
    <View style={styles.emptyContainer}>
      <View style={styles.emptyIconContainer}>
        <MessageCircle size={64} color={iconColor} strokeWidth={1.5} />
        <View style={styles.decorativeElements}>
          <View style={styles.floatingIcon1}>
            <Users size={20} color={iconSecondaryColor} />
          </View>
          <View style={styles.floatingIcon2}>
            <Smile size={18} color={iconSecondaryColor} />
          </View>
        </View>
      </View>

      <Text style={[styles.emptyTitle, { color: textColor }]}>Commencez la conversation</Text>
      <Text style={[styles.emptyMessage, { color: subtitleColor }]}>
        Soyez le premier à envoyer un message dans ce canal !
      </Text>
    </View>
  );

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor }}>
      <Channel channel={channel} keyboardVerticalOffset={headerHeight}>
        {isLoading ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color="#3b82f6" />
            <Text style={[styles.loadingText, { color: subtitleColor }]}>
              Chargement des messages...
            </Text>
          </View>
        ) : hasMessages ? (
          <MessageList />
        ) : (
          <EmptyState />
        )}
        <KeyboardAvoidingView
          behavior={Platform.OS === "ios" ? "padding" : "height"}
          keyboardVerticalOffset={Platform.OS === "ios" ? 0 : 20}
          style={styles.keyboardContainer}
        >
          <MessageInput />
        </KeyboardAvoidingView>
      </Channel>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    gap: 16,
  },
  loadingText: {
    fontSize: 16,
    fontWeight: "500",
  },
  emptyContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    paddingHorizontal: 40,
  },
  emptyIconContainer: {
    position: "relative",
    marginBottom: 32,
    width: 120,
    height: 120,
    justifyContent: "center",
    alignItems: "center",
  },
  decorativeElements: {
    position: "absolute",
    width: "100%",
    height: "100%",
  },
  floatingIcon1: {
    position: "absolute",
    top: 10,
    right: 5,
    backgroundColor: "rgba(255, 255, 255, 0.9)",
    borderRadius: 15,
    padding: 6,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  floatingIcon2: {
    position: "absolute",
    bottom: 15,
    left: 8,
    backgroundColor: "rgba(255, 255, 255, 0.9)",
    borderRadius: 12,
    padding: 5,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  emptyTitle: {
    fontSize: 24,
    fontWeight: "bold",
    marginBottom: 12,
    textAlign: "center",
  },
  emptyMessage: {
    fontSize: 16,
    textAlign: "center",
    lineHeight: 24,
    marginBottom: 32,
  },
  emptyHint: {
    backgroundColor: "rgba(255, 255, 255, 0.9)",
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 20,
    borderWidth: 1,
    borderColor: "rgba(0, 0, 0, 0.1)",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 1,
  },
  emptyHintText: {
    fontSize: 14,
    fontWeight: "500",
    textAlign: "center",
  },
  keyboardContainer: {
    flexShrink: 0,
  },
});
