import React, { useEffect, useState } from "react";
import axios from "axios";
import CharacterCard from "../components/CharacterCard";

const Home = () => {
  const [page, setPage] = useState(1);
  const [data, setData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [loading, setLoading] = useState(true);
  const [suggestions, setSuggestions] = useState([]);

  const increment = () => {
    setPage(page + 1);
  };

  const decrement = () => {
    setPage(page - 1);
  };

  useEffect(() => {
    axios.get(`https://swapi.py4e.com/api/people/?page=${page}`).then((res) => {
      setData(res.data.results);
      setFilteredData(res.data.results);
    });
  }, [page]);



  useEffect(() => {
    const timer = setTimeout(() => {
      setLoading(false);
    }, 1500);

    return () => clearTimeout(timer);
  }, []);




  const handleSearch = (e) => {
    const query = e.target.value.toLowerCase();
    setSearchQuery(query);

    if (query === "") {
      setFilteredData(data);
      setSuggestions([]);
      return;
    }

    // FILTERING DATA TO LOWERCASE
    const filtered = data.filter((character) =>
      character.name.toLowerCase().includes(query)
    );
    setFilteredData(filtered);

    // AUTOCOMPLETE SUGGESTION
    const autoSuggestions = data
      .map((character) => character.name)
      .filter((name) => name.toLowerCase().includes(query))
      .slice(0, 5);
    setSuggestions(autoSuggestions);
  };

  // HANDLING SUGGESTION ONCLICK EVENT
  const handleSuggestionClick = (suggestion) => {
    setSearchQuery(suggestion);
    setFilteredData(
      data.filter(
        (character) => character.name.toLowerCase() === suggestion.toLowerCase()
      )
    );
    setSuggestions([]);
  };

  return (
    <div className="main">
      <div className="header-container">
        <div className="header">
          <img src="/images/logo.png" alt="Logo" />
        </div>

        <div className="search-container">
          <input
            type="text"
            placeholder="Search by name..."
            value={searchQuery}
            onChange={handleSearch}
            className="search-input"
          />
          {suggestions.length > 0 && (
            <ul className="suggestions">
              {suggestions.map((suggestion, index) => (
                <li
                  key={index}
                  className="suggestion-item"
                  onClick={() => handleSuggestionClick(suggestion)}
                >
                  {suggestion}
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>

      {loading ? (
        <ul className="skeleton-character-container">
       {[...(data || Array(5))].map((_, index) => (
            <li className="skeleton-character-card skeleton" key={index}>
              <div className="skeleton-character-details">
                <div className="skeleton-line skeleton-title"></div>
                <div className="skeleton-line"></div>
                <div className="skeleton-line"></div>
                <div className="skeleton-line"></div>
                <div className="skeleton-line"></div>
              </div>
            </li>
          ))}
        </ul>
      ) : (
        <CharacterCard data={filteredData} />
      )}

      <div className="changePage">
        <button className="button" disabled={page === 1} onClick={decrement}>
          Previous
        </button>
        <button className="button" onClick={increment}>
          Next
        </button>
      </div>
    </div>
  );
};

export default Home;
