'use client';

import React, { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import {
  Video,
  Users,
  Clock,
  Eye,
  PlusCircle,
  ArrowRight,
  RefreshCw,
  CheckCircle,
  PauseCircle,
  XCircle,
  Layers,
  VolumeX,
} from 'lucide-react';
import { DashboardStats, 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-medium 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-medium bg-amber-100 text-amber-800">
          <PauseCircle 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-medium 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-medium 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-medium bg-blue-100 text-blue-800">
          <CheckCircle 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-medium bg-slate-100 text-slate-600">
          <XCircle className="w-3 h-3 mr-1" />
          {status}
        </span>
      );
  }
}

export default function AdminDashboardPage() {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);

  const fetchStats = useCallback(async (showIndicator = false) => {
    if (showIndicator) setIsRefreshing(true);
    try {
      const res = await fetch('/api/admin/dashboard');
      if (res.ok) {
        const data = await res.json();
        setStats(data);
      }
    } catch (err) {
      console.error('Failed to load dashboard statistics:', err);
    } finally {
      setLoading(false);
      if (showIndicator) setIsRefreshing(false);
    }
  }, []);

  // Initial load + Auto-refresh every 10 seconds
  useEffect(() => {
    fetchStats();
    const interval = setInterval(() => {
      fetchStats(false);
    }, 10_000);
    return () => clearInterval(interval);
  }, [fetchStats]);

  return (
    <div className="space-y-6">
      {/* Header */}
      <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">Overview Dashboard</h1>
          <p className="text-xs text-slate-500 mt-1">
            Real-time playback and engagement analytics &bull; Auto-refreshes every 10s
          </p>
        </div>

        <div className="flex items-center space-x-3">
          <button
            onClick={() => fetchStats(true)}
            disabled={isRefreshing}
            className="inline-flex items-center space-x-1.5 px-3 py-1.5 text-xs font-medium 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</span>
          </button>
          <Link
            href="/admin/videos"
            className="inline-flex items-center space-x-1.5 px-3.5 py-1.5 text-xs font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 shadow-sm transition"
          >
            <PlusCircle className="w-3.5 h-3.5" />
            <span>Add Video</span>
          </Link>
        </div>
      </div>

      {/* Main Metric Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* Total Videos */}
        <div className="bg-white rounded-xl border border-slate-200 p-5 shadow-sm">
          <div className="flex items-center justify-between text-slate-500 mb-2">
            <span className="text-xs font-semibold uppercase tracking-wider">Total Videos</span>
            <div className="p-2 rounded-lg bg-blue-50 text-blue-600">
              <Video className="w-4 h-4" />
            </div>
          </div>
          <div className="text-4xl font-black text-slate-900 tabular-nums">
            {loading ? '—' : stats?.totalVideos ?? 0}
          </div>
          <div className="text-[11px] text-slate-400 mt-1">Tracked YouTube videos</div>
        </div>

        {/* Total Recipients */}
        <div className="bg-white rounded-xl border border-slate-200 p-5 shadow-sm">
          <div className="flex items-center justify-between text-slate-500 mb-2">
            <span className="text-xs font-semibold uppercase tracking-wider">Total Recipients</span>
            <div className="p-2 rounded-lg bg-indigo-50 text-indigo-600">
              <Users className="w-4 h-4" />
            </div>
          </div>
          <div className="text-4xl font-black text-slate-900 tabular-nums">
            {loading ? '—' : stats?.totalRecipients ?? 0}
          </div>
          <div className="text-[11px] text-slate-400 mt-1">Unique assigned recipients</div>
        </div>

        {/* Total Watched Time */}
        <div className="bg-white rounded-xl border border-slate-200 p-5 shadow-sm">
          <div className="flex items-center justify-between text-slate-500 mb-2">
            <span className="text-xs font-semibold uppercase tracking-wider">Total Watched Time</span>
            <div className="p-2 rounded-lg bg-emerald-50 text-emerald-600">
              <Clock className="w-4 h-4" />
            </div>
          </div>
          <div className="text-4xl font-black text-slate-900 tabular-nums font-mono">
            {loading ? '—' : formatDuration(stats?.totalWatchSeconds ?? 0)}
          </div>
          <div className="text-[11px] text-slate-400 mt-1 flex items-center space-x-1">
            <span>Foreground:</span>
            <span className="font-semibold text-slate-700">
              {formatDuration(stats?.totalForegroundWatchSeconds ?? 0)}
            </span>
          </div>
        </div>

        {/* Currently Watching */}
        <div className="bg-white rounded-xl border border-slate-200 p-5 shadow-sm">
          <div className="flex items-center justify-between text-slate-500 mb-2">
            <span className="text-xs font-semibold uppercase tracking-wider">Currently Watching</span>
            <div className="p-2 rounded-lg bg-amber-50 text-amber-600">
              <Eye className="w-4 h-4" />
            </div>
          </div>
          <div className="text-4xl font-black text-slate-900 tabular-nums flex items-center space-x-2">
            <span>{loading ? '—' : stats?.currentlyWatchingCount ?? 0}</span>
            {(stats?.currentlyWatchingCount ?? 0) > 0 && (
              <span className="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse" />
            )}
          </div>
          <div className="text-[11px] text-slate-400 mt-1">Active recipients right now</div>
        </div>
      </div>

      {/* Secondary Metrics Strip: Pause, Inactivity, Muted Totals */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 bg-white p-4 rounded-xl border border-slate-200 shadow-sm text-xs">
        <div className="flex items-center space-x-3 p-2">
          <div className="p-2 rounded-lg bg-amber-50 text-amber-600">
            <PauseCircle className="w-4 h-4" />
          </div>
          <div>
            <div className="text-slate-400 text-[10px] uppercase font-bold">Total Pause Time</div>
            <div className="text-xl font-black text-slate-800 tabular-nums font-mono">
              {loading ? '—' : formatDuration(stats?.totalPauseSeconds ?? 0)}
            </div>
          </div>
        </div>

        <div className="flex items-center space-x-3 p-2 border-t sm:border-t-0 sm:border-l border-slate-100">
          <div className="p-2 rounded-lg bg-purple-50 text-purple-600">
            <Layers className="w-4 h-4" />
          </div>
          <div>
            <div className="text-slate-400 text-[10px] uppercase font-bold">Total Tab Inactive Time</div>
            <div className="text-xl font-black text-slate-800 tabular-nums font-mono">
              {loading ? '—' : formatDuration(stats?.totalTabInactiveSeconds ?? 0)}
            </div>
          </div>
        </div>

        <div className="flex items-center space-x-3 p-2 border-t sm:border-t-0 sm:border-l border-slate-100">
          <div className="p-2 rounded-lg bg-rose-50 text-rose-600">
            <VolumeX className="w-4 h-4" />
          </div>
          <div>
            <div className="text-slate-400 text-[10px] uppercase font-bold">Total Muted Time</div>
            <div className="text-xl font-black text-slate-800 tabular-nums font-mono">
              {loading ? '—' : formatDuration(stats?.totalMutedSeconds ?? 0)}
            </div>
          </div>
        </div>
      </div>

      {/* Recent Activity Table */}
      <div className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
        <div className="p-4 sm:px-6 border-b border-slate-100 flex items-center justify-between">
          <div>
            <h2 className="text-sm font-bold text-slate-900">Recent Viewing Activity</h2>
            <p className="text-xs text-slate-400">Latest playback updates with high-resolution metrics</p>
          </div>
          <Link
            href="/admin/recipients"
            className="text-xs font-medium text-blue-600 hover:text-blue-700 flex items-center space-x-1"
          >
            <span>View All Analytics</span>
            <ArrowRight className="w-3.5 h-3.5" />
          </Link>
        </div>

        {loading ? (
          <div className="p-8 text-center text-xs text-slate-400">Loading activity data...</div>
        ) : !stats?.recentActivity || stats.recentActivity.length === 0 ? (
          <div className="p-8 text-center text-xs text-slate-400">
            No viewing activity recorded yet. Share a tracking link with a recipient to begin tracking.
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs">
              <thead className="bg-slate-50 text-slate-500 border-b border-slate-100">
                <tr>
                  <th className="py-2.5 px-4 font-semibold">Recipient</th>
                  <th className="py-2.5 px-4 font-semibold">Video</th>
                  <th className="py-2.5 px-4 font-semibold">Status</th>
                  <th className="py-2.5 px-4 font-semibold text-right">Actual Watched</th>
                  <th className="py-2.5 px-4 font-semibold text-right">Video Duration</th>
                  <th className="py-2.5 px-4 font-semibold text-right">Foreground</th>
                  <th className="py-2.5 px-4 font-semibold text-right">Pause Time</th>
                  <th className="py-2.5 px-4 font-semibold text-right">Last Activity</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 text-slate-700">
                {stats.recentActivity.map((act, idx) => (
                  <tr key={idx} className="hover:bg-slate-50/70 transition">
                    <td className="py-3 px-4 font-medium text-slate-900">{act.recipientName}</td>
                    <td className="py-3 px-4 text-slate-600 truncate max-w-xs">{act.videoTitle}</td>
                    <td className="py-3 px-4">
                      <StatusBadge status={act.status} />
                    </td>
                    <td className="py-3 px-4 text-right font-mono font-bold text-slate-900 tabular-nums">
                      {formatDuration(act.totalWatchSeconds)}
                    </td>
                    <td className="py-3 px-4 text-right font-mono text-slate-500 tabular-nums">
                      {act.durationSeconds > 0 ? formatDuration(act.durationSeconds) : '—'}
                    </td>
                    <td className="py-3 px-4 text-right font-mono text-emerald-700 tabular-nums">
                      {formatDuration(act.foregroundWatchSeconds)}
                    </td>
                    <td className="py-3 px-4 text-right font-mono text-amber-700 tabular-nums">
                      {formatDuration(act.pauseSeconds)}
                    </td>
                    <td className="py-3 px-4 text-right text-slate-400 font-mono tabular-nums">
                      {new Date(act.lastHeartbeatAt).toLocaleTimeString([], {
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit',
                      })}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
