'use client';

import { useEffect, useState } from "react";

import AttendanceChart from "@/components/AttendanceChart";
import EventCalendar from "@/components/EventCalendar";
import Footer from "@/components/footer";
import UserCard from "@/components/UserCard";
import { useCurrentUser } from "../../../context/useCurrentUser";
import { useRouter } from "next/navigation";

const AdminPage = () => {
  const user = useCurrentUser();
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!user) {
      setLoading(true);
      const timer = setTimeout(() => {
        router.push("/");
      }, 2500); // delay 2.5 seconds

      return () => clearTimeout(timer);
    }
  }, [user, router]);

  if (!user && loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="animate-spin rounded-full h-20 w-20 border-4 border-t-blue-500 border-b-transparent border-l-transparent border-r-blue-500"></div>
        <p className="ml-4 text-lg font-semibold">Redirecting to login...</p>
      </div>
    );
  }

  if (!user) return null;

  return (
    <div>
      <div className="p-4 flex gap-4 flex-col md:flex-row">
        {/* LEFT SIDE */}
        <div className="w-full lg:w-2/3 flex flex-col gap-8">
          <div
            className="relative text-white p-6 rounded-md shadow-lg flex flex-col justify-between items-start min-h-[200px] bg-cover bg-center"
            style={{
              backgroundImage: `url('/Firefly.jpg')`,
              backgroundSize: "cover",
              backgroundPosition: "center",
              backgroundRepeat: "no-repeat",
            }}
          >
            <div className="absolute inset-0 bg-black bg-opacity-50 rounded-md"></div>
            <div className="relative z-10 flex flex-col gap-2">
              <h2 className="text-3xl font-bold">Welcome back, {user.name}</h2>
              <p className="text-lg">
                Hope you are having a productive day. 🚀
              </p>
            </div>
          </div>

          <div className="flex gap-4 justify-between flex-wrap rounded-md">
            <UserCard type="Visitors" value={120} />
            <UserCard type="Members" value={45} />
            <UserCard type="Inquiries" value={18} />
            <UserCard type="Prayer Requests" value={32} />
          </div>

          <div className="w-full h-[500px] rounded-md">
            <AttendanceChart />
          </div>
        </div>

        <div className="w-full lg:w-1/3 flex flex-col gap-8">
          <EventCalendar />
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default AdminPage;
