"use client";

import * as React from "react";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { formatDateID } from "@/lib/utils";
import {
  Activity,
  Search,
  ChevronLeft,
  ChevronRight,
  ShieldCheck,
  ShieldAlert,
  UserCheck,
} from "lucide-react";

interface AuditLogItem {
  id: string;
  action: string;
  resource: string;
  ipAddress?: string | null;
  details?: string | null;
  createdAt: string;
  user?: {
    id: string;
    username: string;
    role: string;
    teacher?: { fullName: string } | null;
    student?: { fullName: string } | null;
  } | null;
}

export function AuditLogsClient() {
  const [logs, setLogs] = React.useState<AuditLogItem[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [search, setSearch] = React.useState("");
  const [actionFilter, setActionFilter] = React.useState("ALL");
  const [page, setPage] = React.useState(1);
  const [pagination, setPagination] = React.useState<any>({ page: 1, totalPages: 1, total: 0 });

  const fetchLogs = React.useCallback(async () => {
    try {
      setLoading(true);
      const res = await fetch(
        `/api/audit-logs?page=${page}&action=${actionFilter}&search=${encodeURIComponent(search)}`
      );
      const data = await res.json();
      if (data.success) {
        setLogs(data.data || []);
        setPagination(data.pagination);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [page, actionFilter, search]);

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

  const getActionBadge = (action: string) => {
    if (action.includes("LOGIN")) {
      return <Badge variant="info" className="text-[10px] font-mono">AUTH_LOGIN</Badge>;
    }
    if (action.includes("CREATE")) {
      return <Badge variant="success" className="text-[10px] font-mono">{action}</Badge>;
    }
    if (action.includes("UPDATE") || action.includes("GRADE")) {
      return <Badge variant="warning" className="text-[10px] font-mono">{action}</Badge>;
    }
    if (action.includes("DELETE")) {
      return <Badge variant="destructive" className="text-[10px] font-mono">{action}</Badge>;
    }
    return <Badge variant="secondary" className="text-[10px] font-mono">{action}</Badge>;
  };

  return (
    <div className="space-y-4">
      {/* Search and Filters */}
      <Card>
        <CardContent className="p-4 flex flex-col sm:flex-row items-center justify-between gap-3">
          <div className="flex items-center gap-2 w-full sm:w-auto flex-1">
            <div className="relative w-full sm:w-80">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
              <Input
                placeholder="Cari aksi, pengguna, atau IP..."
                value={search}
                onChange={(e) => {
                  setSearch(e.target.value);
                  setPage(1);
                }}
                className="pl-9 text-xs"
              />
            </div>
            <select
              value={actionFilter}
              onChange={(e) => {
                setActionFilter(e.target.value);
                setPage(1);
              }}
              className="text-xs bg-white border border-slate-300 rounded-lg px-3 py-2 text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="ALL">Semua Tipe Aksi</option>
              <option value="LOGIN">LOGIN</option>
              <option value="CREATE_ASSIGNMENT">CREATE_ASSIGNMENT</option>
              <option value="SUBMIT_GRADE">SUBMIT_GRADE</option>
              <option value="CREATE_ANNOUNCEMENT">CREATE_ANNOUNCEMENT</option>
              <option value="UPDATE_PROFILE">UPDATE_PROFILE</option>
            </select>
          </div>

          <div className="text-xs text-slate-500">
            Total tercatat: <strong>{pagination.total || 0}</strong> aktivitas
          </div>
        </CardContent>
      </Card>

      {/* Audit Logs Table */}
      <Card>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-xs text-left">
              <thead className="bg-slate-50 text-slate-700 font-semibold border-b border-slate-200">
                <tr>
                  <th className="py-3 px-4">Waktu</th>
                  <th className="py-3 px-4">Pengguna</th>
                  <th className="py-3 px-4">Aksi</th>
                  <th className="py-3 px-4">Sumber Daya (Resource)</th>
                  <th className="py-3 px-4">Alamat IP</th>
                  <th className="py-3 px-4">Detail Data</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 font-sans">
                {loading ? (
                  <tr>
                    <td colSpan={6} className="py-8 text-center text-slate-400 text-xs">
                      Memuat catatan aktivitas...
                    </td>
                  </tr>
                ) : logs.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="py-8 text-center text-slate-500 text-xs">
                      Belum ada log aktivitas yang cocok dengan kriteria pencarian.
                    </td>
                  </tr>
                ) : (
                  logs.map((log) => {
                    const userName =
                      log.user?.teacher?.fullName ||
                      log.user?.student?.fullName ||
                      log.user?.username ||
                      "Sistem / Anonim";

                    return (
                      <tr key={log.id} className="hover:bg-slate-50 transition-colors">
                        <td className="py-3 px-4 whitespace-nowrap text-slate-500 font-mono text-[11px]">
                          {new Date(log.createdAt).toLocaleString("id-ID", {
                            day: "2-digit",
                            month: "short",
                            year: "numeric",
                            hour: "2-digit",
                            minute: "2-digit",
                            second: "2-digit",
                          })}
                        </td>
                        <td className="py-3 px-4">
                          <div className="font-semibold text-slate-800">{userName}</div>
                          {log.user && (
                            <span className="text-[10px] text-slate-400 font-mono">
                              @{log.user.username} ({log.user.role})
                            </span>
                          )}
                        </td>
                        <td className="py-3 px-4">{getActionBadge(log.action)}</td>
                        <td className="py-3 px-4 font-mono text-slate-600 text-[11px]">
                          {log.resource}
                        </td>
                        <td className="py-3 px-4 font-mono text-slate-500 text-[11px]">
                          {log.ipAddress || "127.0.0.1"}
                        </td>
                        <td className="py-3 px-4 max-w-xs">
                          {log.details ? (
                            <code className="text-[10px] text-slate-600 bg-slate-100 p-1 rounded font-mono truncate block max-w-xs" title={log.details}>
                              {log.details}
                            </code>
                          ) : (
                            <span className="text-slate-400">-</span>
                          )}
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {pagination.totalPages > 1 && (
            <div className="p-4 border-t border-slate-100 flex items-center justify-between text-xs">
              <span className="text-slate-500">
                Halaman {pagination.page} dari {pagination.totalPages}
              </span>
              <div className="flex items-center gap-1">
                <Button
                  variant="outline"
                  size="sm"
                  disabled={page <= 1}
                  onClick={() => setPage((p) => Math.max(1, p - 1))}
                  className="h-8 px-2.5"
                >
                  <ChevronLeft className="h-3.5 w-3.5 mr-1" />
                  Sebelumnya
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  disabled={page >= pagination.totalPages}
                  onClick={() => setPage((p) => p + 1)}
                  className="h-8 px-2.5"
                >
                  Selanjutnya
                  <ChevronRight className="h-3.5 w-3.5 ml-1" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
