import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  SafeAreaView,
  ScrollView,
  ImageBackground,
  TextInput,
  TouchableOpacity,
  StyleSheet,
} from "react-native";
import Feather from "@expo/vector-icons/Feather";
import ListItem from "../components/ListItem/ListItem";
import filter from "lodash.filter";
import { globalStyles } from "../styles/global";
import { getRequest } from "../request";

const HomeScreen = ({ navigation }) => {
  const [posts, setPosts] = useState([]);

  const [query, setQuery] = useState("");
  const [filteredData, setFilteredData] = useState(posts);

  const contains = (name, search) => {
    if (name.includes(search)) {
      return true;
    }
    return false;
  };

  const searchFilter = (text) => {
    const formatedText = text.toLowerCase();

    const data = filter(posts, (item) => {
      return contains(item?.attributes.title.toLowerCase(), formatedText);
    });
    setFilteredData(data);
    setQuery(formatedText);
  };

  const fetchAll = async () => {
    const { data } = await getRequest("api/posts?populate=*");

    if (data.data) {
      setPosts(data.data);
    }
  };

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

  useEffect(() => {
    if (posts) {
      setFilteredData(posts);
    }
  }, [posts]);
  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: "#fff" }}>
      <ScrollView style={{ padding: 20 }}>
        <View style={styles.wrapper}>
          <Text style={{ fontSize: 18 }}>Hello Diligent</Text>
          <TouchableOpacity onPress={() => navigation.openDrawer()}>
            <ImageBackground
              source={require("../assets/images/diligent-purple.png")}
              style={styles.imageBackground}
              imageStyle={{ borderRadius: 25 }}
            />
          </TouchableOpacity>
        </View>
        <View style={styles.search}>
          <Feather
            name="search"
            size={20}
            color="#C6C6C6"
            style={{ marginRight: 5 }}
          />
          <TextInput
            onChangeText={(text) => searchFilter(text)}
            autoCapitalize="none"
            autoCorrect={false}
            placeholder="Search"
            value={query}
            placeholderTextColor="#C6C6C6"
          />
        </View>
        <Text>
          {filteredData.length === 0 && (
            <View>
              <Text style={globalStyles.boldText}>No Results Found</Text>
            </View>
          )}
        </Text>
        {query.length === 0
          ? posts.map((post) => (
              <ListItem
                key={post.id}
                title={post.attributes.title}
                photo={post.attributes.profileImage.data.attributes.formats}
                publishedAt={post.attributes.publishedAt}
                onPress={() =>
                  navigation.navigate("PostDetails", {
                    title: post.attributes.title,
                    id: post.id,
                  })
                }
              />
            ))
          : filteredData.map((post) => (
              <ListItem
                key={post.id}
                title={post.attributes.title}
                photo={post.attributes.profileImage.data.attributes.formats}
                publishedAt={post.attributes.publishedAt}
                onPress={() =>
                  navigation.navigate("PostDetails", {
                    title: post.attributes.title,
                    id: post.id,
                  })
                }
              />
            ))}
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  wrapper: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 20,
  },
  imageBackground: {
    width: 35,
    height: 35,
  },
  search: {
    flexDirection: "row",
    borderColor: "#C6C6C6",
    borderWidth: 1,
    borderRadius: 8,
    paddingHorizontal: 10,
    paddingVertical: 8,
    marginBottom: 20,
  },
});

export default HomeScreen;
