import { useState, useEffect } from "react";
import { Link } from "react-router";
import { LuCheck, LuX, LuPencil, LuPlus } from "react-icons/lu";

// Define the TypeScript interface for the log
interface ActivityLog {
  log_id: number;
  user_id: number;
  log_action: string;
  log_target: string;
  log_target_id: number;
  log_detail: string;
  created_at: string;
  user: {
    user_id: number;
    user_name: string;
  };
  target_activity?: {
    activity_id: number;
    activity_title: string;
  };
}

export default function ActivityRecentOrders() {
  const [logs, setLogs] = useState<ActivityLog[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/system-logs", {
      credentials: "include",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    })
      .then((res) => res.json())
      .then((data) => {
        // Take only the latest 5 for the timeline
        setLogs(data.slice(0, 5));
        setLoading(false);
      })
      .catch((err) => {
        console.error("Failed to fetch logs:", err);
        setLoading(false);
      });
  }, []);

  const getLogConfig = (action: string) => {
    switch (action.toLowerCase()) {
      case "completed":
        return {
          icon: <LuCheck className="size-5" />,
          bgColor: "bg-success-50 dark:bg-success-500/10",
          iconColor: "text-success-600 dark:text-success-500",
          label: "Completed Activity",
        };
      case "canceled":
        return {
          icon: <LuX className="size-5" />,
          bgColor: "bg-error-50 dark:bg-error-500/10",
          iconColor: "text-error-600 dark:text-error-500",
          label: "Canceled Activity",
        };
      case "added":
        return {
          icon: <LuPlus className="size-5" />,
          bgColor: "bg-brand-50 dark:bg-brand-500/10",
          iconColor: "text-brand-600 dark:text-brand-500",
          label: "Added Activity",
        };
      case "updated":
      default:
        return {
          icon: <LuPencil className="size-5" />,
          bgColor: "bg-warning-50 dark:bg-warning-500/10",
          iconColor: "text-warning-600 dark:text-warning-500",
          label: "Updated Activity",
        };
    }
  };

  const formatTimestamp = (dateStr: string) => {
    const date = new Date(dateStr);
    const now = new Date();

    // Reset hours to compare dates only
    const dDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    const dNow = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const diffDays = Math.floor((dNow.getTime() - dDate.getTime()) / (1000 * 60 * 60 * 24));

    const time = date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", hour12: false });

    if (diffDays === 0) {
      return `today ${time} WIB`;
    } else if (diffDays === 1) {
      return `yesterday ${time} WIB`;
    } else {
      const day = date.getDate();
      const months = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"];
      const month = months[date.getMonth()];
      const year = date.getFullYear();
      return `${day} ${month} ${year} ${time} WIB`;
    }
  };

  if (loading) {
    return (
      <div className="overflow-hidden rounded-2xl border border-gray-200 bg-white px-4 pb-3 pt-4 dark:border-gray-800 dark:bg-white/[0.03] sm:px-6">
        <div className="flex items-center justify-center p-10">
          <div className="w-8 h-8 border-4 border-brand-500 border-t-transparent rounded-full animate-spin"></div>
        </div>
      </div>
    );
  }

  return (
    <div className="overflow-hidden rounded-2xl border border-gray-200 bg-white px-4 pb-6 pt-4 dark:border-gray-800 dark:bg-white/[0.03] sm:px-6">
      <div className="flex flex-col gap-2 mb-8 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h3 className="text-lg font-semibold text-gray-800 dark:text-white/90">
            Activity Log
          </h3>
        </div>
        <Link
          to="/activity-log"
          className="text-sm font-medium text-brand-500 hover:text-brand-600 dark:text-brand-400 dark:hover:text-brand-300"
        >
          See all
        </Link>
      </div>

      <div className="relative space-y-10 pb-2">
        {logs.length > 0 ? (
          logs.map((log, index) => {
            const config = getLogConfig(log.log_action);
            const formattedDate = formatTimestamp(log.created_at);

            return (
              <div key={log.log_id} className="relative pl-16">
                {/* Discrete vertical line segment in the gap between icons */}
                {index !== logs.length - 1 && (
                  <div className="absolute left-[22.5px] top-[54px] h-7 w-[3px] bg-gray-200/60 dark:bg-gray-800/60 rounded-full" />
                )}

                <div
                  className={`absolute left-0 top-0 flex h-12 w-12 items-center justify-center rounded-full ${config.bgColor} ${config.iconColor} transition-transform hover:scale-105 z-10`}
                >
                  {config.icon}
                </div>
                <div className="pt-0.5">
                  <h4 className="text-[17px] font-semibold text-gray-900 dark:text-white/90 leading-tight">
                    {config.label} “{log.target_activity?.activity_title || 'Activity Deleted'}”
                  </h4>
                  {log.log_detail && (
                    <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                      {log.log_detail}
                    </p>
                  )}
                  <p className="mt-1 text-[14px] text-gray-400 dark:text-gray-500 italic">
                    By {log.user.user_name} - {formattedDate}
                  </p>
                </div>
              </div>
            );
          })
        ) : (
          <div className="py-10 text-center text-gray-500">
            No activity logs found.
          </div>
        )}
      </div>
    </div>
  );
}
