import { FlatList, Text, ActivityIndicator, RefreshControl, Dimensions } from "react-native";
import { useState, useEffect } from "react";
import { Ionicons, MaterialCommunityIcons } 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 { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { KeyboardAvoidingView, Platform } from "react-native";
import {
    Actionsheet,
    ActionsheetContent,
    ActionsheetItem,
    ActionsheetItemText,
    ActionsheetDragIndicator,
    ActionsheetDragIndicatorWrapper,
    ActionsheetBackdrop,
} from "@/components/ui/actionsheet";
import {
    Select,
    SelectTrigger,
    SelectInput,
    SelectIcon,
    SelectPortal,
    SelectBackdrop,
    SelectContent,
    SelectDragIndicator,
    SelectDragIndicatorWrapper,
    SelectItem,
} from "@/components/ui/select";
import { ScrollView } from "react-native-gesture-handler";

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 [showSortSheet, setShowSortSheet] = 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) {
            if( params.sort == "latest"){
                result = [...result].sort(
                    (a, b) => new Date(b.publishDate) - new Date(a.publishDate)
                );
            }else if (params.sort == "oldest") {
                result = [...result].sort(
                    (a, b) => new Date(a.publishDate) - new Date(b.publishDate)
                );
            }else if (params.sort == "cheapest") {
                result = [...result].sort((a, b) => {
                    const priceA = parseFloat(a.price);
                    const priceB = parseFloat(b.price);
                    return isNaN(priceA) || isNaN(priceB) ? 0 : priceA - priceB;
                });
            }else if (params.sort == "expensive") {
                result = [...result].sort((a, b) => {
                    const priceA = parseFloat(a.price);
                    const priceB = parseFloat(b.price);
                    return isNaN(priceA) || isNaN(priceB) ? 0 : priceB - priceA;
                });
            }

        }

        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);
    }, [notices,
    params.category,
    params.sort,
    params.priceFrom,
    params.priceTo,
    params.search]);


    let filterActive = !!params.category || !!params.sort || !!params.priceFrom || !!params.priceTo || !!params.search;


    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 handleSort = (value) => {
        router.replace({
            pathname: "/notices",
            params: { ...params, sort: value }
        });
        setShowSortSheet(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" }}>
                <Box style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
                    <Button variant="outline" onPress={() => setShowActionsheet(true)}>
                        <ButtonText>Filtruj</ButtonText>
                        <Ionicons name="filter-outline" size={20} color="black" />
                    </Button>
                    <Button variant="outline" onPress={() => setShowSortSheet(true)}>
                        <Ionicons name="chevron-expand-outline" size={20} color="black" />
                    </Button>
                </Box>
                {filterActive && (
                    <Button variant="link" onPress={() => router.replace("/notices")}>
                        <ButtonText>Wyczyść</ButtonText>
                    </Button>
                )}
            </Box>
            <Actionsheet isOpen={showActionsheet} onClose={handleClose}>
                <ActionsheetBackdrop />
                <ActionsheetContent  style={{ maxHeight: SCREEN_HEIGHT * 0.6, width: '100%' }} >
    <KeyboardAwareScrollView
      contentContainerStyle={{ flexGrow: 1, width: '100%' }}
      enableOnAndroid={true}
      extraScrollHeight={40}
      >
                    <ActionsheetDragIndicatorWrapper>
                        <ActionsheetDragIndicator />
                    </ActionsheetDragIndicatorWrapper>
                    <Box className="mb-4" style={{ width: "100%" }}>
                        <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" style={{ flex: 1 }}>
                        <Select
                            style={{  flex: 1  }}
                            selectedValue={params.category || ''}
                            onValueChange={handleCategorySelect}
                        >
                            <SelectTrigger variant="outline" size="md">
                                <SelectInput
                                style={{ flex: 1 }}
                                    placeholder="Wybierz kategorię"
                                    value={selectedCategory ? selectedCategory.label : ""}
                                />
                                <SelectIcon style={{ marginRight: 12 }} as={ChevronDownIcon} />
                            </SelectTrigger>
                            <SelectPortal>
                                <SelectBackdrop />
                                <SelectContent
                                    style={{ maxHeight: SCREEN_HEIGHT * 0.6}}
                                >
                                    <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>
</KeyboardAwareScrollView>
                </ActionsheetContent>
            </Actionsheet>
            <Actionsheet isOpen={showSortSheet} onClose={() => setShowSortSheet(false)}>
                <ActionsheetBackdrop />
                <ActionsheetContent>
                    <ActionsheetDragIndicatorWrapper>
                        <ActionsheetDragIndicator />
                    </ActionsheetDragIndicatorWrapper>
                    <ActionsheetItem 
                    className={ !params.sort ? 'bg-gray-200' : ''}
                    onPress={() => handleSort()}>
                        <ActionsheetItemText>Trafność</ActionsheetItemText>
                    </ActionsheetItem>
                    <ActionsheetItem 
                     className={ params.sort == 'latest' ? 'bg-gray-200' : ''}
                    onPress={() => handleSort('latest')}>
                        <ActionsheetItemText>Najnowsze</ActionsheetItemText>
                    </ActionsheetItem>
                    <ActionsheetItem 
                     className={ params.sort == 'oldest' ? 'bg-gray-200' : ''}
                    onPress={() => handleSort('oldest')}>
                        <ActionsheetItemText>Najstarsze</ActionsheetItemText>
                    </ActionsheetItem>
                    <ActionsheetItem 
                     className={ params.sort == 'cheapest' ? 'bg-gray-200' : ''}
                     onPress={() => handleSort('cheapest')}>
                        <ActionsheetItemText>Najtańsze</ActionsheetItemText>
                    </ActionsheetItem>
                    <ActionsheetItem
                     className={ params.sort == 'expensive' ? 'bg-gray-200' : ''}
                    onPress={() => handleSort('expensive')}>
                        <ActionsheetItemText>Najdroższe</ActionsheetItemText>
                    </ActionsheetItem>
                </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"
                    />
                }
            />
        </>
    );
}