import { useState, useEffect, useRef } from "react";
import axios from "axios";
import { useAppDispatch, useAppSelector } from "../../../../utils/hooks";
import { updateSendMessageData } from "../../../../store/Slices/SendMessageSlice";
import { useTheme } from "../../../../context/ThemeProvider";
import { IoSearchOutline } from "react-icons/io5";
import { ClipLoader } from "react-spinners";
import { useFile } from "../../../../context/FileProvider";

const GIPHY_API_KEY = import.meta.env.VITE_GIPHY_API_KEY;

export default function GiphyComponent() {
  const dispatch = useAppDispatch();
  const SendMessageData = useAppSelector((state) => state.SendMessageData);
  const sendMessageDataRef = useRef(SendMessageData);
  const [searchTerm, setSearchTerm] = useState("hello"); // Default trending
  const [gifs, setGifs] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { setSelectedFile } = useFile();

  // @ts-ignore
  const { theme } = useTheme();

  useEffect(() => {
    sendMessageDataRef.current = SendMessageData;
  }, [SendMessageData]);

  // Function to fetch GIFs from Giphy API
  const fetchGifs = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await axios.get(
        `https://api.giphy.com/v1/gifs/search?q=${searchTerm}&api_key=${GIPHY_API_KEY}&limit=18`,
      );
      setGifs(res.data.data); // Store the fetched GIFs
    } catch (err) {
      setError("Failed to load GIFs. Please try again.");
    }
    setLoading(false);
  };

  // Fetch GIFs when searchTerm changes
  useEffect(() => {
    if (searchTerm.trim()) {
      fetchGifs();
    }
  }, [searchTerm]);

  const handleGifClick = async (gif: any) => {
    try {
      // const response = await fetch(gif.images.original.url); // Fetch the GIF as a Blob
      // const blob = await response.blob(); // Convert it to a Blob
      // const file = new File([blob], `${gif.id}.gif`, { type: "image/gif" }); // Convert Blob to File

      //   console.log("Selected GIF File:", file);
      // setSelectedFile(file); // Set the selected File but in new version we are not using this
      dispatch(
        updateSendMessageData({
          showGiphyPicker: false,
          message: gif.images.original.url,
        }),
      );
    } catch (error) {
      console.error("Error fetching GIF:", error);
    }
  };

  return (
    <>
      <div
        className={`z-10 w-full max-w-xl bg-selectedChat transition duration-500 sm:-left-0`}
      >
        <div style={{ textAlign: "center", padding: "20px" }}>
          <h2>Send GIFs</h2>
          <div className="relative mb-6 mt-3 h-fit">
            <IoSearchOutline className="absolute left-3 top-2 text-2xl text-lightText" />
            <input
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className={` ${
                theme == "dark" ? "bg-transparent" : "bg-[#F2F2F2]"
              } w-full rounded-xl border border-borderColor py-2 pl-11 placeholder-lightText outline-none`}
              type="text"
              placeholder={"Search User"}
            />
          </div>

          {/* Loading & Error Handling */}

          {error && <p style={{ color: "red" }}>{error}</p>}

          {/* Display GIFs in a Grid */}
          {loading ? (
            <div className="grid h-96 place-content-center">
              <ClipLoader
                size={19}
                color={theme == "dark" ? "white" : "black"}
              />
            </div>
          ) : (
            <div className="grid max-h-[30rem] min-h-96 grid-cols-3 gap-3 overflow-auto">
              {gifs.map((gif) => (
                <img
                  key={gif.id}
                  src={gif.images.fixed_height.url}
                  alt={gif.title}
                  className="h-full w-full cursor-pointer rounded-lg object-cover"
                  onClick={() => handleGifClick(gif)} // Handle the click to set the file
                />
              ))}
            </div>
          )}
        </div>
      </div>
    </>
  );
}
