"use client";

import * as React from "react";
import {
  ShieldAlert,
  Search,
  Filter,
  RefreshCw,
  AlertTriangle,
  User,
  Clock,
  Terminal,
  ChevronDown,
  ChevronRight,
  MapPin,
  Globe,
  Wifi,
} from "lucide-react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { formatLocationDisplay } from "@/lib/admin/location-formatter";

interface AuditLogEntry {
  id: string;
  actorId: string;
  actorName: string;
  actorEmail: string;
  actorLevel: string;
  targetUserId: string | null;
  targetUserEmail: string | null;
  targetUserName: string | null;
  action: string;
  details: Record<string, unknown>;
  ipAddress: string | null;
  location?: {
    status: "available" | "denied" | "unavailable";
    latitude?: number;
    longitude?: number;
    address?: string;
    locality?: string;
    city?: string;
    region?: string;
    country?: string;
    postalCode?: string;
    source?: string;
    capturedAt?: string;
  } | null;
  networkSecurity?: {
    ip: string;
    isVpn: boolean;
    isProxy: boolean;
    isTor: boolean;
    isRelay: boolean;
    isBlocked: boolean;
    blockReason?: string | null;
    risk: "LOW" | "MEDIUM" | "HIGH";
    asn?: string;
    country?: string;
    city?: string;
    provider?: string;
    checkedAt?: string;
  } | null;
  timestamp: string;
}

export function SecurityAuditPanel() {
  const [logs, setLogs] = React.useState<AuditLogEntry[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);

  // Filters
  const [search, setSearch] = React.useState("");
  const [actionFilter, setActionFilter] = React.useState("ALL");
  const [expandedId, setExpandedId] = React.useState<string | null>(null);

  const fetchLogs = React.useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const params = new URLSearchParams();
      if (search.trim()) params.set("search", search.trim());
      if (actionFilter !== "ALL") params.set("action", actionFilter);

      const res = await fetch(`/api/admin/security/audit?${params.toString()}`);

      if (res.status === 403) {
        setError("Access Denied: Main Administrator authority required to view security audit logs.");
        return;
      }

      if (!res.ok) throw new Error("Failed to load security audit records");
      const data = await res.json();
      setLogs(data.logs || []);
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setLoading(false);
    }
  }, [search, actionFilter]);

  React.useEffect(() => {
    const timer = setTimeout(() => {
      fetchLogs();
    }, 250);
    return () => clearTimeout(timer);
  }, [fetchLogs]);

  const toggleExpand = (id: string) => {
    setExpandedId(expandedId === id ? null : id);
  };

  const getBadgeColor = (action: string) => {
    if (action.includes("FAILURE") || action.includes("SUSPENDED") || action.includes("REJECTED")) {
      return "bg-red-100 text-red-800 dark:bg-red-950 dark:text-red-300";
    }
    if (action.includes("SUCCESS") || action.includes("CREATED") || action.includes("REACTIVATED")) {
      return "bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-300";
    }
    if (action.includes("RESET") || action.includes("FORCE") || action.includes("ROLE")) {
      return "bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-300";
    }
    return "bg-neutral-100 text-neutral-800 dark:bg-neutral-800 dark:text-neutral-200";
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <div className="flex items-center gap-2">
            <h1 className="font-bold text-xl tracking-tight text-neutral-900 dark:text-white">
              Security & Access Audit
            </h1>
            <span className="rounded-full bg-neutral-900 px-2 py-0.5 text-[9px] font-bold text-white uppercase tracking-wider dark:bg-white dark:text-neutral-900">
              Main Admin Only
            </span>
          </div>
          <p className="mt-0.5 text-xs text-neutral-500">
            Immutable, append-only security logs. Tracks logins, credential resets, role modifications, session revocations, and system policies.
          </p>
        </div>

        <button
          type="button"
          onClick={fetchLogs}
          disabled={loading}
          className="flex h-8 items-center gap-1.5 rounded-lg border border-neutral-200 px-3 text-xs font-medium text-neutral-700 hover:bg-neutral-100 dark:border-neutral-800 dark:text-neutral-300 dark:hover:bg-neutral-800"
        >
          <RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
          <span>Refresh Audit</span>
        </button>
      </div>

      {error && (
        <div className="rounded-xl border border-red-200 bg-red-50 p-4 text-xs text-red-700 dark:border-red-900/50 dark:bg-red-950/50 dark:text-red-300">
          <div className="flex items-center gap-2 font-semibold">
            <AlertTriangle className="h-4 w-4" />
            <span>Authorization Error</span>
          </div>
          <p className="mt-1">{error}</p>
        </div>
      )}

      {/* Filter Bar */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
        <div className="relative flex-1">
          <Search className="pointer-events-none absolute inset-y-0 left-0 my-auto ml-3 h-3.5 w-3.5 text-neutral-400" />
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search by actor, target user, email, or action..."
            className="h-9 w-full rounded-lg border border-neutral-200 bg-white pr-3 pl-8 text-xs text-neutral-900 placeholder:text-neutral-400 focus:border-neutral-900 focus:ring-1 focus:ring-neutral-900 focus:outline-none dark:border-neutral-800 dark:bg-neutral-900 dark:text-white"
          />
        </div>

        <div className="flex items-center gap-2">
          <Filter className="h-3.5 w-3.5 text-neutral-400" />
          <Select value={actionFilter} onValueChange={setActionFilter}>
            <SelectTrigger className="h-9 w-52 text-xs">
              <SelectValue placeholder="All Security Actions" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="ALL">All Security Actions</SelectItem>
              <SelectItem value="LOGIN_SUCCESS">Login Success</SelectItem>
              <SelectItem value="LOGIN_FAILURE">Login Failure</SelectItem>
              <SelectItem value="ADMIN_CREATED">Admin Created</SelectItem>
              <SelectItem value="ROLE_CHANGED">Role Changed</SelectItem>
              <SelectItem value="ADMIN_SUSPENDED">Admin Suspended</SelectItem>
              <SelectItem value="ADMIN_REACTIVATED">Admin Reactivated</SelectItem>
              <SelectItem value="FORCE_LOGOUT_ALL">Force Logout</SelectItem>
              <SelectItem value="PASSWORD_CHANGE">Password Changed</SelectItem>
              <SelectItem value="PASSWORD_RESET_COMPLETED">Password Reset Completed</SelectItem>
              <SelectItem value="PASSWORD_RESET_REQUESTED">Password Reset Requested</SelectItem>
              <SelectItem value="SETTINGS_CHANGED">Settings Changed</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Audit Log Table */}
      <div className="overflow-hidden rounded-xl border border-neutral-200 bg-white shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs">
            <thead>
              <tr className="border-b border-neutral-200 bg-neutral-50/75 text-[11px] font-semibold text-neutral-500 uppercase dark:border-neutral-800 dark:bg-neutral-950/50">
                <th className="w-8 px-4 py-3"></th>
                <th className="px-4 py-3">Timestamp</th>
                <th className="px-4 py-3">Security Action</th>
                <th className="px-4 py-3">Actor</th>
                <th className="px-4 py-3">Target Subject</th>
                <th className="px-4 py-3">IP Address</th>
                <th className="px-4 py-3">Location</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-neutral-200 dark:divide-neutral-800">
              {loading ? (
                <tr>
                  <td colSpan={7} className="px-5 py-8 text-center text-neutral-400">
                    Loading security audit logs...
                  </td>
                </tr>
              ) : logs.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-5 py-8 text-center text-neutral-400">
                    No matching audit records found.
                  </td>
                </tr>
              ) : (
                logs.map((log) => {
                  const isExpanded = expandedId === log.id;
                  return (
                    <React.Fragment key={log.id}>
                      <tr
                        onClick={() => toggleExpand(log.id)}
                        className="cursor-pointer transition hover:bg-neutral-50/50 dark:hover:bg-neutral-800/30"
                      >
                        <td className="px-4 py-3 text-neutral-400">
                          {isExpanded ? (
                            <ChevronDown className="h-3.5 w-3.5" />
                          ) : (
                            <ChevronRight className="h-3.5 w-3.5" />
                          )}
                        </td>

                        <td suppressHydrationWarning className="px-4 py-3 font-mono text-[11px] text-neutral-500">
                          {new Date(log.timestamp).toLocaleString("en-US", {
                            dateStyle: "short",
                            timeStyle: "medium",
                          })}
                        </td>

                        <td className="px-4 py-3">
                          <span
                            className={`inline-block rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider ${getBadgeColor(
                              log.action
                            )}`}
                          >
                            {(log.action || "").replace(/_/g, " ")}
                          </span>
                        </td>

                        <td className="px-4 py-3">
                          <div className="font-semibold text-neutral-900 dark:text-white">
                            {log.actorName}
                          </div>
                          <div className="text-[10px] text-neutral-400">
                            {log.actorEmail} ({log.actorLevel})
                          </div>
                        </td>

                        <td className="px-4 py-3">
                          {log.targetUserName ? (
                            <div>
                              <span className="font-medium text-neutral-900 dark:text-white">
                                {log.targetUserName}
                              </span>
                              <div className="text-[10px] text-neutral-400">
                                {log.targetUserEmail}
                              </div>
                            </div>
                          ) : (
                            <span className="text-neutral-400">—</span>
                          )}
                        </td>

                        <td className="px-4 py-3 font-mono text-[11px] text-neutral-400">
                          {log.ipAddress || "127.0.0.1"}
                        </td>

                        <td className="px-4 py-3 max-w-[220px] truncate">
                          {log.location?.status === "available" ? (
                            <span
                              className="inline-flex items-center gap-1 rounded-md bg-cyan-50 px-2 py-0.5 text-[10px] font-medium text-cyan-800 border border-cyan-200 dark:border-cyan-900/40 dark:bg-cyan-950/40 dark:text-cyan-300 max-w-full truncate"
                              title={
                                log.location.latitude != null && log.location.longitude != null
                                  ? `Coordinates: ${log.location.latitude}, ${log.location.longitude}\nSource: ${log.location.source || "Browser Geolocation"}`
                                  : "Location available"
                              }
                            >
                              <MapPin className="h-3 w-3 text-cyan-600 shrink-0" />
                              <span className="truncate">{formatLocationDisplay(log.location)}</span>
                            </span>
                          ) : log.location?.status === "denied" ? (
                            <span className="inline-flex items-center gap-1 text-[10px] text-neutral-400">
                              Denied
                            </span>
                          ) : (
                            <span className="text-[10px] text-neutral-400">—</span>
                          )}
                        </td>
                      </tr>

                      {isExpanded && (
                        <tr className="bg-neutral-50/80 dark:bg-neutral-950/80">
                          <td colSpan={7} className="px-6 py-4">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                              {/* Location Security Details */}
                              <div className="rounded-lg border border-neutral-200 bg-white p-3.5 dark:border-neutral-800 dark:bg-neutral-900">
                                <div className="flex items-center gap-1.5 text-[10px] font-bold text-neutral-500 uppercase tracking-wider">
                                  <MapPin className="h-3 w-3 text-cyan-600" />
                                  <span>Geographic Audit Location</span>
                                </div>
                                <div className="mt-2.5 space-y-1.5 text-[11px] text-neutral-600 dark:text-neutral-400">
                                  <div>
                                    <span className="text-neutral-400">Location: </span>
                                    <strong className="text-neutral-800 dark:text-neutral-200 font-semibold">
                                      {formatLocationDisplay(log.location)}
                                    </strong>
                                  </div>
                                  <div>
                                    <span className="text-neutral-400">Location Status: </span>
                                    <span className="capitalize">{log.location?.status || "Unavailable"}</span>
                                  </div>
                                  {log.location?.latitude != null && log.location?.longitude != null && (
                                    <div>
                                      <span className="text-neutral-400">Coordinates: </span>
                                      <span className="font-mono text-neutral-700 dark:text-neutral-300">
                                        {log.location.latitude}, {log.location.longitude}
                                      </span>
                                    </div>
                                  )}
                                  <div>
                                    <span className="text-neutral-400">Source: </span>
                                    <span>{log.location?.source || (log.location?.status === "available" ? "Browser Geolocation" : "None")}</span>
                                  </div>
                                  {log.location?.capturedAt && (
                                    <div>
                                      <span className="text-neutral-400">Captured: </span>
                                      <span>
                                        {new Date(log.location.capturedAt).toLocaleString("en-US", {
                                          dateStyle: "medium",
                                          timeStyle: "medium",
                                        })}
                                      </span>
                                    </div>
                                  )}
                                </div>
                              </div>

                              {/* Network Security Signals */}
                              <div className="rounded-lg border border-neutral-200 bg-white p-3.5 dark:border-neutral-800 dark:bg-neutral-900">
                                <div className="flex items-center gap-1.5 text-[10px] font-bold text-neutral-500 uppercase tracking-wider">
                                  <Wifi className="h-3 w-3 text-emerald-600" />
                                  <span>Server-Side Network Security</span>
                                </div>
                                <div className="mt-2.5 space-y-1.5 text-[11px] text-neutral-600 dark:text-neutral-400">
                                  <div>
                                    <span className="text-neutral-400">Client IP: </span>
                                    <span className="font-mono font-semibold text-neutral-800 dark:text-neutral-200">
                                      {log.networkSecurity?.ip || log.ipAddress || "127.0.0.1"}
                                    </span>
                                  </div>
                                  {log.networkSecurity ? (
                                    <>
                                      <div className="flex flex-wrap items-center gap-1.5 pt-0.5">
                                        <span className="text-neutral-400 text-[10px]">Signals:</span>
                                        <span className={`px-1.5 py-0.5 rounded text-[10px] font-mono font-medium ${log.networkSecurity.isVpn ? "bg-red-100 text-red-700 dark:bg-red-950 dark:text-red-300" : "bg-neutral-100 text-neutral-600 dark:bg-neutral-800 dark:text-neutral-400"}`}>
                                          VPN={log.networkSecurity.isVpn ? "true" : "false"}
                                        </span>
                                        <span className={`px-1.5 py-0.5 rounded text-[10px] font-mono font-medium ${log.networkSecurity.isProxy ? "bg-red-100 text-red-700 dark:bg-red-950 dark:text-red-300" : "bg-neutral-100 text-neutral-600 dark:bg-neutral-800 dark:text-neutral-400"}`}>
                                          Proxy={log.networkSecurity.isProxy ? "true" : "false"}
                                        </span>
                                        <span className={`px-1.5 py-0.5 rounded text-[10px] font-mono font-medium ${log.networkSecurity.isTor ? "bg-red-100 text-red-700 dark:bg-red-950 dark:text-red-300" : "bg-neutral-100 text-neutral-600 dark:bg-neutral-800 dark:text-neutral-400"}`}>
                                          Tor={log.networkSecurity.isTor ? "true" : "false"}
                                        </span>
                                        <span className={`px-1.5 py-0.5 rounded text-[10px] font-mono font-medium ${log.networkSecurity.isRelay ? "bg-red-100 text-red-700 dark:bg-red-950 dark:text-red-300" : "bg-neutral-100 text-neutral-600 dark:bg-neutral-800 dark:text-neutral-400"}`}>
                                          Relay={log.networkSecurity.isRelay ? "true" : "false"}
                                        </span>
                                      </div>
                                      <div>
                                        <span className="text-neutral-400">Risk Level: </span>
                                        <span className={`font-semibold ${log.networkSecurity.risk === "HIGH" ? "text-red-600 dark:text-red-400" : "text-emerald-600 dark:text-emerald-400"}`}>
                                          {log.networkSecurity.risk}
                                        </span>
                                        {log.networkSecurity.provider && (
                                          <span className="text-neutral-400 text-[10px]"> ({log.networkSecurity.provider})</span>
                                        )}
                                      </div>
                                      {log.networkSecurity.asn && (
                                        <div>
                                          <span className="text-neutral-400">ASN: </span>
                                          <span className="font-mono text-[10px]">{log.networkSecurity.asn}</span>
                                        </div>
                                      )}
                                      {log.networkSecurity.blockReason && (
                                        <div className="text-red-600 dark:text-red-400 font-medium text-[10px]">
                                          Reason: {log.networkSecurity.blockReason}
                                        </div>
                                      )}
                                    </>
                                  ) : (
                                    <div>
                                      <span className="text-neutral-400">Risk Assessment: </span>
                                      <span className="text-emerald-600 dark:text-emerald-400 font-medium">Direct Network Connection</span>
                                    </div>
                                  )}
                                </div>
                              </div>
                            </div>

                            {/* Raw Event Telemetry */}
                            {log.details && Object.keys(log.details).length > 0 && (
                              <div className="mt-3 rounded-lg border border-neutral-200 bg-white p-3 dark:border-neutral-800 dark:bg-neutral-900">
                                <div className="flex items-center gap-1.5 text-[10px] font-bold text-neutral-400 uppercase tracking-wider">
                                  <Terminal className="h-3 w-3" />
                                  <span>Event Telemetry Details</span>
                                </div>
                                <pre className="mt-2 overflow-x-auto font-mono text-[11px] text-neutral-700 dark:text-neutral-300">
                                  {JSON.stringify(log.details, null, 2)}
                                </pre>
                              </div>
                            )}
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

export default SecurityAuditPanel;
