"use client";

import { useEffect, useState, useCallback } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { ScrollText, RefreshCw, Search, ChevronLeft, ChevronRight } from "lucide-react";
import { formatDistanceToNow } from "date-fns";

interface AuditEntry {
  log: {
    id: string;
    userId: string;
    action: string;
    target: string;
    targetId: string | null;
    details: string | null;
    ipAddress: string | null;
    createdAt: number;
  };
  userName: string | null;
  userEmail: string | null;
}

const ACTION_COLORS: Record<string, string> = {
  "server.start": "bg-emerald-500/20 text-emerald-400 border-emerald-500/30",
  "server.stop": "bg-zinc-500/20 text-zinc-400 border-zinc-500/30",
  "server.restart": "bg-blue-500/20 text-blue-400 border-blue-500/30",
  "player.ban": "bg-red-500/20 text-red-400 border-red-500/30",
  "player.unban": "bg-emerald-500/20 text-emerald-400 border-emerald-500/30",
  "player.kick": "bg-amber-500/20 text-amber-400 border-amber-500/30",
  "file.upload": "bg-blue-500/20 text-blue-400 border-blue-500/30",
  "file.delete": "bg-red-500/20 text-red-400 border-red-500/30",
  "plugin.enable": "bg-emerald-500/20 text-emerald-400 border-emerald-500/30",
  "plugin.disable": "bg-zinc-500/20 text-zinc-400 border-zinc-500/30",
};

function getActionColor(action: string): string {
  return ACTION_COLORS[action] ?? "bg-zinc-500/20 text-zinc-400 border-zinc-500/30";
}

export default function AuditPage() {
  const [entries, setEntries] = useState<AuditEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [hasMore, setHasMore] = useState(true);
  const LIMIT = 50;

  const fetchLogs = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: String(page),
        limit: String(LIMIT),
      });
      if (search) params.set("action", search);
      const res = await fetch(`/api/audit?${params}`);
      if (res.ok) {
        const data = await res.json();
        setEntries(data.logs);
        setHasMore(data.logs.length === LIMIT);
      }
    } finally {
      setLoading(false);
    }
  }, [page, search]);

  useEffect(() => {
    fetchLogs();
  }, [fetchLogs]);

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Audit Log</h1>
          <p className="text-zinc-400 text-sm mt-1">
            Complete history of admin actions
          </p>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={fetchLogs}
          className="border-zinc-700 text-zinc-400 hover:text-white"
        >
          <RefreshCw className="w-4 h-4" />
        </Button>
      </div>

      {/* Filter */}
      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500" />
        <Input
          placeholder="Filter by action (e.g. player.ban)"
          value={search}
          onChange={(e) => { setSearch(e.target.value); setPage(1); }}
          className="pl-9 bg-zinc-900 border-zinc-700 text-white placeholder:text-zinc-500 focus:border-emerald-500/50"
        />
      </div>

      <Card className="bg-zinc-900 border-zinc-800">
        <CardContent className="p-0">
          {loading ? (
            <div className="p-4 space-y-3">
              {Array.from({ length: 10 }).map((_, i) => (
                <Skeleton key={i} className="h-12 w-full bg-zinc-800" />
              ))}
            </div>
          ) : entries.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-zinc-600">
              <ScrollText className="w-10 h-10 mb-3 opacity-50" />
              <p>No audit log entries</p>
            </div>
          ) : (
            <div className="divide-y divide-zinc-800">
              <div className="grid grid-cols-[auto_1fr_auto_auto] gap-4 px-4 py-2.5 text-xs font-medium text-zinc-500 uppercase tracking-wide">
                <span>Action</span>
                <span>Details</span>
                <span>User</span>
                <span>Time</span>
              </div>
              {entries.map(({ log, userName, userEmail }) => (
                <div
                  key={log.id}
                  className="grid grid-cols-[auto_1fr_auto_auto] gap-4 px-4 py-3 items-start hover:bg-zinc-800/50 transition-colors"
                >
                  <Badge className={`text-xs shrink-0 mt-0.5 ${getActionColor(log.action)}`}>
                    {log.action}
                  </Badge>
                  <div>
                    {log.targetId && (
                      <p className="text-sm text-zinc-300">
                        Target:{" "}
                        <span className="font-mono text-xs text-zinc-400">
                          {log.targetId}
                        </span>
                      </p>
                    )}
                    {log.details && (
                      <p className="text-xs text-zinc-500 font-mono mt-0.5 truncate max-w-xs">
                        {log.details}
                      </p>
                    )}
                    {log.ipAddress && (
                      <p className="text-xs text-zinc-600 mt-0.5">
                        IP: {log.ipAddress}
                      </p>
                    )}
                  </div>
                  <div className="text-right">
                    <p className="text-sm text-zinc-300">
                      {userName ?? "Unknown"}
                    </p>
                    <p className="text-xs text-zinc-600">{userEmail ?? ""}</p>
                  </div>
                  <p className="text-xs text-zinc-500 whitespace-nowrap">
                    {formatDistanceToNow(new Date(log.createdAt), {
                      addSuffix: true,
                    })}
                  </p>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Pagination */}
      <div className="flex items-center justify-between">
        <p className="text-sm text-zinc-500">Page {page}</p>
        <div className="flex gap-2">
          <Button
            variant="outline"
            size="sm"
            disabled={page === 1 || loading}
            onClick={() => setPage((p) => p - 1)}
            className="border-zinc-700 text-zinc-400 hover:text-white"
          >
            <ChevronLeft className="w-4 h-4" />
          </Button>
          <Button
            variant="outline"
            size="sm"
            disabled={!hasMore || loading}
            onClick={() => setPage((p) => p + 1)}
            className="border-zinc-700 text-zinc-400 hover:text-white"
          >
            <ChevronRight className="w-4 h-4" />
          </Button>
        </div>
      </div>
    </div>
  );
}
