"use client";

import { useEffect, useState, useCallback } from "react";
import { Activity, RefreshCw } from "lucide-react";

interface LiveSession {
  sessionId: string;
  entryPage: string;
  referrer: string | null;
  device: string | null;
  country: string | null;
  channelGroup: string | null;
  score: number;
  scoreBand: string;
  scoreBandLabel: string;
  topFactors: string[];
  startedAt: string;
  lastSeenAt: string;
  pageCount: number;
  ageSeconds: number;
}

interface Summary {
  total: number;
  highIntent: number;
  avgScore: number;
  windowMinutes: number;
}

interface LiveSessionsData {
  sessions: LiveSession[];
  summary: Summary | null;
}

const BAND_COLORS: Record<string, string> = {
  very_high: "text-violet-700 bg-violet-50 border-violet-200",
  high:      "text-emerald-700 bg-emerald-50 border-emerald-200",
  moderate:  "text-amber-700 bg-amber-50 border-amber-200",
  low:       "text-slate-500 bg-slate-50 border-slate-200",
  very_low:  "text-slate-400 bg-slate-50 border-slate-100",
};

function urlPath(url: string): string {
  let path = url;
  try { path = new URL(url).pathname || "/"; } catch { /* keep original */ }
  return path.length > 40 ? path.slice(0, 39) + "…" : path;
}

function fmtAge(seconds: number): string {
  if (seconds < 60) return `${seconds}s`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
  return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
}

export function LiveSessionsCard({ brandId }: { brandId: string }) {
  const [data, setData] = useState<LiveSessionsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [windowMinutes, setWindowMinutes] = useState(30);

  const fetch = useCallback(async (isRefresh = false) => {
    if (isRefresh) setRefreshing(true);
    else setLoading(true);
    try {
      const res = await window.fetch(`/api/dashboard/live-sessions?brandId=${brandId}&windowMinutes=${windowMinutes}`);
      if (res.ok) {
        const json = await res.json();
        setData(json);
      }
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [brandId, windowMinutes]);

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

  // Auto-refresh every 30 seconds
  useEffect(() => {
    const id = setInterval(() => fetch(true), 30_000);
    return () => clearInterval(id);
  }, [fetch]);

  if (loading) {
    return (
      <div className="rounded-xl border border-slate-200 bg-white shadow-sm p-6 animate-pulse">
        <div className="h-4 w-40 bg-slate-200 rounded mb-4" />
        <div className="space-y-3">
          {[1, 2, 3].map((i) => <div key={i} className="h-12 bg-slate-100 rounded" />)}
        </div>
      </div>
    );
  }

  const { sessions = [], summary } = data ?? {};

  return (
    <div className="rounded-xl border border-slate-200 bg-white shadow-sm overflow-hidden">
      {/* Header */}
      <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between gap-4">
        <div className="flex items-center gap-2">
          <Activity className="w-4 h-4 text-emerald-500" />
          <h2 className="text-base font-semibold text-slate-900">Live Sessions</h2>
          {summary && (
            <span className="text-xs text-slate-400 ml-1">last {summary.windowMinutes} min</span>
          )}
        </div>
        <div className="flex items-center gap-3">
          <select
            value={windowMinutes}
            onChange={(e) => setWindowMinutes(Number(e.target.value))}
            className="text-xs border border-slate-200 rounded px-2 py-1 text-slate-600 bg-white focus:outline-none"
          >
            <option value={15}>15 min</option>
            <option value={30}>30 min</option>
            <option value={60}>60 min</option>
          </select>
          <button
            onClick={() => fetch(true)}
            disabled={refreshing}
            className="flex items-center gap-1 text-xs text-slate-400 hover:text-slate-700 transition-colors"
          >
            <RefreshCw className={`w-3.5 h-3.5 ${refreshing ? "animate-spin" : ""}`} />
            Refresh
          </button>
        </div>
      </div>

      {/* Summary strip */}
      {summary && (
        <div className="grid grid-cols-3 divide-x divide-slate-100 border-b border-slate-100">
          {[
            { label: "Active Sessions", value: summary.total },
            { label: "High-Intent", value: summary.highIntent },
            { label: "Avg Score", value: `${summary.avgScore}/100` },
          ].map(({ label, value }) => (
            <div key={label} className="px-4 py-3 text-center">
              <p className="text-lg font-bold text-slate-900">{value}</p>
              <p className="text-xs text-slate-400">{label}</p>
            </div>
          ))}
        </div>
      )}

      {/* Session list */}
      {sessions.length === 0 ? (
        <div className="px-6 py-10 text-center text-sm text-slate-400">
          No active sessions in the last {windowMinutes} minutes.
        </div>
      ) : (
        <div className="divide-y divide-slate-50">
          {sessions.map((s) => (
            <div key={s.sessionId} className="px-6 py-3 flex items-start gap-4">
              {/* Score badge */}
              <div className="shrink-0 text-center">
                <span className={`inline-flex items-center justify-center w-11 h-11 rounded-full text-sm font-bold border ${BAND_COLORS[s.scoreBand] ?? "bg-slate-50 text-slate-500 border-slate-200"}`}>
                  {s.score}
                </span>
              </div>
              {/* Session info */}
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="text-sm font-medium text-slate-700 truncate">{urlPath(s.entryPage)}</span>
                  <span className={`inline-block text-[10px] font-semibold px-1.5 py-0.5 rounded-full border ${BAND_COLORS[s.scoreBand] ?? ""}`}>
                    {s.scoreBandLabel}
                  </span>
                </div>
                <div className="flex items-center gap-3 mt-0.5 text-xs text-slate-400 flex-wrap">
                  {s.channelGroup && <span>{s.channelGroup}</span>}
                  {s.device && <span className="capitalize">{s.device}</span>}
                  {s.country && <span>{s.country}</span>}
                  <span>{s.pageCount} page{s.pageCount !== 1 ? "s" : ""}</span>
                  <span>{fmtAge(s.ageSeconds)} active</span>
                </div>
                {s.topFactors.length > 0 && (
                  <div className="flex flex-wrap gap-1 mt-1.5">
                    {s.topFactors.map((f) => (
                      <span key={f} className="inline-block text-[10px] bg-slate-100 text-slate-500 px-1.5 py-0.5 rounded">
                        {f}
                      </span>
                    ))}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
