"use client";

import { useEffect, useState } from "react";
import { Button, Badge } from "@/components/ui";

interface ActivityStats {
  activeSessions: number;
  loginsToday: number;
  failedToday: number;
  signupsWeek: number;
}

interface Event {
  id: string;
  action: string;
  email: string;
  userName: string | null;
  familyName: string | null;
  ipAddress: string | null;
  userAgent: string | null;
  createdAt: string;
}

interface ActivityData {
  stats: ActivityStats;
  loginsByDay: { date: string; count: number }[];
  failedByDay: { date: string; count: number }[];
  events: Event[];
}

const ACTION_CONFIG: Record<string, { label: string; color: string; badge: "rose" | "warning" | "default" }> = {
  login: { label: "Login", color: "text-emerald-400", badge: "default" },
  login_failed: { label: "Failed Login", color: "text-rose-400", badge: "rose" },
  signup: { label: "Signup", color: "text-blue-400", badge: "default" },
  logout: { label: "Logout", color: "text-gray-400", badge: "default" },
};

function timeAgo(iso: string) {
  const diff = Date.now() - new Date(iso).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return "just now";
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  return `${days}d ago`;
}

function parseDevice(ua: string | null) {
  if (!ua) return "Unknown";
  if (ua.includes("iPhone") || ua.includes("Android")) return "Mobile";
  if (ua.includes("iPad")) return "Tablet";
  return "Desktop";
}

export default function AdminActivity() {
  const [data, setData] = useState<ActivityData | null>(null);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState("all");
  const [autoRefresh, setAutoRefresh] = useState(false);

  useEffect(() => {
    fetchActivity();
  }, [filter]);

  useEffect(() => {
    if (!autoRefresh) return;
    const id = setInterval(fetchActivity, 15000);
    return () => clearInterval(id);
  }, [autoRefresh, filter]);

  const fetchActivity = async () => {
    try {
      const res = await fetch(`/api/admin/activity?action=${filter}&limit=100`, { credentials: "include" });
      const json = await res.json();
      setData(json);
    } catch (err) {
      console.error("Failed to fetch activity:", err);
    }
    setLoading(false);
  };

  if (loading || !data) {
    return (
      <div className="p-6">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-700 rounded w-48" />
          <div className="grid grid-cols-4 gap-4">
            {[1, 2, 3, 4].map(i => <div key={i} className="h-24 bg-gray-800 rounded-xl" />)}
          </div>
        </div>
      </div>
    );
  }

  const { stats, loginsByDay, failedByDay, events } = data;
  const maxLogins = Math.max(...loginsByDay.map(d => d.count), 1);
  const maxFailed = Math.max(...failedByDay.map(d => d.count), 1);

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold">Activity Monitor</h1>
          <p className="text-gray-400">Real-time login events and session tracking</p>
        </div>
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-2">
            <div className={`w-2 h-2 rounded-full ${autoRefresh ? "bg-emerald-400 animate-pulse" : "bg-gray-600"}`} />
            <button
              onClick={() => setAutoRefresh(!autoRefresh)}
              className="text-sm text-gray-400 hover:text-white"
            >
              {autoRefresh ? "Live" : "Paused"}
            </button>
          </div>
          <Button size="sm" variant="secondary" onClick={fetchActivity}>Refresh</Button>
        </div>
      </div>

      {/* Stat Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-gray-800 p-5 rounded-xl border border-gray-700">
          <div className="text-3xl font-bold text-emerald-400">{stats.activeSessions}</div>
          <div className="text-gray-400 text-sm mt-1">Active Sessions</div>
          <div className="text-xs text-gray-600 mt-1">Currently online</div>
        </div>
        <div className="bg-gray-800 p-5 rounded-xl border border-gray-700">
          <div className="text-3xl font-bold text-blue-400">{stats.loginsToday}</div>
          <div className="text-gray-400 text-sm mt-1">Logins Today</div>
          <div className="text-xs text-gray-600 mt-1">Last 24 hours</div>
        </div>
        <div className="bg-gray-800 p-5 rounded-xl border border-gray-700">
          <div className={`text-3xl font-bold ${stats.failedToday > 0 ? "text-rose-400" : "text-gray-400"}`}>
            {stats.failedToday}
          </div>
          <div className="text-gray-400 text-sm mt-1">Failed Attempts</div>
          <div className="text-xs text-gray-600 mt-1">Last 24 hours</div>
        </div>
        <div className="bg-gray-800 p-5 rounded-xl border border-gray-700">
          <div className="text-3xl font-bold text-amber-400">{stats.signupsWeek}</div>
          <div className="text-gray-400 text-sm mt-1">New Signups</div>
          <div className="text-xs text-gray-600 mt-1">Last 7 days</div>
        </div>
      </div>

      {/* Charts */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="bg-gray-800 p-6 rounded-xl">
          <h3 className="text-sm font-semibold text-gray-400 mb-4">LOGIN ACTIVITY — LAST 30 DAYS</h3>
          <div className="h-32 flex items-end gap-1">
            {loginsByDay.slice(-30).map((d, i) => (
              <div key={i} className="flex-1 flex flex-col items-center gap-1">
                <div
                  className="w-full bg-emerald-500 rounded-t opacity-80"
                  style={{ height: `${(d.count / maxLogins) * 100}%`, minHeight: d.count > 0 ? "3px" : "0" }}
                />
                <div className="text-[7px] text-gray-600">{d.date?.slice(5) || ""}</div>
              </div>
            ))}
            {loginsByDay.length === 0 && (
              <div className="w-full h-full flex items-center justify-center text-gray-600 text-sm">
                No login data yet
              </div>
            )}
          </div>
        </div>
        <div className="bg-gray-800 p-6 rounded-xl">
          <h3 className="text-sm font-semibold text-gray-400 mb-4">FAILED LOGINS — LAST 30 DAYS</h3>
          <div className="h-32 flex items-end gap-1">
            {failedByDay.slice(-30).map((d, i) => (
              <div key={i} className="flex-1 flex flex-col items-center gap-1">
                <div
                  className="w-full bg-rose-500 rounded-t opacity-80"
                  style={{ height: `${(d.count / maxFailed) * 100}%`, minHeight: d.count > 0 ? "3px" : "0" }}
                />
                <div className="text-[7px] text-gray-600">{d.date?.slice(5) || ""}</div>
              </div>
            ))}
            {failedByDay.length === 0 && (
              <div className="w-full h-full flex items-center justify-center text-gray-600 text-sm">
                No failed logins
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Events Table */}
      <div className="bg-gray-800 rounded-xl overflow-hidden">
        {/* Filter tabs */}
        <div className="flex gap-1 p-3 border-b border-gray-700 bg-gray-900">
          {[
            { key: "all", label: "All Events" },
            { key: "login", label: "Logins" },
            { key: "login_failed", label: "Failures" },
            { key: "signup", label: "Signups" },
          ].map(({ key, label }) => (
            <button
              key={key}
              onClick={() => setFilter(key)}
              className={`px-3 py-1.5 rounded text-sm font-medium transition-colors ${
                filter === key
                  ? "bg-rose-500 text-white"
                  : "text-gray-400 hover:text-white hover:bg-gray-700"
              }`}
            >
              {label}
            </button>
          ))}
          <div className="ml-auto text-xs text-gray-600 flex items-center">
            {events.length} events
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-gray-700">
              <tr>
                <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-400">TIME</th>
                <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-400">EVENT</th>
                <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-400">USER</th>
                <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-400">FAMILY</th>
                <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-400">IP</th>
                <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-400">DEVICE</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-700">
              {events.map((event) => {
                const config = ACTION_CONFIG[event.action] || { label: event.action, color: "text-gray-400", badge: "default" as const };
                return (
                  <tr key={event.id} className={`hover:bg-gray-750 ${event.action === "login_failed" ? "bg-rose-500/5" : ""}`}>
                    <td className="px-4 py-2.5 text-gray-500 whitespace-nowrap">
                      {timeAgo(event.createdAt)}
                    </td>
                    <td className="px-4 py-2.5">
                      <span className={`font-medium ${config.color}`}>{config.label}</span>
                    </td>
                    <td className="px-4 py-2.5">
                      <div className="font-medium truncate max-w-[180px]">{event.email}</div>
                      {event.userName && event.userName !== event.email && (
                        <div className="text-xs text-gray-500">{event.userName}</div>
                      )}
                    </td>
                    <td className="px-4 py-2.5 text-gray-400">{event.familyName || "—"}</td>
                    <td className="px-4 py-2.5 text-gray-500 font-mono text-xs">{event.ipAddress || "—"}</td>
                    <td className="px-4 py-2.5 text-gray-500 text-xs">{parseDevice(event.userAgent)}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {events.length === 0 && (
            <div className="p-12 text-center text-gray-600">
              No events recorded yet
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
