import { Ionicons } from "@expo/vector-icons";
import React, { useCallback, useRef, useState } from "react";
import {
  FlatList,
  Image,
  Platform,
  StyleSheet,
  TouchableOpacity,
  View,
  useWindowDimensions,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

import { CategoryPills } from "@/components/CategoryPills";
import { VideoCard } from "@/components/VideoCard";
import { useColors } from "@/hooks/useColors";
import { VIDEOS, type Video } from "@/data/mockData";

export default function FeedScreen() {
  const colors = useColors();
  const insets = useSafeAreaInsets();
  const { height } = useWindowDimensions();
  const [selectedCat, setSelectedCat] = useState("all");
  const [activeIndex, setActiveIndex] = useState(0);

  const topPad = Platform.OS === "web" ? 67 : insets.top;
  const bottomPad = Platform.OS === "web" ? 34 : insets.bottom;

  const filteredVideos =
    selectedCat === "all"
      ? VIDEOS
      : VIDEOS.filter((v) => v.categoryId === selectedCat);

  const viewabilityConfig = useRef({
    itemVisiblePercentThreshold: 70,
  });

  const onViewableItemsChanged = useRef(
    ({
      viewableItems,
    }: {
      viewableItems: Array<{ index: number | null }>;
    }) => {
      if (viewableItems.length > 0 && viewableItems[0].index != null) {
        setActiveIndex(viewableItems[0].index);
      }
    }
  );

  const renderItem = useCallback(
    ({ item, index }: { item: Video; index: number }) => (
      <VideoCard
        video={item}
        height={height}
        bottomInset={bottomPad}
        isActive={index === activeIndex}
      />
    ),
    [height, bottomPad, activeIndex]
  );

  const keyExtractor = useCallback((item: Video) => item.id, []);

  return (
    <View style={[s.screen, { backgroundColor: colors.background }]}>
      <FlatList
        data={filteredVideos}
        renderItem={renderItem}
        keyExtractor={keyExtractor}
        pagingEnabled
        snapToInterval={height}
        decelerationRate="fast"
        showsVerticalScrollIndicator={false}
        viewabilityConfig={viewabilityConfig.current}
        onViewableItemsChanged={onViewableItemsChanged.current}
        scrollEnabled={filteredVideos.length > 0}
        getItemLayout={(_, index) => ({
          length: height,
          offset: height * index,
          index,
        })}
      />

      <View
        style={[
          s.header,
          {
            top: topPad,
            paddingTop: Platform.OS === "web" ? 8 : 0,
          },
        ]}
        pointerEvents="box-none"
      >
        <View style={s.headerTop} pointerEvents="box-none">
          <View style={s.logoPill}>
            <Image
              source={require("../../assets/images/logo.png")}
              style={s.logoImg}
              resizeMode="contain"
            />
          </View>
          <View style={s.headerRight}>
            <TouchableOpacity style={s.iconBtn}>
              <Ionicons name="notifications-outline" size={22} color="#fff" />
            </TouchableOpacity>
          </View>
        </View>
        <View pointerEvents="box-none">
          <CategoryPills
            selected={selectedCat}
            onSelect={setSelectedCat}
            style={{ paddingLeft: 0 }}
          />
        </View>
      </View>
    </View>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1 },
  header: {
    position: "absolute",
    left: 0,
    right: 0,
    zIndex: 10,
  },
  headerTop: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 16,
    paddingBottom: 8,
  },
  logoPill: {
    backgroundColor: "rgba(0,0,0,0.55)",
    borderRadius: 12,
    paddingHorizontal: 10,
    paddingVertical: 5,
    borderWidth: 1,
    borderColor: "rgba(255,255,255,0.1)",
  },
  logoImg: {
    width: 130,
    height: 34,
  },
  headerRight: { flexDirection: "row", gap: 8 },
  iconBtn: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: "rgba(0,0,0,0.3)",
    alignItems: "center",
    justifyContent: "center",
  },
});
