'use client';

import React, { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import {
  Users,
  RefreshCw,
  Search,
  ExternalLink,
  Ban,
  CheckCircle2,
  Clock,
  Play,
  Pause,
  Layers,
  VolumeX,
  Eye,
} 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':
      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" />
          Inactive
        </span>
      );
    case 'Not Started':
    default:
      return (
        <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-500">
          Not Started
        </span>
      );
  }
}

export default function AdminRecipientsPage() {
  const [analytics, setAnalytics] = useState<RecipientAnalyticsItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('ALL');
  const [isRefreshing, setIsRefreshing] = useState(false);

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

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

  const toggleLinkStatus = async (assignmentId: string, currentActive: boolean) => {
    try {
      const res = await fetch(`/api/admin/assignments/${assignmentId}/revoke`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isActive: !currentActive }),
      });
      if (res.ok) {
        fetchAnalytics(false);
      }
    } catch (err) {
      console.error('Failed to toggle link status:', err);
    }
  };

  const filteredAnalytics = analytics.filter((item) => {
    const matchesSearch =
      item.recipientName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.videoTitle.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = statusFilter === 'ALL' || item.currentStatus === statusFilter;
    return matchesSearch && matchesStatus;
  });

  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">Recipient Analytics</h1>
          <p className="text-xs text-slate-500 mt-1">
            Verified watch-time, foreground/background breakdown, pause, tab inactivity, and muted metrics
          </p>
        </div>

        <button
          onClick={() => fetchAnalytics(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</span>
        </button>
      </div>

      {/* Search & Filter Toolbar */}
      <div className="flex flex-col sm:flex-row items-center justify-between gap-3 bg-white p-3 rounded-xl border border-slate-200 shadow-sm">
        <div className="relative w-full sm:w-72">
          <Search className="w-3.5 h-3.5 text-slate-400 absolute left-3 top-2.5" />
          <input
            type="text"
            placeholder="Search by recipient or video title..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-9 pr-3 py-1.5 text-xs border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <div className="flex items-center space-x-2 w-full sm:w-auto">
          <span className="text-xs text-slate-500 font-medium">Status:</span>
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="text-xs border border-slate-200 rounded-lg px-2.5 py-1.5 bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="ALL">All Statuses</option>
            <option value="Watching">Watching</option>
            <option value="Paused">Paused</option>
            <option value="Buffering">Buffering</option>
            <option value="Tab Inactive">Tab Inactive</option>
            <option value="Completed">Completed</option>
            <option value="Inactive">Inactive</option>
            <option value="Not Started">Not Started</option>
          </select>
        </div>
      </div>

      {/* Main Table with Detailed Metrics */}
      <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 recipient analytics...</div>
        ) : filteredAnalytics.length === 0 ? (
          <div className="p-8 text-center text-xs text-slate-400">
            No recipient assignments found. Add videos and assign recipients to track playback.
          </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-200">
                <tr>
                  <th className="py-3 px-3 font-semibold">Recipient</th>
                  <th className="py-3 px-3 font-semibold">Video</th>
                  <th className="py-3 px-3 font-semibold text-right">Duration</th>
                  <th className="py-3 px-3 font-semibold text-right">Actual Watched</th>
                  <th className="py-3 px-3 font-semibold text-right">Foreground</th>
                  <th className="py-3 px-3 font-semibold text-right">Content Watched</th>
                  <th className="py-3 px-3 font-semibold text-right">Pause Time</th>
                  <th className="py-3 px-3 font-semibold text-right">Tab Inactive</th>
                  <th className="py-3 px-3 font-semibold text-right">Muted Time</th>
                  <th className="py-3 px-3 font-semibold">Completion</th>
                  <th className="py-3 px-3 font-semibold">Status</th>
                  <th className="py-3 px-3 font-semibold text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 text-slate-700">
                {filteredAnalytics.map((item) => (
                  <tr key={item.assignmentId} className="hover:bg-slate-50/70 transition">
                    {/* Recipient Name */}
                    <td className="py-3.5 px-3 font-bold text-slate-900">
                      <Link
                        href={`/admin/recipients/${item.recipientId}`}
                        className="hover:text-blue-600 transition"
                      >
                        {item.recipientName}
                      </Link>
                    </td>

                    {/* Video Title */}
                    <td className="py-3.5 px-3 text-slate-600 truncate max-w-[180px] font-medium" title={item.videoTitle}>
                      {item.videoTitle}
                    </td>

                    {/* Total Video Duration */}
                    <td className="py-3.5 px-3 text-right font-mono text-sm text-slate-600 tabular-nums">
                      {item.durationSeconds > 0 ? formatDuration(item.durationSeconds) : '—'}
                    </td>

                    {/* Actual Watched Time */}
                    <td className="py-3.5 px-3 text-right font-mono text-sm font-bold text-slate-900 bg-blue-50/30 tabular-nums">
                      {formatDuration(item.totalWatchSeconds)}
                    </td>

                    {/* Foreground Watched Time */}
                    <td className="py-3.5 px-3 text-right font-mono text-sm text-slate-700 tabular-nums">
                      {formatDuration(item.foregroundWatchSeconds)}
                    </td>

                    {/* Video Content Watched */}
                    <td className="py-3.5 px-3 text-right font-mono text-sm font-semibold text-indigo-700 tabular-nums">
                      {formatDuration(item.contentWatchedSeconds)}
                    </td>

                    {/* Pause Time */}
                    <td className="py-3.5 px-3 text-right font-mono text-sm text-amber-700 tabular-nums">
                      {formatDuration(item.pauseSeconds)}
                    </td>

                    {/* Tab Inactive Time */}
                    <td className="py-3.5 px-3 text-right font-mono text-sm text-slate-500 tabular-nums">
                      {formatDuration(item.tabInactiveSeconds)}
                    </td>

                    {/* Muted Time */}
                    <td className="py-3.5 px-3 text-right font-mono text-sm text-slate-500 tabular-nums">
                      {formatDuration(item.mutedSeconds)}
                    </td>

                    {/* Completion % */}
                    <td className="py-3.5 px-3">
                      <div className="flex items-center space-x-1.5">
                        <div className="w-14 bg-slate-100 h-1.5 rounded-full overflow-hidden">
                          <div
                            className="bg-blue-600 h-full rounded-full transition-all"
                            style={{ width: `${item.progressPercent}%` }}
                          />
                        </div>
                        <span className="text-sm font-black text-slate-800 tabular-nums">
                          {item.progressPercent}%
                        </span>
                      </div>
                    </td>

                    {/* Status */}
                    <td className="py-3.5 px-3">
                      <StatusBadge status={item.currentStatus} />
                    </td>

                    {/* Actions */}
                    <td className="py-3.5 px-3 text-right">
                      <div className="flex items-center justify-end space-x-1.5">
                        <button
                          onClick={() => toggleLinkStatus(item.assignmentId, item.isActive)}
                          className={`p-1.5 rounded text-xs transition ${
                            item.isActive
                              ? 'text-red-600 hover:bg-red-50'
                              : 'text-emerald-600 hover:bg-emerald-50'
                          }`}
                          title={item.isActive ? 'Revoke tracking link' : 'Re-activate link'}
                        >
                          {item.isActive ? (
                            <Ban className="w-3.5 h-3.5" />
                          ) : (
                            <CheckCircle2 className="w-3.5 h-3.5" />
                          )}
                        </button>

                        <Link
                          href={`/admin/recipients/${item.recipientId}`}
                          className="p-1.5 text-slate-400 hover:text-blue-600 rounded hover:bg-slate-100"
                          title="View Recipient History"
                        >
                          <ExternalLink className="w-3.5 h-3.5" />
                        </Link>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
