"use client";

import { urlFor } from "@/lib/sanity";
import { blogPost, getBlogPosts } from "@/lib/services/blog.service";
import { motion, useInView } from "framer-motion";
import Image from "next/image";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { BiSolidDonateHeart } from "react-icons/bi";

const InsightsSection = () => {
  const [insights, setInsights] = useState<blogPost[]>([]);

  useEffect(() => {
    const fetchPosts = async () => {
      try {
        const data = await getBlogPosts();
        setInsights(data);
      } catch (error) {
        console.log("Failed to fetch Insights", error);
      }
    };

    fetchPosts();
  }, []);
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true });
  return (
    <motion.div
      ref={ref}
      initial={{ opacity: 0, y: 100 }}
      animate={isInView ? { opacity: 1, y: 0 } : {}}
      transition={{ duration: 0.5, delay: 0.5 }}
      className="lg:w-10/12 py-20 px-5 lg:px-0 lg:mx-auto"
    >
      <div className="mb-16">
        <h1 className="text-5xl lg:text-6xl custom-oswald font-semibold">
          Stories & Insights
        </h1>
      </div>
      <div className="grid lg:grid-cols-3 md:grid-cols-2 gap-10">
        {insights.length > 0 &&
          insights.map((item, idx) => (
            <div className="border-4 hover:border-colour-1 p-6 group border-dashed">
              <div className="relative mb-5 min-h-52">
                <Image
                  src={urlFor(item.postImage).url()}
                  alt={item.title}
                  layout="fill"
                  objectFit="cover"
                  className=""
                />
              </div>
              <div className="space-y-5">
                <Link href={`/media-and-insights/${item.currentSlug}`}>
                  <h1 className="text-2xl group-hover:font-semibold">
                    {item.title}
                  </h1>
                </Link>
                <div className="flex justify-between">
                  <h2>
                    {new Date(item.dateCreated).toLocaleDateString("en-US", {
                      year: "numeric",
                      month: "short",
                      day: "2-digit",
                    })}
                  </h2>
                  <Link
                    href={`/media-and-insights/${item.currentSlug}`}
                    className="bg-colour-1 text-white px-4 py-1"
                  >
                    Read
                  </Link>
                </div>
              </div>
            </div>
          ))}
      </div>
      <div className="flex mt-12 items-center justify-center">
        <Link href="/media-and-insights" className="px-7 py-4 border-2 border-colour-1">
          READ MORE
        </Link>
      </div>
    </motion.div>
  );
};

export default InsightsSection;
