"use client";

import Image from "next/image";
import { motion } from "framer-motion";
import { useEffect, useState } from "react";
import { getAgentData } from "@/service/agent";

type Agent = {
  id: number;
  name: string;
  job_title: string;
  status_id: number;
  profile_picture_url: string;
  created_at: string;
};

export default function Agent() {
  const [agents, setAgents] = useState<Agent[]>([]);

  useEffect(() => {
    const fetchAgents = async () => {
      try {
        const req = {
          limit: "10",
          page: 1,
          search: "",
        };

        const res = await getAgentData(req);

        const agentsData: Agent[] = res?.data?.data || [];

        const latestApprovedAgents = agentsData
          .filter((agent) => agent.status_id === 2) // ✅ approved only
          .sort(
            (a, b) =>
              new Date(b.created_at).getTime() -
              new Date(a.created_at).getTime(),
          ) // ✅ newest first
          .slice(0, 5); // ✅ max 5

        setAgents(latestApprovedAgents);
      } catch (error) {
        console.error("Failed to fetch agents:", error);
      }
    };

    fetchAgents();
  }, []);

  return (
    <section className="py-16 px-6 md:px-5 bg-[#FAFDFF] text-center mt-0">
      <motion.h2
        initial={{ opacity: 0, y: 30 }}
        whileInView={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.6 }}
        viewport={{ once: true }}
        className="text-3xl md:text-6xl font-semibold text-gray-900 mb-2"
      >
        Our Teams
      </motion.h2>

      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-2 place-items-center mt-10">
        {agents.map((agent, index) => (
          <motion.div
            key={agent.id}
            initial={{ opacity: 0, y: 40 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{
              duration: 0.6,
              delay: index * 0.2 + 0.3,
              ease: "easeOut",
            }}
            viewport={{ once: true, amount: 0.3 }}
            className="bg-white shadow-md py-4 gap-2 flex flex-col items-center h-[300px] w-[250px]"
          >
            <div className="relative w-44 h-48 mb-3">
              <Image
                src={agent.profile_picture_url}
                alt={agent.name}
                fill
                className="rounded-full object-cover"
              />
            </div>

            <h3 className="text-lg text-gray-900 text-center">{agent.name}</h3>

            <p className="text-sm text-gray-600 text-center mt-1">
              {agent.job_title}
            </p>
          </motion.div>
        ))}
      </div>
    </section>
  );
}
