'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import {
  ArrowLeft,
  User,
  Clock,
  Video,
  CheckCircle,
  PauseCircle,
  XCircle,
  History,
  Eye,
  Layers,
  VolumeX,
  Play,
  RefreshCw,
} from 'lucide-react';
import { IndividualRecipientDetails, 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">
          <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-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">
          <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-semibold bg-slate-100 text-slate-600">
          <XCircle className="w-3 h-3 mr-1" />
          {status}
        </span>
      );
  }
}

export default function IndividualRecipientPage() {
  const params = useParams();
  const recipientId = params.id as string;

  const [details, setDetails] = useState<IndividualRecipientDetails | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadData() {
      try {
        const res = await fetch(`/api/admin/recipients/${recipientId}`);
        if (res.ok) {
          const data = await res.json();
          setDetails(data);
        }
      } catch (err) {
        console.error('Failed to load recipient details:', err);
      } finally {
        setLoading(false);
      }
    }
    if (recipientId) {
      loadData();
    }
  }, [recipientId]);

  if (loading) {
    return (
      <div className="p-8 text-center text-xs text-slate-400">Loading recipient analytics...</div>
    );
  }

  if (!details) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-8 text-center">
        <h2 className="text-base font-bold text-slate-900 mb-2">Recipient Not Found</h2>
        <p className="text-xs text-slate-500 mb-4">
          The requested recipient profile could not be located.
        </p>
        <Link
          href="/admin/recipients"
          className="inline-flex items-center space-x-1.5 px-3 py-1.5 bg-blue-600 text-white rounded-lg text-xs font-semibold"
        >
          <ArrowLeft className="w-3.5 h-3.5" />
          <span>Back to Recipients</span>
        </Link>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header & Back Link */}
      <div className="flex items-center space-x-3">
        <Link
          href="/admin/recipients"
          className="p-1.5 rounded-lg border border-slate-200 bg-white text-slate-600 hover:bg-slate-50 shadow-sm"
        >
          <ArrowLeft className="w-4 h-4" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-slate-900 tracking-tight flex items-center space-x-2">
            <User className="w-5 h-5 text-blue-600" />
            <span>{details.recipient.name}</span>
          </h1>
          <p className="text-xs text-slate-500">
            Registered on {new Date(details.recipient.created_at).toLocaleDateString()}
          </p>
        </div>
      </div>

      {/* Video Assignments & Detailed Metrics */}
      {details.assignments.length === 0 ? (
        <div className="bg-white rounded-xl border border-slate-200 p-8 text-center text-xs text-slate-400">
          No videos currently assigned to this recipient.
        </div>
      ) : (
        <div className="space-y-6">
          {details.assignments.map((assignment) => (
            <div
              key={assignment.id}
              className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden"
            >
              {/* Assignment Title & Status Bar */}
              <div className="p-5 border-b border-slate-100 flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div className="flex items-start space-x-3.5">
                  <div className="p-2.5 bg-blue-50 text-blue-600 rounded-lg">
                    <Video className="w-5 h-5" />
                  </div>
                  <div>
                    <h2 className="text-sm font-bold text-slate-900">{assignment.video.title}</h2>
                    <div className="flex items-center space-x-2 text-xs text-slate-400 mt-0.5">
                      <span>YouTube ID: {assignment.video.youtube_video_id}</span>
                      <span>&bull;</span>
                      <span>Total Duration: {assignment.durationSeconds > 0 ? formatDuration(assignment.durationSeconds) : '—'}</span>
                      <span>&bull;</span>
                      <span>Link Status: {assignment.isActive ? 'Active' : 'Revoked'}</span>
                    </div>
                  </div>
                </div>

                <div className="flex items-center space-x-4">
                  <StatusBadge status={assignment.status} />
                </div>
              </div>

              {/* 7 Metric Cards Row */}
              <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-3 p-5 bg-slate-50/50 border-b border-slate-100 text-xs">
                {/* Total Watched Time */}
                <div className="bg-white p-3 rounded-lg border border-slate-100">
                  <div className="text-slate-400 uppercase tracking-wider text-[10px] font-semibold flex items-center space-x-1">
                    <Clock className="w-3 h-3 text-blue-600" />
                    <span>Total Watched</span>
                  </div>
                  <div className="text-base font-bold text-slate-900 mt-1 font-mono tabular-nums">
                    {formatDuration(assignment.totalWatchSeconds)}
                  </div>
                  <div className="text-[10px] text-slate-400 mt-0.5">Actual elapsed</div>
                </div>

                {/* Foreground Watched Time */}
                <div className="bg-white p-3 rounded-lg border border-slate-100">
                  <div className="text-slate-400 uppercase tracking-wider text-[10px] font-semibold flex items-center space-x-1">
                    <Eye className="w-3 h-3 text-emerald-600" />
                    <span>Foreground</span>
                  </div>
                  <div className="text-base font-bold text-emerald-700 mt-1 font-mono tabular-nums">
                    {formatDuration(assignment.foregroundWatchSeconds)}
                  </div>
                  <div className="text-[10px] text-slate-400 mt-0.5">Tab visible</div>
                </div>

                {/* Video Content Watched */}
                <div className="bg-white p-3 rounded-lg border border-slate-100">
                  <div className="text-slate-400 uppercase tracking-wider text-[10px] font-semibold flex items-center space-x-1">
                    <Play className="w-3 h-3 text-indigo-600" />
                    <span>Content Played</span>
                  </div>
                  <div className="text-base font-bold text-indigo-700 mt-1 font-mono tabular-nums">
                    {formatDuration(assignment.contentWatchedSeconds)}
                  </div>
                  <div className="text-[10px] text-slate-400 mt-0.5">Unique content</div>
                </div>

                {/* Pause Time */}
                <div className="bg-white p-3 rounded-lg border border-slate-100">
                  <div className="text-slate-400 uppercase tracking-wider text-[10px] font-semibold flex items-center space-x-1">
                    <PauseCircle className="w-3 h-3 text-amber-600" />
                    <span>Pause Time</span>
                  </div>
                  <div className="text-base font-bold text-amber-700 mt-1 font-mono tabular-nums">
                    {formatDuration(assignment.pauseSeconds)}
                  </div>
                  <div className="text-[10px] text-slate-400 mt-0.5">Player paused</div>
                </div>

                {/* Tab Inactive Time */}
                <div className="bg-white p-3 rounded-lg border border-slate-100">
                  <div className="text-slate-400 uppercase tracking-wider text-[10px] font-semibold flex items-center space-x-1">
                    <Layers className="w-3 h-3 text-purple-600" />
                    <span>Tab Inactive</span>
                  </div>
                  <div className="text-base font-bold text-purple-700 mt-1 font-mono tabular-nums">
                    {formatDuration(assignment.tabInactiveSeconds)}
                  </div>
                  <div className="text-[10px] text-slate-400 mt-0.5">Tab hidden</div>
                </div>

                {/* Muted Time */}
                <div className="bg-white p-3 rounded-lg border border-slate-100">
                  <div className="text-slate-400 uppercase tracking-wider text-[10px] font-semibold flex items-center space-x-1">
                    <VolumeX className="w-3 h-3 text-rose-600" />
                    <span>Muted Time</span>
                  </div>
                  <div className="text-base font-bold text-rose-700 mt-1 font-mono tabular-nums">
                    {formatDuration(assignment.mutedSeconds)}
                  </div>
                  <div className="text-[10px] text-slate-400 mt-0.5">Volume zero/muted</div>
                </div>

                {/* Completion % */}
                <div className="bg-white p-3 rounded-lg border border-slate-100">
                  <div className="text-slate-400 uppercase tracking-wider text-[10px] font-semibold flex items-center space-x-1">
                    <CheckCircle className="w-3 h-3 text-blue-600" />
                    <span>Completion</span>
                  </div>
                  <div className="text-base font-bold text-blue-700 mt-1 tabular-nums">
                    {assignment.progressPercent}%
                  </div>
                  <div className="text-[10px] text-slate-400 mt-0.5">Content covered</div>
                </div>
              </div>

              {/* Viewing Sessions Table */}
              <div className="p-5">
                <h3 className="text-xs font-bold text-slate-900 uppercase tracking-wider mb-3 flex items-center space-x-1.5">
                  <History className="w-3.5 h-3.5 text-slate-400" />
                  <span>Viewing Session History ({assignment.sessions.length})</span>
                </h3>

                {assignment.sessions.length === 0 ? (
                  <div className="text-xs text-slate-400 py-3">No viewing sessions recorded yet.</div>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="w-full text-left text-xs">
                      <thead className="text-slate-400 border-b border-slate-100 text-[11px]">
                        <tr>
                          <th className="py-2 px-3 font-semibold">Session Start</th>
                          <th className="py-2 px-3 font-semibold">Last Heartbeat / End</th>
                          <th className="py-2 px-3 font-semibold text-right">Actual Watched</th>
                          <th className="py-2 px-3 font-semibold text-right">Foreground</th>
                          <th className="py-2 px-3 font-semibold text-right">Content Watched</th>
                          <th className="py-2 px-3 font-semibold text-right">Pause Time</th>
                          <th className="py-2 px-3 font-semibold text-right">Tab Inactive</th>
                          <th className="py-2 px-3 font-semibold text-right">Muted Time</th>
                          <th className="py-2 px-3 font-semibold">Status</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100 text-slate-700">
                        {assignment.sessions.map((sess) => (
                          <tr key={sess.id} className="hover:bg-slate-50/60">
                            <td className="py-2.5 px-3 font-medium">
                              {new Date(sess.started_at).toLocaleTimeString([], {
                                hour: '2-digit',
                                minute: '2-digit',
                                second: '2-digit',
                              })}
                            </td>
                            <td className="py-2.5 px-3 text-slate-500">
                              {sess.ended_at
                                ? new Date(sess.ended_at).toLocaleTimeString([], {
                                    hour: '2-digit',
                                    minute: '2-digit',
                                    second: '2-digit',
                                  })
                                : new Date(sess.last_heartbeat_at).toLocaleTimeString([], {
                                    hour: '2-digit',
                                    minute: '2-digit',
                                    second: '2-digit',
                                  })}
                            </td>
                            <td className="py-2.5 px-3 text-right font-bold text-slate-900 font-mono tabular-nums">
                              {formatDuration(sess.total_watch_seconds)}
                            </td>
                            <td className="py-2.5 px-3 text-right font-mono text-emerald-700 tabular-nums">
                              {formatDuration(sess.foreground_watch_seconds)}
                            </td>
                            <td className="py-2.5 px-3 text-right font-mono text-indigo-700 font-semibold tabular-nums">
                              {formatDuration(sess.content_watched_seconds)}
                            </td>
                            <td className="py-2.5 px-3 text-right font-mono text-amber-700 tabular-nums">
                              {formatDuration(sess.pause_seconds)}
                            </td>
                            <td className="py-2.5 px-3 text-right font-mono text-slate-500 tabular-nums">
                              {formatDuration(sess.tab_inactive_seconds)}
                            </td>
                            <td className="py-2.5 px-3 text-right font-mono text-slate-500 tabular-nums">
                              {formatDuration(sess.muted_seconds)}
                            </td>
                            <td className="py-2.5 px-3">
                              <StatusBadge status={sess.status} />
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
