import React, { useEffect, useState } from 'react'
import { IoSearchOutline } from "react-icons/io5";
import Card from '../components/Card';
import { GetPosts } from '../api';

const Home = () => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [search, setSearch] = useState("");
  const [filterPost, setFilterPost] = useState([]);

  const getPost = async () => {
    setLoading(true)
    await GetPosts().then((res) => {
      setLoading(false)
      setPosts(res?.data?.data);
      setFilterPost(res?.data?.data);

    }).catch((error) => {
      setError(error?.response?.data?.message);
      setLoading(false)
    })
  }

  useEffect(() => {
    getPost()
  }, [])

  useEffect(() => {
    if(!search){
      setFilterPost(posts);
    }
    const searchFilterPost = posts.filter((post) => {
      const promptMatch = post?.prompt?.toLowerCase().includes(search.toString().toLowerCase())
      const authorMatch = post?.name?.toLowerCase().includes(search.toString().toLowerCase())

      return promptMatch || authorMatch; 
    })
    if(search){
      setFilterPost(searchFilterPost)
    }

  }, [posts, search])

  return (
    <div className='h-full overflow-y-scroll p-5 flex flex-col gap-5 items-center'>
      <p className='flex px-2 text-2xl text-[#F6F1E9] text-center'>Explore our popular images using AI generator</p>
      {/*=== Search ===*/}
      <div className='w-[100%] sm:w-[50%] flex border rounded-sm overflow-hidden'>
        <input value={search} onChange={(e) => setSearch(e.target.value)} type="text" placeholder='What do you want to see?' className='w-[95%] border-none p-2 outline-none bg-black'/>
        <button  className='w-[5%] flex justify-center items-center duration-300 font-semibold'><IoSearchOutline/></button>
      </div>


      <div className='max-w-[1500px] w-full flex justify-center py-5'>
        {error && <div className='text-red-500'>{error}</div>}
        {loading ? (<>Loading...</>) : (
        <div className='grid gap-[10px] grid-cols-4 max-[999px]:grid-cols-3 max-[640px]:grid-cols-2'>
          {
            filterPost.length === 0 ? (<p>No post...</p>) : ( 
            <>
              {filterPost.slice().reverse().map((item, index) => (
                <Card key={index} item={item}/>
              ))}
            </>
          )}
        </div>
        )}
      </div>
    </div>
  )
}

export default Home