import axios from 'axios'
import Link from 'next/link'
import React, { useEffect, useState } from 'react'
import { format } from 'date-fns'
import { IoCalendarOutline } from 'react-icons/io5'

const WhatsNewMonthlyUpdate = () => {
  const [data, setData] = useState([])

  useEffect(() => {
    const fetchData = async () => {
      try {
        let cachedData = localStorage.getItem('monthlyReleaseData')
        if (cachedData) {
          // If cached data is available, parse and set it
          setData(JSON.parse(cachedData))
        } else {
          const response = await axios.get(
            'https://cmswp.gwkbali.com/wp-json/wp/v2/monthly-release/',
            {
              // headers: {
              //   'Cache-Control': 'public, max-age=3600, must-revalidate',
              // },
            }
          )
          setData(response.data)
          // Cache the fetched data in local storage
          localStorage.setItem(
            'monthlyReleaseData',
            JSON.stringify(response.data)
          )
        }
      } catch (error) {
        console.error('Error fetching data:', error)
      }
    }

    fetchData()
  }, [])

  return (
    <div>
      {data.slice(0, 1).map((item) => (
        <div key={item.id}>
          <div>
            <Link href={`/monthly-release/${item.slug}`}>
              <h3 className="pb-2 text-3xl font-semibold leading-tight text-yellow-600 duration-150 ease-in hover:text-stone-900 sm:text-3xl ">
                {item.title.rendered}
              </h3>
            </Link>
            <div className="pb-2">
              <span className="inline-flex items-center font-sans text-sm text-stone-600">
                <IoCalendarOutline />
                &nbsp;{format(new Date(item.date), 'dd-MM-yyyy')}
              </span>
            </div>
            <p
              className="pb-2 font-sans text-base font-light sm:text-base"
              dangerouslySetInnerHTML={{
                __html: item.excerpt.rendered,
              }}
            ></p>
            <div id="readmore" className="readmore">
              <Link
                href={`/monthly-release/${item.slug}`}
                className="readmore font-sans text-xs text-yellow-600 hover:text-stone-900 hover:underline"
              >
                Read more
              </Link>
            </div>
          </div>
        </div>
      ))}
    </div>
  )
}

export default WhatsNewMonthlyUpdate
