import { FlatList, Text, ActivityIndicator, RefreshControl, Dimensions } from "react-native";
import { useState, useEffect } from "react";
import { Ionicons } from "@expo/vector-icons";
import { useNoticesStore } from "@/store/noticesStore";
import { NoticeCard } from "@/components/NoticeCard";
import { useLocalSearchParams, useRouter } from "expo-router";
import { Box } from "@/components/ui/box";
import { Button, ButtonText } from "@/components/ui/button";
import { ChevronDownIcon } from "@/components/ui/icon";
import { listCategories } from "@/api/categories";
import { FormControl, FormControlLabel } from "@/components/ui/form-control";
import { Input, InputField } from "@/components/ui/input";
import { HStack } from "@/components/ui/hstack";
import {
    Actionsheet,
    ActionsheetContent,
    ActionsheetDragIndicator,
    ActionsheetDragIndicatorWrapper,
    ActionsheetBackdrop,
} from "@/components/ui/actionsheet";
import {
    Select,
    SelectTrigger,
    SelectInput,
    SelectIcon,
    SelectPortal,
    SelectBackdrop,
    SelectContent,
    SelectDragIndicator,
    SelectDragIndicatorWrapper,
    SelectItem,
} from "@/components/ui/select";

export default function Notices() {
    // Hooks
    const { notices, fetchNotices } = useNoticesStore();
    const [refreshing, setRefreshing] = useState(false);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const [showActionsheet, setShowActionsheet] = useState(false);
    const [categories, setCategories] = useState([]);
    const [filteredNotices, setFilteredNotices] = useState([]);
    const params = useLocalSearchParams();
    const router = useRouter();

    useEffect(() => {
        const fetchSelectItems = async () => {
            try {
                const data = await listCategories();
                if (Array.isArray(data)) {
                    setCategories(data);
                } else {
                    console.error('listCategories did not return an array:', data);
                    setError(new Error('Invalid categories data'));
                }
            } catch (error) {
                console.error('Error fetching select items:', error);
                setError(error);
            }
        };
        fetchSelectItems();
    }, []);

    useEffect(() => {
        loadData();
    }, []);

    useEffect(() => {
        let result = notices;

        if (params.category) {
            result = result.filter(notice => notice.category === params.category);
        }

        if (params.sort === "latest") {
            result = [...result].sort(
                (a, b) => new Date(b.publishDate) - new Date(a.publishDate)
            );
        }

        if(params.priceFrom) {
            result = result.filter(notice => {
                const price = parseFloat(notice.price);
                const priceFrom = parseFloat(params.priceFrom);
                return !isNaN(price) && price >= priceFrom;
            });
        }

        if (params.priceTo) {
            result = result.filter(notice => {
                const price = parseFloat(notice.price);
                const priceTo = parseFloat(params.priceTo);
                return !isNaN(price) && price <= priceTo;
            });
        }

        
        if (params.search) {
            const searchTerm = params.search.toLowerCase();
            result = result.filter(notice =>{
                 return notice.title.toLowerCase().includes(searchTerm);
            });
        }

        setFilteredNotices(result);
    }, );


    let filterActive = !!params.category || params.sort === "latest";


    const loadData = async () => {
        setIsLoading(true);
        try {
            await fetchNotices();
            setError(null);
        } catch (err) {
            setError(err);
        } finally {
            setIsLoading(false);
        }
    };

    const handleCategorySelect = (value) => {
        router.replace({
            pathname: "/notices",
            params: { ...params, category: value }
        });
    };

    const handlePriceFrom = (value) => {
         router.replace({
            pathname: "/notices",
            params: { ...params, priceFrom: value }
        });
    }

    const handlePriceTo = (value) => {
        router.replace({
            pathname: "/notices",
            params: { ...params, priceTo: value }
        });
    }

    const handleClose = () => setShowActionsheet(false);

    const onRefresh = async () => {
        setRefreshing(true);
        try {
            await fetchNotices();
        } catch (err) {
            setError(err);
        } finally {
            setRefreshing(false);
        }
    };

    if (isLoading && !refreshing) {
        return <ActivityIndicator />;
    }

    if (error) {
        return <Text>Nie udało się pobrać listy. {error.message}</Text>;
    }

    const SCREEN_HEIGHT = Dimensions.get('window').height;

    const selectedCategory = params.category && categories?.find(
        (cat) => cat.value === params.category
    ) || null;

    return (
        <>
            <Box style={{ flexDirection: "row", padding: 8, paddingTop: 16, paddingBottom: 16, backgroundColor: "white", alignItems: "center", justifyContent: "space-between" }}>
                <Button variant="outline" onPress={() => setShowActionsheet(true)}>
                    <ButtonText>Filtry</ButtonText>
                    <Ionicons name="filter-outline" size={20} color="black" />
                </Button>
                {filterActive && (
                    <Button variant="link" onPress={() => router.replace("/notices")}>
                        <ButtonText>Wyczyść</ButtonText>
                    </Button>
                )}
            </Box>
            <Actionsheet isOpen={showActionsheet} onClose={handleClose}>
                <ActionsheetBackdrop />
                <ActionsheetContent>
                    <ActionsheetDragIndicatorWrapper>
                        <ActionsheetDragIndicator />
                    </ActionsheetDragIndicatorWrapper>
                    <Box className="mb-4">
                        <HStack space="md" style={{ width: "100%"}}>
                            <FormControl
                                style={{ flex: 1 }}>
                                <Input>
                                    <InputField
                                        keyboardType="numeric"
                                        placeholder="Od:"
                                        value={params.priceFrom || ''}
                                        onChangeText={handlePriceFrom}
                                    />
                                </Input>
                            </FormControl>
                            <FormControl
                                style={{ flex: 1 }}>
                                <Input>
                                    <InputField
                                        keyboardType="numeric"
                                        placeholder="Do:"
                                        value={params.priceTo || ''} 
                                        onChangeText={handlePriceTo}
                                    />
                                </Input>
                            </FormControl>
                        </HStack>
                    </Box>
                    <Box className="mb-4 w-full">
                        <Select
                            style={{ width: '100%' }}
                            selectedValue={params.category || ''}
                            onValueChange={handleCategorySelect}
                        >
                            <SelectTrigger variant="outline" size="md">
                                <SelectInput
                                    placeholder="Wybierz kategorię"
                                    value={selectedCategory ? selectedCategory.label : ""}
                                />
                                <SelectIcon style={{ marginRight: 12 }} as={ChevronDownIcon} />
                            </SelectTrigger>
                            <SelectPortal>
                                <SelectBackdrop />
                                <SelectContent
                                    style={{ maxHeight: SCREEN_HEIGHT * 0.6, width: '100%' }}
                                >
                                    <SelectDragIndicatorWrapper>
                                        <SelectDragIndicator />
                                    </SelectDragIndicatorWrapper>
                                    <FlatList
                                        style={{ width: '100%' }}
                                        data={categories}
                                        keyExtractor={(item) => item.value?.toString() || item.id?.toString() || Math.random().toString()}
                                        renderItem={({ item }) => (
                                            <SelectItem
                                                label={item.label}
                                                value={item.value}
                                            />
                                        )}
                                    />
                                </SelectContent>
                            </SelectPortal>
                        </Select>
                    </Box>

                </ActionsheetContent>
            </Actionsheet>
            <FlatList
                data={filteredNotices}
                numColumns={2}
                columnWrapperStyle={{ gap: 8, marginHorizontal: 8 }}
                contentContainerStyle={{ paddingBottom: 16 }}
                renderItem={({ item }) => <NoticeCard notice={item} />}
                refreshControl={
                    <RefreshControl
                        refreshing={refreshing}
                        onRefresh={onRefresh}
                        colors={["#3b82f6"]}
                        tintColor="#3b82f6"
                    />
                }
            />
        </>
    );
}