// @File: src/pages/admin/cms/CmsVisitorLive.tsx
// @Desc: Real-time online visitors list. Auto-refreshes every 10 seconds.
import { useCallback, useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import {
  Activity,
  Globe2,
  Loader2,
  Monitor,
  RefreshCw,
  Search,
  Smartphone,
  Tablet,
} from "lucide-react";
import CmsLayout from "./CmsLayout";
import { Badge, PageHeader, SectionCard, TextInput } from "./ui";
import { vmListSessions, type VmSessionItem } from "@/lib/adminApi";

const AUTO_REFRESH_MS = 10_000;

function DeviceIcon({ device }: { device: string | null }) {
  if (device === "mobile") return <Smartphone className="w-4 h-4 text-slate-500" />;
  if (device === "tablet") return <Tablet className="w-4 h-4 text-slate-500" />;
  return <Monitor className="w-4 h-4 text-slate-500" />;
}

function formatDuration(s: number): string {
  if (s < 60) return `${s}s`;
  const m = Math.floor(s / 60);
  const rem = s % 60;
  if (m < 60) return `${m}m ${rem}s`;
  const h = Math.floor(m / 60);
  return `${h}h ${m % 60}m`;
}

function formatTime(iso: string): string {
  try {
    return new Date(iso).toLocaleTimeString();
  } catch {
    return iso;
  }
}

export default function CmsVisitorLive() {
  const [items, setItems] = useState<VmSessionItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState("");
  const [autoRefresh, setAutoRefresh] = useState(true);
  const intervalRef = useRef<number | null>(null);

  const load = useCallback(async () => {
    setError(null);
    try {
      const res = await vmListSessions({
        onlyOnline: true,
        search: search || undefined,
        page: 1,
        pageSize: 100,
      });
      setItems(res.items);
      setTotal(res.total);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load live visitors");
    } finally {
      setLoading(false);
    }
  }, [search]);

  useEffect(() => {
    void load();
  }, [load]);

  useEffect(() => {
    if (!autoRefresh) {
      if (intervalRef.current) {
        window.clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
      return;
    }
    intervalRef.current = window.setInterval(() => {
      void load();
    }, AUTO_REFRESH_MS);
    return () => {
      if (intervalRef.current) {
        window.clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    };
  }, [autoRefresh, load]);

  return (
    <CmsLayout>
      <PageHeader
        title="Live Visitors"
        description="Everyone currently browsing the site. Updates every 10 seconds."
        icon={<Activity className="w-6 h-6" />}
      />

      <SectionCard
        title={`${total} online`}
        description="Green dot = active in the last 2 minutes"
        actions={
          <div className="flex items-center gap-2">
            <label className="inline-flex items-center gap-2 text-xs font-semibold text-slate-600 cursor-pointer">
              <input
                type="checkbox"
                checked={autoRefresh}
                onChange={(e) => setAutoRefresh(e.target.checked)}
                className="accent-[#0b6e3e]"
              />
              Auto-refresh
            </label>
            <button
              onClick={() => void load()}
              className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-slate-300 bg-white text-sm font-semibold text-slate-700 hover:bg-slate-50 transition"
            >
              {loading ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <RefreshCw className="w-4 h-4" />
              )}
              Refresh
            </button>
          </div>
        }
      >
        <div className="relative">
          <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <TextInput
            placeholder="Search IP, country, page, campaign…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-9"
          />
        </div>

        {error && (
          <div className="p-3 rounded-lg bg-red-50 border border-red-200 text-sm text-red-700">
            {error}
          </div>
        )}

        <div className="overflow-x-auto -mx-5 md:-mx-6">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 text-left text-[11px] uppercase tracking-wider text-slate-500">
              <tr>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3">Location</th>
                <th className="px-4 py-3">Device</th>
                <th className="px-4 py-3">Current Page</th>
                <th className="px-4 py-3">Campaign</th>
                <th className="px-4 py-3">Duration</th>
                <th className="px-4 py-3">Last Activity</th>
                <th className="px-4 py-3"></th>
              </tr>
            </thead>
            <tbody>
              {items.length === 0 && !loading && (
                <tr>
                  <td colSpan={8} className="px-4 py-10 text-center text-slate-500">
                    No visitors are online right now.
                  </td>
                </tr>
              )}
              {items.map((row) => (
                <tr
                  key={row.session_id}
                  className="border-t border-slate-100 hover:bg-slate-50/60"
                >
                  <td className="px-4 py-3">
                    <span className="inline-flex items-center gap-2 text-xs font-semibold text-emerald-700">
                      <span className="relative flex w-2.5 h-2.5">
                        <span className="absolute inset-0 rounded-full bg-emerald-400 animate-ping opacity-75" />
                        <span className="relative w-2.5 h-2.5 rounded-full bg-emerald-500" />
                      </span>
                      Online
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <Globe2 className="w-4 h-4 text-slate-400" />
                      <div className="min-w-0">
                        <div className="text-slate-900 font-medium truncate max-w-[180px]">
                          {row.country || "Unknown"}
                          {row.city ? ` · ${row.city}` : ""}
                        </div>
                        <div className="text-[11px] text-slate-400 font-mono">
                          {row.ip_address || "—"}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <DeviceIcon device={row.device} />
                      <div className="min-w-0">
                        <div className="text-slate-700">{row.browser || "—"}</div>
                        <div className="text-[11px] text-slate-400">{row.os || "—"}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3 max-w-[220px]">
                    <div
                      className="text-slate-700 truncate"
                      title={row.current_page || undefined}
                    >
                      {row.current_page || "—"}
                    </div>
                    <div
                      className="text-[11px] text-slate-400 truncate"
                      title={row.referrer || undefined}
                    >
                      from {row.referrer || "direct"}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    {row.utm_campaign ? (
                      <Badge tone="blue">{row.utm_campaign}</Badge>
                    ) : (
                      <span className="text-slate-400">—</span>
                    )}
                    {row.utm_source && (
                      <div className="text-[11px] text-slate-400 mt-0.5">
                        {row.utm_source}
                      </div>
                    )}
                  </td>
                  <td className="px-4 py-3 text-slate-700">
                    {formatDuration(row.duration_seconds)}
                  </td>
                  <td className="px-4 py-3 text-slate-500 text-[12px]">
                    {formatTime(row.last_activity_at)}
                  </td>
                  <td className="px-4 py-3">
                    <Link
                      to={`/admin/cms/visitor-monitor/journey?session=${encodeURIComponent(row.session_id)}`}
                      className="text-[#0b6e3e] hover:underline text-xs font-semibold"
                    >
                      Journey →
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </SectionCard>
    </CmsLayout>
  );
}