"use client";

import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import {
  FileText,
  Calendar,
  Filter,
  RefreshCcw,
  ArrowLeftRight,
  Trash2,
  Plus,
  Edit3,
} from "lucide-react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Loading from "../components/Loading";
// import { formatWIB } from "../lib/formatWIB";

export default function ActivityLogsPage() {
  const PAGE_SIZE = 10;
  const formatWIB = (date?: string | Date | null) => {
    if (!date) return "-";

    return new Date(date).toLocaleString("id-ID", {
      timeZone: "Asia/Jakarta",
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
  };
  const getActionStyle = (action: string) => {
    switch (action) {
      case "CREATE":
        return "bg-green-50 border-green-200 text-green-800";
      case "ADD_ITEM":
        return "bg-blue-50 border-blue-200 text-blue-800";
      case "DELETE_ITEM":
        return "bg-red-50 border-red-200 text-red-800";
      case "UPDATE":
        return "bg-yellow-50 border-yellow-200 text-yellow-800";
      default:
        return "bg-gray-50 border-gray-200 text-gray-800";
    }
  };

  const { data: session, status } = useSession();
  const router = useRouter();
  const currentUser = session?.user as any;

  const [logs, setLogs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");

  const [page, setPage] = useState(1);

  const fetchLogs = async () => {
    setLoading(true);

    let url = "/api/activity-logs";

    if (startDate && endDate) {
      url += `?start=${startDate}&end=${endDate}`;
    }

   const res = await fetch(url, {
    cache: "no-store",
  });
    const json = await res.json();

    setLogs(json.data || []);
    setLoading(false);
  };

  useEffect(() => {
      // 1. tunggu session selesai load
  if (status === "loading") return;

  // 2. kalau belum login
  if (status === "unauthenticated") {
    router.replace("/login");
    return;
  }

    fetchLogs();
  }, [status]);

  const filtered = logs;

  const totalPages = Math.ceil(filtered.length / PAGE_SIZE);
  const start = (page - 1) * PAGE_SIZE;
  const paginated = filtered.slice(start, start + PAGE_SIZE);

  const getIcon = (action: string) => {
    switch (action) {
      case "CREATE":
        return <Plus className="w-4 h-4 text-green-600" />;
      case "UPDATE":
        return <Edit3 className="w-4 h-4 text-yellow-600" />;
      case "DELETE":
        return <Trash2 className="w-4 h-4 text-red-600" />;
      default:
        return <FileText className="w-4 h-4 text-gray-600" />;
    }
  };

  return (
    <div className="min-h-screen p-6 relative overflow-hidden bg-linear-to-b from-green-50 via-emerald-50 to-lime-50">

      {/* 🌿 glow background */}
      <div className="absolute -top-40 -left-40 w-125 h-125 bg-green-300/20 blur-[160px]" />
      <div className="absolute bottom-0 right-0 w-125 h-125 bg-lime-300/20 blur-[160px]" />

      {/* HEADER 3D */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="relative rounded-[40px] overflow-hidden shadow-[0_70px_180px_rgba(0,0,0,0.25)]"
      >
        <div className="absolute inset-0 bg-linear-to-br from-green-700 via-emerald-500 to-lime-400" />
        <div className="absolute inset-0 bg-white/10 backdrop-blur-2xl" />

        <div className="relative p-6 flex items-center justify-between">

          <div>
            <h1 className="text-2xl md:text-3xl font-bold text-white flex items-center gap-2">
              <FileText className="w-6 h-6" />
              🌾 Activity Logs
            </h1>
            <p className="text-white/80 text-sm">
              Audit trail semua aktivitas sistem
            </p>
          </div>

          <button
            onClick={fetchLogs}
            className="px-4 py-2 rounded-xl bg-white/20 text-white border border-white/30 hover:bg-white/30 transition flex items-center gap-2"
          >
            <RefreshCcw className="w-4 h-4" />
            Refresh
          </button>
        </div>
      </motion.div>

      {/* FILTER SECTION */}
      <div className="mt-6 grid md:grid-cols-3 gap-4">

        {/* start date */}
        <div className="relative group">
          <div className="absolute inset-0 translate-y-3 bg-green-300/20 blur-2xl rounded-2xl" />

          <div className="relative p-4 rounded-2xl bg-white/70 backdrop-blur-2xl border border-white/40 shadow-xl">
            <label className="text-xs text-gray-500 flex items-center gap-2">
              <Calendar className="w-4 h-4" /> Start Date
            </label>
            <input
              type="date"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
              className="w-full mt-2 bg-transparent outline-none text-green-800"
            />
          </div>
        </div>

        {/* end date */}
        <div className="relative group">
          <div className="absolute inset-0 translate-y-3 bg-green-300/20 blur-2xl rounded-2xl" />

          <div className="relative p-4 rounded-2xl bg-white/70 backdrop-blur-2xl border border-white/40 shadow-xl">
            <label className="text-xs text-gray-500 flex items-center gap-2">
              <Calendar className="w-4 h-4" /> End Date
            </label>
            <input
              type="date"
              value={endDate}
              onChange={(e) => setEndDate(e.target.value)}
              className="w-full mt-2 bg-transparent outline-none text-green-800"
            />
          </div>
        </div>

        {/* filter button */}
        <div className="flex items-end">
          <button
            onClick={() => {
              setPage(1);
              fetchLogs();
            }}
            className="w-full px-4 py-3 rounded-2xl bg-linear-to-br from-green-600 to-emerald-500 text-white font-semibold shadow-xl flex items-center justify-center gap-2 hover:scale-[1.02] transition"
          >
            <Filter className="w-4 h-4" />
            Apply Filter
          </button>
        </div>
      </div>

      {/* LIST */}
      <div className="mt-6 space-y-4">

        {loading && (
          <div className="text-green-700 animate-pulse">
            🌿 Loading activity logs...
          </div>
        )}

        {!loading && paginated.map((log, i) => (
          <motion.div
            key={log.id}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: i * 0.03 }}
            className="relative group"
          >
            {/* depth */}
            <div className="absolute inset-0 translate-y-3 bg-green-300/20 blur-2xl rounded-2xl" />

            {/* card */}
            {/* <div className="relative flex items-start gap-4 p-5 rounded-2xl bg-white/70 backdrop-blur-2xl border border-white/40 shadow-xl hover:-translate-y-1 transition"> */}
            <div className={`relative flex items-start gap-4 p-5 rounded-2xl border shadow-xl ${getActionStyle(log.action)}`}>

              {/* icon */}
              <div className="w-10 h-10 rounded-xl bg-white flex items-center justify-center shadow-inner">
                {getIcon(log.action)}
              </div>

              {/* content */}
              <div className="flex-1">

                <div className="flex justify-between">
                  <h3 className="font-semibold text-green-900">
                    {log.entity}
                  </h3>

                  <span className="text-xs text-gray-500">
                    {/* {new Date(log.created_at).toLocaleString()} */}
                    {formatWIB(log.created_at)}
                          {/* {log.created_at} */}
                  </span>
                </div>

                <p className="text-sm text-gray-600 mt-1">
                  {log.description}
                </p>

                <div className="mt-2 text-xs text-green-700 font-medium">
                  Action: {log.action} • ID: {log.entity_id}
                </div>

                <div className="text-xs text-gray-500 mt-1">
                  Created by: <span className="font-semibold">{log.created_by_name || "-"}</span>
                </div>

              </div>
            </div>
          </motion.div>
        ))}
      </div>

      {/* PAGINATION */}
      {filtered.length > PAGE_SIZE && (
        <div className="flex justify-center items-center gap-3 mt-8">

          <button
            disabled={page === 1}
            onClick={() => setPage((p) => p - 1)}
            className="px-4 py-2 rounded-xl bg-white/70 border text-green-700 disabled:opacity-40"
          >
            Prev
          </button>

          <div className="text-sm text-green-800 font-medium">
            Page {page} / {totalPages}
          </div>

          <button
            disabled={page === totalPages}
            onClick={() => setPage((p) => p + 1)}
            className="px-4 py-2 rounded-xl bg-white/70 border text-green-700 disabled:opacity-40"
          >
            Next
          </button>

        </div>
      )}

    </div>
  );
}