import React, {useCallback, useState} from "react";
import {
    View, Text, ScrollView, TouchableOpacity,
    ActivityIndicator, useColorScheme,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import SearchBar from "../components/SearchBar";
import CollapsibleCategory from "../components/CollapsibleCategory";
import {useFocusEffect} from "expo-router";


const GROUPS = [
    { id: "1-year", label: "Prva godina", groupName: "Прва година", icon: "book-outline" as const, color: "#3B7DD8", darkColor: "#5E9EF4" },
    { id: "2-year", label: "Druga godina", groupName: "Друга година", icon: "book-outline" as const, color: "#2E9E6B", darkColor: "#4EC992" },
    { id: "3-year", label: "Treća godina", groupName: "Трећа година", icon: "book-outline" as const, color: "#9B4FB8", darkColor: "#C47CE0" },
    { id: "4-year", label: "Četvrta godina", groupName: "Четврта година", icon: "book-outline" as const, color: "#C4622D", darkColor: "#E07B45" },

    { id: "2-cycle", label: "Drugi ciklus", groupName: "Други циклус", icon: "book-outline" as const, color: "#3B7DD8", darkColor: "#5E9EF4" },
    { id: "3-cycle", label: "Treći ciklus", groupName: "Трећи циклус", icon: "book-outline" as const, color: "#2E9E6B", darkColor: "#4EC992" },
    { id: "postgraduate", label: "Postdiplomski studij", groupName: "Постдипломски студиј", icon: "book-outline" as const, color: "#9B4FB8", darkColor: "#C47CE0" },
    { id: "defenses", label: "Odbrane završnih radova", groupName: "Одбрана завршних радова", icon: "book-outline" as const, color: "#C4622D", darkColor: "#E07B45" },
];


export default function AllFeed() {
    const dark = useColorScheme() === "dark";
    const accent = dark ? "#E07B45" : "#C4622D";

    const [query,      setQuery]      = useState("");
    const [refreshKey, setRefreshKey] = useState(0);
    const [refreshing, setRefreshing] = useState(false);

    const visibleGroups = query.trim()
        ? GROUPS.filter((g) => g.label.toLowerCase().includes(query.toLowerCase()))
        : GROUPS;

    const handleRefresh = () => {
        setRefreshing(true);
        setRefreshKey((k) => k + 1);
        setTimeout(() => setRefreshing(false), 800);
    };

    useFocusEffect(
        useCallback(() => {
            handleRefresh();
        }, [])
    );

    return (
        <SafeAreaView className={`flex-1 ${dark ? "bg-obsidian-200" : "bg-parchment-50"}`}>
            {/* Header */}
            <View className={`border-b ${dark ? "border-border-dark" : "border-border-light"}`}>
                <View className="px-4 pt-2 pb-1 flex-row items-center">
                    <View className="flex-1">
                        <Text className={`text-2xl font-display font-bold ${dark ? "text-ink-dark" : "text-ink-light"}`}>
                            Discover
                        </Text>
                        <Text className={`text-xs mt-0.5 font-sans ${dark ? "text-muted-dark" : "text-muted-light"}`}>
                            {GROUPS.length} groups
                        </Text>
                    </View>

                    {/* Refresh button */}
                    <TouchableOpacity
                        onPress={handleRefresh}
                        disabled={refreshing}
                        className={`w-9 h-9 rounded-xl items-center justify-center ${
                            dark ? "bg-obsidian-50" : "bg-parchment-200"
                        }`}
                        activeOpacity={0.7}
                    >
                        {refreshing
                            ? <ActivityIndicator size="small" color={accent} />
                            : <Ionicons name="refresh-outline" size={18} color={accent} />
                        }
                    </TouchableOpacity>
                </View>

                <SearchBar placeholder="Search groups…" onSearch={setQuery} />
            </View>

            <ScrollView
                contentContainerStyle={{ paddingTop: 16, paddingBottom: 40 }}
                showsVerticalScrollIndicator={false}
                keyboardDismissMode="on-drag"
            >
                {visibleGroups.length === 0 ? (
                    <View className="items-center mt-16 px-8">
                        <Text className="text-4xl mb-3">🔍</Text>
                        <Text className={`text-base font-sans font-semibold text-center ${dark ? "text-ink-dark" : "text-ink-light"}`}>
                            No groups match &#34;{query}&#34;
                        </Text>
                    </View>
                ) : (
                    visibleGroups.map((group, index) => (
                        <CollapsibleCategory
                            key={group.id}
                            {...group}
                            refreshKey={refreshKey}
                        />
                    ))
                )}
            </ScrollView>
        </SafeAreaView>
    );
}