'use client';

import React, { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { Activity, RefreshCw, Eye, Pause, CheckCircle2, Clock, Layers, VolumeX } from 'lucide-react';
import { RecipientAnalyticsItem, SessionStatus } from '@/lib/db/types';

function formatDuration(totalSeconds: number): string {
  const sec = Math.max(0, Math.round(totalSeconds));
  const hrs = Math.floor(sec / 3600);
  const mins = Math.floor((sec % 3600) / 60);
  const remSec = sec % 60;
  if (hrs > 0) {
    return `${hrs}:${String(mins).padStart(2, '0')}:${String(remSec).padStart(2, '0')}`;
  }
  return `${mins}:${String(remSec).padStart(2, '0')}`;
}

function StatusBadge({ status }: { status: SessionStatus }) {
  switch (status) {
    case 'Watching':
      return (
        <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-800">
          <span className="w-1.5 h-1.5 mr-1.5 rounded-full bg-emerald-500 animate-pulse" />
          Watching
        </span>
      );
    case 'Paused':
      return (
        <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-amber-100 text-amber-800">
          <Pause className="w-3 h-3 mr-1" />
          Paused
        </span>
      );
    case 'Buffering':
      return (
        <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-blue-100 text-blue-800">
          <RefreshCw className="w-3 h-3 mr-1 animate-spin" />
          Buffering
        </span>
      );
    case 'Tab Inactive':
      return (
        <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-indigo-100 text-indigo-800">
          <Layers className="w-3 h-3 mr-1" />
          Tab Inactive
        </span>
      );
    case 'Completed':
      return (
        <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-blue-100 text-blue-800">
          <CheckCircle2 className="w-3 h-3 mr-1" />
          Completed
        </span>
      );
    case 'Inactive':
    default:
      return (
        <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-slate-100 text-slate-600">
          <Clock className="w-3 h-3 mr-1" />
          {status}
        </span>
      );
  }
}

export default function AdminActivityPage() {
  const [items, setItems] = useState<RecipientAnalyticsItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);

  const fetchActivity = useCallback(async (indicator = false) => {
    if (indicator) setIsRefreshing(true);
    try {
      const res = await fetch('/api/admin/recipients');
      if (res.ok) {
        const data: RecipientAnalyticsItem[] = await res.json();
        const activeOnly = data
          .filter((d) => d.lastActivityAt)
          .sort((a, b) => new Date(b.lastActivityAt!).getTime() - new Date(a.lastActivityAt!).getTime());
        setItems(activeOnly);
      }
    } catch (err) {
      console.error('Failed to load activity feed:', err);
    } finally {
      setLoading(false);
      if (indicator) setIsRefreshing(false);
    }
  }, []);

  useEffect(() => {
    fetchActivity();
    const interval = setInterval(() => {
      fetchActivity(false);
    }, 10_000);
    return () => clearInterval(interval);
  }, [fetchActivity]);

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-slate-900 tracking-tight flex items-center space-x-2">
            <Activity className="w-6 h-6 text-blue-600" />
            <span>Viewing Activity Stream</span>
          </h1>
          <p className="text-xs text-slate-500 mt-1">
            Real-time feed with foreground/background, pause, and mute activity breakdown
          </p>
        </div>

        <button
          onClick={() => fetchActivity(true)}
          disabled={isRefreshing}
          className="self-start sm:self-auto inline-flex items-center space-x-1.5 px-3 py-1.5 text-xs font-semibold text-slate-600 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 shadow-sm transition"
        >
          <RefreshCw className={`w-3.5 h-3.5 ${isRefreshing ? 'animate-spin' : ''}`} />
          <span>Refresh Feed</span>
        </button>
      </div>

      <div className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
        {loading ? (
          <div className="p-8 text-center text-xs text-slate-400">Loading activity feed...</div>
        ) : items.length === 0 ? (
          <div className="p-8 text-center text-xs text-slate-400">
            No active or recent viewing sessions detected.
          </div>
        ) : (
          <div className="divide-y divide-slate-100">
            {items.map((item) => (
              <div
                key={item.assignmentId}
                className="p-4 sm:px-6 flex flex-col sm:flex-row sm:items-center justify-between gap-3 hover:bg-slate-50/70 transition"
              >
                <div className="flex items-center space-x-3.5">
                  <div
                    className={`w-3 h-3 rounded-full flex-shrink-0 ${
                      item.currentStatus === 'Watching'
                        ? 'bg-emerald-500 animate-pulse'
                        : item.currentStatus === 'Paused'
                        ? 'bg-amber-400'
                        : item.currentStatus === 'Tab Inactive'
                        ? 'bg-indigo-400'
                        : item.currentStatus === 'Buffering'
                        ? 'bg-blue-400 animate-spin'
                        : 'bg-slate-300'
                    }`}
                  />
                  <div>
                    <div className="text-xs sm:text-sm font-bold text-slate-900">
                      <Link
                        href={`/admin/recipients/${item.recipientId}`}
                        className="hover:text-blue-600"
                      >
                        {item.recipientName}
                      </Link>
                    </div>
                    <div className="text-xs text-slate-500 line-clamp-1">{item.videoTitle}</div>
                  </div>
                </div>

                <div className="flex flex-wrap items-center gap-3 self-end sm:self-center text-xs font-mono tabular-nums">
                  <div className="text-right">
                    <span className="text-[10px] text-slate-400 block font-sans">Watched:</span>
                    <span className="font-bold text-slate-900">{formatDuration(item.totalWatchSeconds)}</span>
                  </div>

                  <div className="text-right">
                    <span className="text-[10px] text-slate-400 block font-sans">Foreground:</span>
                    <span className="text-emerald-700">{formatDuration(item.foregroundWatchSeconds)}</span>
                  </div>

                  <div className="text-right">
                    <span className="text-[10px] text-slate-400 block font-sans">Pause:</span>
                    <span className="text-amber-700">{formatDuration(item.pauseSeconds)}</span>
                  </div>

                  <div className="text-right">
                    <span className="text-[10px] text-slate-400 block font-sans">Content:</span>
                    <span className="text-indigo-700 font-semibold">{formatDuration(item.contentWatchedSeconds)}</span>
                  </div>

                  <StatusBadge status={item.currentStatus} />

                  <div className="text-[11px] text-slate-400 min-w-[70px] text-right font-mono tabular-nums">
                    {item.lastActivityAt
                      ? new Date(item.lastActivityAt).toLocaleTimeString([], {
                          hour: '2-digit',
                          minute: '2-digit',
                          second: '2-digit',
                        })
                      : '—'}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
