import { useState, useEffect, useCallback } from "react";
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  CardFooter,
} from "@/shared/common/ui/card";
import { FileText, RefreshCw, ChevronLeft, ChevronRight } from "lucide-react";
import { Activity } from "./ContentManagement";
import { useTranslation } from "react-i18next";
import i18n from "i18next";
import { Button } from "@/shared/common/ui/button";
import { listAuditLogExtensions, AuditLogExtensionItem } from "@/shared/services/audit/audit.api";

interface Props {
  activities?: Activity[];
  pageSize?: number;
}

const RecentActivitiesCard = ({ activities = [], pageSize = 10 }: Props) => {
  const { t } = useTranslation();
  const [auditLogs, setAuditLogs] = useState<AuditLogExtensionItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalCount, setTotalCount] = useState(0);

  const [allLogs, setAllLogs] = useState<AuditLogExtensionItem[]>([]);

  const fetchAuditLogs = useCallback(async () => {
    setLoading(true);
    try {
      // Fetch all 1000 records at once
      const data = await listAuditLogExtensions(
        "/audit-log-extensions/audit/unitAdmin",
        {
          skip: 0,
          take: 1000,
          orderBy: "createdAt:DESC",
        }
      );

      const logs = data.items || [];
      setAllLogs(logs);
      setTotalCount(logs.length);
      setCurrentPage(1); // Reset to first page
    } catch (error: any) {
      console.error("Error fetching audit logs:", error);
      // Silently fail for now - don't show error toast on load
      // as this is a supplementary feature
      setAllLogs([]);
      setTotalCount(0);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchAuditLogs();
    // Refresh every 30 seconds
    const interval = setInterval(fetchAuditLogs, 30000);
    return () => clearInterval(interval);
  }, [fetchAuditLogs]);

  // Paginate the allLogs whenever currentPage changes
  useEffect(() => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    setAuditLogs(allLogs.slice(startIndex, endIndex));
  }, [currentPage, pageSize, allLogs]);

  const formatDate = (date: Date) =>
    new Intl.DateTimeFormat("en-US", {
      hour: "numeric",
      minute: "numeric",
      hour12: true,
      month: "short",
      day: "numeric",
    }).format(date);

  const totalPages = Math.ceil(totalCount / pageSize);
  const hasNextPage = currentPage < totalPages;
  const hasPrevPage = currentPage > 1;

  return (
    <Card className="bg-gradient-to-br from-gray-50 to-slate-50 dark:from-gray-800 dark:to-gray-900 dark:border-gray-700">
      <CardHeader>
        <div className="flex items-center justify-between">
          <div className="flex-1">
            <CardTitle className="flex items-center dark:text-white">
              <FileText className="h-5 w-5 mr-2" />
              {t("dashboard.recentActivities", "Recent Activities")}
            </CardTitle>
            <CardDescription className="dark:text-gray-400">
              {t("organization.recentContentActivities", "Recent content management activities")}
            </CardDescription>
          </div>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => fetchAuditLogs()}
            disabled={loading}
            className="ml-2"
          >
            <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        {/* Display audit logs if available */}
        {auditLogs.length > 0 ? (
          <div className="space-y-3">
            {auditLogs.map((log, idx) => {
              const userName = i18n.language === "am" ? log.user.name.am : log.user.name.en;
              const entityLabel = log.entityName.replace(/_/g, " ");
              const timestamp = new Date(log.createdAt).toLocaleString(
                i18n.language,
                {
                  year: "numeric",
                  month: "short",
                  day: "numeric",
                  hour: "2-digit",
                  minute: "2-digit",
                }
              );

              return (
                <div
                  key={log.id || idx}
                  className="p-3 rounded-lg bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 hover:shadow-sm transition-shadow"
                >
                  <p className="text-sm text-gray-900 dark:text-gray-100">
                    <span className="font-semibold">{userName}</span>
                    {" "}
                    <span className="text-gray-600 dark:text-gray-300">
                      {log.queryMethod.toLowerCase() === "insert"
                        ? "created"
                        : log.queryMethod.toLowerCase() === "update"
                        ? "updated"
                        : log.queryMethod.toLowerCase() === "delete"
                        ? "deleted"
                        : log.queryMethod.toLowerCase()}
                    </span>
                    {" "}
                    <span className="text-gray-900 dark:text-gray-100 font-medium">
                      {entityLabel}
                    </span>
                    {" "}
                    <span className="text-gray-500 dark:text-gray-400">at {timestamp}</span>
                  </p>
                </div>
              );
            })}
          </div>
        ) : activities.length > 0 ? (
          <div className="space-y-4">
            {activities.map(({ id, type, description, timestamp }) => (
              <div key={id} className="flex justify-between items-center">
                <span className="text-sm font-medium capitalize dark:text-white">{type}</span>
                <span className="text-sm dark:text-gray-300">{description}</span>
                <span className="text-xs text-muted-foreground dark:text-gray-400">
                  {formatDate(timestamp)}
                </span>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-sm text-muted-foreground dark:text-gray-400 text-center py-8">
            {loading ? (
              <div className="flex items-center justify-center gap-2">
                <RefreshCw className="h-4 w-4 animate-spin" />
                <span>{t("common.loading", "Loading...")}</span>
              </div>
            ) : (
              t("auditLog.noRecords", "No recent activities.")
            )}
          </p>
        )}
      </CardContent>
      
      {/* Pagination Footer */}
      {auditLogs.length > 0 && (
        <CardFooter className="flex items-center justify-between border-t border-gray-200 dark:border-gray-600 pt-4">
          <div className="text-xs text-gray-600 dark:text-gray-400">
            {t("common.showing", "Showing")} {(currentPage - 1) * pageSize + 1}-
            {Math.min(currentPage * pageSize, totalCount)} {t("common.of", "of")} {totalCount}
          </div>
          
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setCurrentPage(currentPage - 1)}
              disabled={!hasPrevPage || loading}
              className="h-8 w-8 p-0"
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            
            <div className="flex items-center gap-1">
              <span className="text-xs font-medium text-gray-700 dark:text-gray-300 px-2">
                {currentPage} / {totalPages || 1}
              </span>
            </div>
            
            <Button
              variant="outline"
              size="sm"
              onClick={() => setCurrentPage(currentPage + 1)}
              disabled={!hasNextPage || loading}
              className="h-8 w-8 p-0"
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </CardFooter>
      )}
    </Card>
  );
};

export default RecentActivitiesCard;
