/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useState } from "react"
import axios from "axios"
import PageIntro from "../PageIntro"
import styles from "./crypto-news.module.scss"
import CryptoCard from "./CryptoCard"

const CryptoNews = () => {
  const API_KEY = "pub_79818e2290a1a4b2c339f64fa177647f9d1f6" // POWERED BY https://newsdata.io/api-key
  const [news, setNews] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchNews = async () => {
      try {
        setLoading(true)
        const response = await axios.get(
          `https://newsdata.io/api/1/news?apikey=${API_KEY}&q=crypto&language=en`
        )
        const data = response.data?.results || []
        setNews(data)
      } catch (err) {
        console.error("Error fetching crypto news:", err)
        setError("Failed to fetch crypto news. Please try again later.")
      } finally {
        setLoading(false)
      }
    }

    fetchNews()
  }, [])

  return (
    <div className={styles["crypto__news"]}>
      <PageIntro
        title="Crypto Latest News"
        description="Do not miss out on anything. Follow market trends and updates as they happen!"
      />

      {loading ? (
        <p className={styles["loading-text"]}>Fetching latest crypto news...</p>
      ) : error ? (
        <p className={styles["error-text"]}>{error}</p>
      ) : news.length > 0 ? (
        <div className={styles["crypto__news__grid"]}>
          {news.map((singleNews, index) => (
            <CryptoCard key={singleNews?.link || index} news={singleNews} />
          ))}
        </div>
      ) : (
        <p className={styles["no-news-text"]}>No crypto news found.</p>
      )}
    </div>
  )
}

export default CryptoNews
