import { router } from "expo-router";
import {
  ChannelList,
  ChannelPreviewMessenger,
  ChannelPreviewMessengerProps,
  DefaultStreamChatGenerics,
} from "stream-chat-expo";
import { ChannelSort, Channel } from "stream-chat";
import { useUser } from "@/providers/UserProvider";
import { View, Text, StyleSheet, StatusBar } from "react-native";
import { LinearGradient } from "expo-linear-gradient";
import { Search } from "lucide-react-native";
import React, { useMemo } from "react";
import { useSharedValue } from "react-native-reanimated";
import { useTablosList } from "@/hooks/tablos";
import { ColorMap } from "@/constants/colors";
import { UserTablo } from "@/types/tablos.types";
import { SwipeableChannelPreview } from "@/components/SwipeableChannelPreview";
import { useThemeColor } from "@/hooks/useThemeColor";
import { useColorScheme } from "@/hooks/useColorScheme";

// Custom Avatar Component for Channel List

// Custom Title Component for bigger channel names
const CustomChannelTitle = ({ channel }: { channel: Channel }) => {
  const channelName = channel?.data?.name || channel?.id || "Channel";
  const textColor = useThemeColor({ light: "#1f2937", dark: "#f9fafb" }, "text");

  return (
    <Text style={[styles.customChannelTitle, { color: textColor }]} numberOfLines={1}>
      {channelName}
    </Text>
  );
};

// Custom Preview Component with Swipe to Archive
// Swipe left on any channel to reveal the archive button
const CustomChannelPreview = (props: ChannelPreviewMessengerProps<DefaultStreamChatGenerics>) => {
  return (
    <SwipeableChannelPreview channel={props.channel}>
      <ChannelPreviewMessenger {...props} />
    </SwipeableChannelPreview>
  );
};

export default function HomeScreen() {
  const user = useUser();
  const { data: tablos, isLoading } = useTablosList();
  const colorScheme = useColorScheme();

  // 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 cardBackgroundColor = useThemeColor({ light: "#ffffff", dark: "#1f2937" }, "background");
  const borderColor = colorScheme === "dark" ? "#374151" : "#e5e7eb";
  const placeholderColor = useThemeColor({ light: "#9ca3af", dark: "#6b7280" }, "text");
  const iconColor = useThemeColor({ light: "#6b7280", dark: "#9ca3af" }, "text");
  const emptyTextColor = useThemeColor({ light: "#4b5563", dark: "#d1d5db" }, "text");
  const emptyIconColor = useThemeColor({ light: "#d1d5db", dark: "#6b7280" }, "text");

  // Theme-aware gradient colors
  const gradientColors: [string, string, string] =
    colorScheme === "dark" ? ["#1f2937", "#374151", "#4b5563"] : ["#1e3a8a", "#3b82f6", "#60a5fa"];

  const loadingColors = {
    container: colorScheme === "dark" ? "#1f2937" : "#f8fafc",
    item: colorScheme === "dark" ? "#374151" : "#e5e7eb",
    itemSecondary: colorScheme === "dark" ? "#4b5563" : "#f3f4f6",
  };

  // const animations = useSharedValue<Record<string, number>>({});

  // Search animation state
  // const [isSearchVisible, setIsSearchVisible] = useState(false);
  // const [searchQuery, setSearchQuery] = useState("");
  // const [debouncedSearchQuery, setDebouncedSearchQuery] = useState("");
  const searchAnimation = useSharedValue(0);
  // const searchInputRef = useRef<TextInput>(null);

  // // Debounce search query for better performance
  // useEffect(() => {
  //   const timer = setTimeout(() => {
  //     setDebouncedSearchQuery(searchQuery);
  //   }, 300);

  //   return () => clearTimeout(timer);
  // }, [searchQuery]);

  // Create filters based on search query
  const filters = useMemo(() => {
    const baseFilters = {
      members: { $in: [user.id] },
      type: "messaging",
    };

    // Add name filter when searching
    // if (debouncedSearchQuery.trim()) {
    //   return {
    //     ...baseFilters,
    //     name: { $autocomplete: debouncedSearchQuery.trim() },
    //   };
    // }

    return baseFilters;
  }, [user.id]);

  const sort: ChannelSort = { last_updated: -1 };
  const options = {
    state: true,
    watch: true,
    limit: 20,
  };

  const CustomChannelAvatar = ({ channel, tablos }: { channel: Channel; tablos: UserTablo[] }) => {
    const tabloId = channel?.id || "";
    const tablo = tablos?.find((t) => t.id === tabloId);
    const tabloColor = tablo?.color || "bg-blue-500";
    const tabloName = tablo?.name || channel?.data?.name || "Tablo";

    // Get members info
    const members = channel?.state?.members || {};
    const memberCount = Object.keys(members).length;

    // Generate initials from tablo name
    const getInitials = (name: string) => {
      return name
        .split(" ")
        .map((word) => word.charAt(0))
        .join("")
        .toUpperCase()
        .slice(0, 2);
    };

    // // Create gradient colors based on tablo color
    const getTabloGradientColors = (colorKey: string): [string, string] => {
      const baseColor = ColorMap[colorKey] || ColorMap["bg-blue-500"];

      // Create a lighter version for gradient effect
      const lightenColor = (hex: string, percent: number): string => {
        const num = parseInt(hex.replace("#", ""), 16);
        const amt = Math.round(2.55 * percent);
        const R = Math.min(255, Math.max(0, (num >> 16) + amt));
        const G = Math.min(255, Math.max(0, ((num >> 8) & 0x00ff) + amt));
        const B = Math.min(255, Math.max(0, (num & 0x0000ff) + amt));
        return "#" + ((1 << 24) + (R << 16) + (G << 8) + B).toString(16).slice(1);
      };

      // Create a darker version for gradient effect
      const darkenColor = (hex: string, percent: number): string => {
        const num = parseInt(hex.replace("#", ""), 16);
        const amt = Math.round(2.55 * percent);
        const R = Math.min(255, Math.max(0, (num >> 16) - amt));
        const G = Math.min(255, Math.max(0, ((num >> 8) & 0x00ff) - amt));
        const B = Math.min(255, Math.max(0, (num & 0x0000ff) - amt));
        return "#" + ((1 << 24) + (R << 16) + (G << 8) + B).toString(16).slice(1);
      };

      const lightColor = lightenColor(baseColor, 15);
      const darkColor = darkenColor(baseColor, 10);

      return [lightColor, darkColor];
    };

    const initials = getInitials(tabloName);
    const gradientColors = getTabloGradientColors(tabloColor);

    return (
      <View style={styles.avatarContainer}>
        <LinearGradient
          colors={gradientColors}
          style={styles.avatarGradient}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
        >
          <Text style={styles.avatarInitials}>{initials}</Text>

          {/* Member count indicator for group channels */}
          {memberCount > 2 && (
            <View style={styles.memberCountBadge}>
              <Text style={styles.memberCountText}>{memberCount}</Text>
            </View>
          )}
        </LinearGradient>

        {/* Decorative ring */}
        <View style={[styles.avatarRing, { borderColor: `${ColorMap[tabloColor]}30` }]} />

        {/* Status indicator (online/active) */}
        <View style={[styles.statusIndicator, { borderColor: cardBackgroundColor }]} />
      </View>
    );
  };

  // Toggle search animation
  // const toggleSearch = () => {
  //   const toValue = isSearchVisible ? 0 : 1;

  //   searchAnimation.value = withTiming(toValue, {
  //     duration: 300,
  //   });

  //   if (toValue === 1) {
  //     // Focus input when animation starts
  //     setTimeout(() => searchInputRef.current?.focus(), 150);
  //   } else {
  //     // Clear search when hiding
  //     setSearchQuery("");
  //     setDebouncedSearchQuery("");
  //   }

  //   setIsSearchVisible(!isSearchVisible);
  // };

  // Close search when keyboard is dismissed
  // useEffect(() => {
  //   const keyboardDidHideListener = Keyboard.addListener(
  //     "keyboardDidHide",
  //     () => {
  //       if (isSearchVisible && searchQuery === "") {
  //         toggleSearch();
  //       }
  //     }
  //   );

  //   return () => {
  //     keyboardDidHideListener?.remove();
  //   };
  // }, [isSearchVisible, searchQuery]);

  // Animated styles using react-native-reanimated
  // const animatedSearchStyle = useAnimatedStyle(() => {
  //   const height = interpolate(
  //     searchAnimation.value,
  //     [0, 1],
  //     [0, 80],
  //     Extrapolate.CLAMP
  //   );

  //   const opacity = interpolate(
  //     searchAnimation.value,
  //     [0, 0.5, 1],
  //     [0, 0, 1],
  //     Extrapolate.CLAMP
  //   );

  //   return {
  //     height,
  //     opacity,
  //   };
  // });

  // Simple search header component - no memoization
  // const SearchHeader = () => (
  //   <Animated.View style={[styles.searchHeaderContainer, animatedSearchStyle]}>
  //     <View style={styles.searchInputContainer}>
  //       <Search size={18} color="#6b7280" style={styles.searchIcon} />
  //       <TextInput
  //         ref={searchInputRef}
  //         style={styles.searchInput}
  //         placeholder="Rechercher une conversation..."
  //         placeholderTextColor="#9ca3af"
  //         value={searchQuery}
  //         onChangeText={setSearchQuery}
  //         returnKeyType="search"
  //         autoCapitalize="none"
  //         autoCorrect={false}
  //         onSubmitEditing={() => {
  //           console.log("Searching for:", searchQuery);
  //           Keyboard.dismiss();
  //         }}
  //       />
  //       {searchQuery.length > 0 && (
  //         <TouchableOpacity
  //           onPress={() => {
  //             setSearchQuery("");
  //             setDebouncedSearchQuery("");
  //             searchInputRef.current?.focus();
  //           }}
  //           style={styles.clearButton}
  //         >
  //           <X size={16} color="#6b7280" />
  //         </TouchableOpacity>
  //       )}
  //     </View>

  //     {/* Search Results Info */}
  //     {debouncedSearchQuery.trim() && (
  //       <View style={styles.searchInfoContainer}>
  //         <Text style={styles.searchInfoText}>
  //           Recherche: "{debouncedSearchQuery}"
  //         </Text>
  //       </View>
  //     )}
  //   </Animated.View>
  // );

  if (isLoading) {
    return (
      <View style={[styles.container, { backgroundColor }]}>
        <StatusBar
          barStyle={colorScheme === "dark" ? "light-content" : "light-content"}
          backgroundColor={gradientColors[0]}
        />

        {/* Loading Header */}
        <LinearGradient
          colors={gradientColors}
          style={styles.headerGradient}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
        >
          <View style={styles.headerContent}>
            <View style={styles.headerBottom}>
              <View style={styles.titleContainer}>
                <Text style={styles.headerTitle}>Discussions</Text>
                <Text style={styles.headerSubtitle}>Chargement de vos conversations...</Text>
              </View>
            </View>
          </View>

          {/* Decorative Elements */}
          <View style={styles.decorativeCircle1} />
          <View style={styles.decorativeCircle2} />
        </LinearGradient>

        {/* Loading Content */}
        <View
          style={[styles.loadingContentContainer, { backgroundColor: loadingColors.container }]}
        >
          {/* Loading Skeleton Items */}
          {[1, 2, 3, 4, 5].map((item) => (
            <View key={item} style={styles.loadingItem}>
              <View style={[styles.loadingAvatar, { backgroundColor: loadingColors.item }]} />
              <View style={styles.loadingTextContainer}>
                <View style={[styles.loadingTitle, { backgroundColor: loadingColors.item }]} />
                <View
                  style={[styles.loadingSubtitle, { backgroundColor: loadingColors.itemSecondary }]}
                />
              </View>
            </View>
          ))}
        </View>
      </View>
    );
  }

  return (
    <View style={[styles.container, { backgroundColor }]}>
      <StatusBar
        barStyle={colorScheme === "dark" ? "light-content" : "light-content"}
        backgroundColor={gradientColors[0]}
      />

      {/* Beautiful Header */}
      <LinearGradient
        colors={gradientColors}
        style={styles.headerGradient}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
      >
        <View style={styles.headerContent}>
          <View style={styles.headerBottom}>
            <View style={styles.titleContainer}>
              <Text style={styles.headerTitle}>Discussions</Text>
              <Text style={styles.headerSubtitle}>
                {/* {debouncedSearchQuery.trim()
                  ? `Recherche: "${debouncedSearchQuery}"`
                  : "Gérez les conversations de vos tablos"} */}
                Gérez les conversations de vos tablos
              </Text>
            </View>

            {/* <TouchableOpacity
              style={styles.searchButton}
              onPress={toggleSearch}
            >
              {isSearchVisible ? (
                <X size={20} color="#3b82f6" />
              ) : (
                <Search size={20} color="#3b82f6" />
              )}
            </TouchableOpacity> */}
          </View>
        </View>

        {/* Decorative Elements */}
        <View style={styles.decorativeCircle1} />
        <View style={styles.decorativeCircle2} />
      </LinearGradient>

      {/* Channel List with animated search */}
      <View style={[styles.channelListContainer, { backgroundColor }]}>
        {/* <SearchHeader /> */}
        <ChannelList
          filters={filters}
          onSelect={(channel) => {
            // Close search when selecting a channel
            // if (isSearchVisible) {
            //   toggleSearch();
            // }
            router.push(`/channel/${channel.cid}`);
          }}
          sort={sort}
          options={options}
          Preview={(props) => (
            <CustomChannelPreview
              {...props}
              // animations={animations}
              // cancelOtherAnimations={(id) => {
              //   animations.value = {
              //     [id]: 0,
              //   };
              // }}
            />
          )}
          PreviewAvatar={(props) => (
            <CustomChannelAvatar channel={props.channel} tablos={tablos || []} />
          )}
          PreviewTitle={CustomChannelTitle}
          // ListHeaderComponent={SearchHeader}
          // Show loading state during search
          LoadingIndicator={() => (
            <View style={styles.searchLoadingContainer}>
              <Text style={[styles.searchLoadingText, { color: subtitleColor }]}>
                {/* {debouncedSearchQuery
                  ? "Recherche en cours..."
                  : "Chargement..."} */}
                Chargement...
              </Text>
            </View>
          )}
          // Show empty state when no results
          EmptyStateIndicator={() => (
            <View style={styles.emptySearchContainer}>
              <Search size={48} color={emptyIconColor} />
              <Text style={[styles.emptySearchTitle, { color: emptyTextColor }]}>
                {/* {debouncedSearchQuery
                  ? "Aucun résultat"
                  : "Aucune conversation"} */}
                Aucune conversation
              </Text>
              <Text style={[styles.emptySearchMessage, { color: subtitleColor }]}>
                {/* {debouncedSearchQuery
                  ? `Aucune conversation trouvée pour "${debouncedSearchQuery}"`
                  : "Vous n'avez pas encore de conversations"} */}
                Vous n'avez pas encore de conversations
              </Text>
            </View>
          )}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    // backgroundColor is set dynamically
  },
  headerGradient: {
    paddingTop: 50,
    paddingBottom: 25,
    paddingHorizontal: 20,
    position: "relative",
    overflow: "hidden",
  },
  headerContent: {
    zIndex: 10,
  },
  headerTop: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 20,
  },
  userInfo: {
    flexDirection: "row",
    alignItems: "center",
    flex: 1,
  },
  avatar: {
    marginRight: 12,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 5,
    borderWidth: 3,
    borderColor: "rgba(255, 255, 255, 0.3)",
  },
  greetingContainer: {
    flex: 1,
  },
  greeting: {
    fontSize: 16,
    color: "rgba(255, 255, 255, 0.9)",
    fontWeight: "500",
  },
  userName: {
    fontSize: 20,
    color: "white",
    fontWeight: "bold",
    marginTop: 2,
  },
  headerActions: {
    flexDirection: "row",
    alignItems: "center",
    gap: 15,
  },
  actionButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: "rgba(255, 255, 255, 0.2)",
    justifyContent: "center",
    alignItems: "center",
    position: "relative",
  },
  notificationBadge: {
    position: "absolute",
    top: -2,
    right: -2,
    backgroundColor: "#ef4444",
    borderRadius: 10,
    minWidth: 20,
    height: 20,
    justifyContent: "center",
    alignItems: "center",
    borderWidth: 2,
    borderColor: "white",
  },
  badgeText: {
    color: "white",
    fontSize: 12,
    fontWeight: "bold",
  },
  headerBottom: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-end",
  },
  titleContainer: {
    flex: 1,
  },
  headerTitle: {
    fontSize: 28,
    color: "white",
    fontWeight: "bold",
    marginBottom: 4,
  },
  headerSubtitle: {
    fontSize: 16,
    color: "rgba(255, 255, 255, 0.8)",
    fontWeight: "400",
  },
  searchButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: "white",
    justifyContent: "center",
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 8,
    elevation: 4,
  },
  decorativeCircle1: {
    position: "absolute",
    top: -50,
    right: -30,
    width: 120,
    height: 120,
    borderRadius: 60,
    backgroundColor: "rgba(255, 255, 255, 0.1)",
  },
  decorativeCircle2: {
    position: "absolute",
    bottom: -20,
    left: -20,
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: "rgba(255, 255, 255, 0.08)",
  },
  channelListContainer: {
    flex: 1,
    // backgroundColor is set dynamically
    marginTop: -10,
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    paddingTop: 10,
  },

  // Custom Avatar Styles
  avatarContainer: {
    position: "relative",
    width: 56,
    height: 56,
    marginRight: 12,
  },
  avatarGradient: {
    width: 56,
    height: 56,
    borderRadius: 16,
    justifyContent: "center",
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.15,
    shadowRadius: 8,
    elevation: 6,
    position: "relative",
  },
  avatarInitials: {
    fontSize: 18,
    fontWeight: "bold",
    color: "white",
    textShadowColor: "rgba(0, 0, 0, 0.3)",
    textShadowOffset: { width: 0, height: 1 },
    textShadowRadius: 2,
  },
  avatarRing: {
    position: "absolute",
    top: -2,
    left: -2,
    width: 60,
    height: 60,
    borderRadius: 18,
    borderWidth: 2,
    borderColor: "rgba(59, 130, 246, 0.2)",
    backgroundColor: "transparent",
  },
  statusIndicator: {
    position: "absolute",
    bottom: 2,
    right: 2,
    width: 16,
    height: 16,
    borderRadius: 8,
    backgroundColor: "#10b981",
    borderWidth: 3,
    // borderColor is set dynamically to match background
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 4,
    elevation: 3,
  },
  memberCountBadge: {
    position: "absolute",
    top: -4,
    right: -4,
    backgroundColor: "#3b82f6",
    borderRadius: 10,
    minWidth: 20,
    height: 20,
    justifyContent: "center",
    alignItems: "center",
    borderWidth: 2,
    borderColor: "white",
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 4,
    elevation: 3,
  },
  memberCountText: {
    color: "white",
    fontSize: 11,
    fontWeight: "bold",
  },
  // Custom Channel Title Styles
  customChannelTitle: {
    fontSize: 18,
    fontWeight: "bold",
    // color is set dynamically
  },

  // Search Header Styles
  searchHeaderContainer: {
    // backgroundColor is set dynamically
    borderBottomWidth: 1,
    // borderBottomColor is set dynamically
    overflow: "hidden",
    paddingHorizontal: 20,
  },
  searchInputContainer: {
    flexDirection: "row",
    alignItems: "center",
    // backgroundColor is set dynamically
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderWidth: 1,
    // borderColor is set dynamically
    marginTop: 15,
  },
  searchIcon: {
    marginRight: 10,
  },
  searchInput: {
    flex: 1,
    fontSize: 16,
    // color is set dynamically
    paddingVertical: 0,
    fontWeight: "500",
  },
  clearButton: {
    padding: 5,
  },
  searchInfoContainer: {
    paddingTop: 10,
    paddingBottom: 15,
  },
  searchInfoText: {
    fontSize: 14,
    // color is set dynamically
  },
  searchLoadingContainer: {
    paddingVertical: 20,
    alignItems: "center",
  },
  searchLoadingText: {
    fontSize: 16,
    // color is set dynamically
  },
  emptySearchContainer: {
    paddingVertical: 40,
    alignItems: "center",
  },
  emptySearchTitle: {
    fontSize: 20,
    // color is set dynamically
    marginTop: 10,
  },
  emptySearchMessage: {
    fontSize: 16,
    // color is set dynamically
    marginTop: 5,
    textAlign: "center",
    paddingHorizontal: 20,
  },

  // Loading Skeleton Styles
  loadingContentContainer: {
    flex: 1,
    // backgroundColor is set dynamically
    marginTop: -10,
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    paddingTop: 20,
    paddingHorizontal: 20,
  },
  loadingItem: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 12,
    marginBottom: 8,
  },
  loadingAvatar: {
    width: 56,
    height: 56,
    borderRadius: 16,
    // backgroundColor is set dynamically
    marginRight: 12,
  },
  loadingTextContainer: {
    flex: 1,
  },
  loadingTitle: {
    height: 20,
    // backgroundColor is set dynamically
    borderRadius: 4,
    marginBottom: 8,
    width: "70%",
  },
  loadingSubtitle: {
    height: 16,
    // backgroundColor is set dynamically
    borderRadius: 4,
    width: "50%",
  },
});
