"use client";

import { useState, useEffect, useCallback } from "react";
import { Video, MessageSquare, Play, CheckCircle2, Gauge, Clock } from "lucide-react";
import { TableSkeleton } from "./_shared";

// ─── Types ──────────────────────────────────────────────────────

interface VideoStats {
  videoPlays: number;
  videoCompletes: number;
  completionRate: number;       // 0-100
  totalWatchTimeMs: number;
  avgWatchTimeMs: number;
  chatOpens: number;
  chatWidgetsDetected: number;
  chatMessages: number;
}
interface TopVideoRow {
  videoId: string;
  title: string | null;
  provider: string | null;
  plays: number;
  completes: number;
  completionRate: number;       // 0-100
  avgWatchTimeMs: number;
}
interface ChatEvent { date: string; page: string; platform: string; action: string }
interface ChatSummary {
  opens: number;
  widgetsDetected: number;
  messages: number;
  topPage: string | null;
  events: ChatEvent[];
}
interface VideoChatData {
  stats: VideoStats;
  topVideos: TopVideoRow[];
  chat: ChatSummary;
  videos?: unknown[]; // legacy, ignored
}

export interface VideoChatTabProps { brandId: string; range: string }

// ─── Helpers ────────────────────────────────────────────────────

function fmtMs(ms: number): string {
  if (!ms || ms < 1000) return `${Math.round(ms)}ms`;
  const s = Math.round(ms / 1000);
  if (s < 60) return `${s}s`;
  const m = Math.floor(s / 60);
  const rs = s % 60;
  return rs > 0 ? `${m}m ${rs}s` : `${m}m`;
}

function completionTone(pct: number): string {
  if (pct >= 50) return "text-green-600";
  if (pct >= 20) return "text-amber-600";
  return "text-slate-400";
}

// ─── Component ──────────────────────────────────────────────────

export function VideoChatTab({ brandId, range }: VideoChatTabProps) {
  const [data, setData] = useState<VideoChatData | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch(`/api/site-tag/analytics/video-chat?brandId=${brandId}&range=${range}`);
    if (res.ok) setData(await res.json());
    setLoading(false);
  }, [brandId, range]);

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

  if (loading && !data) {
    return (
      <div className="space-y-6">
        <TableSkeleton rows={5} cols={5} />
      </div>
    );
  }

  // Only show the empty splash if there's NO video or chat activity
  // whatsoever — per spec, "No video data yet" gates purely on
  // videoPlays, but chat-only brands should still see their chat
  // stats instead of the splash.
  const stats = data?.stats;
  const topVideos = data?.topVideos ?? [];
  const chat = data?.chat;
  const hasAny = !!stats && (
    stats.videoPlays > 0 ||
    stats.videoCompletes > 0 ||
    stats.chatOpens > 0 ||
    stats.chatWidgetsDetected > 0 ||
    stats.chatMessages > 0
  );
  if (!hasAny) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-12 text-center">
        <Video className="w-10 h-10 text-slate-200 mx-auto mb-3" />
        <h2 className="text-lg font-bold text-slate-900 mb-1">No video or chat data yet</h2>
        <p className="text-sm text-slate-500 max-w-sm mx-auto">
          This tab populates once the Site Tag detects video players (YouTube, Vimeo, HTML5, Wistia, Vidyard, Loom) or chat widgets on your site.
        </p>
      </div>
    );
  }

  const videoLive = stats!.videoPlays > 0;
  const chatLive = stats!.chatOpens > 0 || stats!.chatWidgetsDetected > 0 || stats!.chatMessages > 0;

  return (
    <div className="space-y-6">
      {/* ── Video Stats ─────────────────────────────────────── */}
      {videoLive ? (
        <div className="space-y-3">
          <h2 className="text-base font-bold text-slate-900 flex items-center gap-2">
            <Play className="w-4 h-4 text-slate-500" />
            Video Engagement
          </h2>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
            <MiniStat icon={Play}          label="Total Plays"      value={stats!.videoPlays.toLocaleString()}  accent="text-violet-700" bg="bg-violet-50" />
            <MiniStat icon={CheckCircle2}  label="Completions"      value={stats!.videoCompletes.toLocaleString()} accent="text-emerald-700" bg="bg-emerald-50" />
            <MiniStat icon={Gauge}         label="Completion Rate"  value={`${stats!.completionRate}%`} accent={completionTone(stats!.completionRate)} bg="bg-slate-50" />
            <MiniStat icon={Clock}         label="Avg Watch Time"   value={stats!.avgWatchTimeMs > 0 ? fmtMs(stats!.avgWatchTimeMs) : "—"} accent="text-slate-700" bg="bg-slate-50" />
          </div>

          {topVideos.length > 0 ? (
            <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
              <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
                <Video className="w-4 h-4 text-brand-600" />
                <h3 className="font-bold text-slate-800 text-sm">Top Videos</h3>
              </div>
              <table className="w-full text-sm">
                <thead>
                  <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100 bg-slate-50/40">
                    <th className="px-5 py-2.5">Video</th>
                    <th className="px-5 py-2.5">Provider</th>
                    <th className="px-5 py-2.5 text-right">Plays</th>
                    <th className="px-5 py-2.5 text-right">Completion Rate</th>
                    <th className="px-5 py-2.5 text-right">Avg Watch Time</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {topVideos.map((v) => (
                    <tr key={v.videoId} className="hover:bg-slate-50 transition-colors">
                      <td className="px-5 py-2.5 max-w-[280px]">
                        <p className="text-xs font-semibold text-slate-800 truncate" title={v.title ?? v.videoId}>{v.title || v.videoId}</p>
                        {v.title && (
                          <p className="font-mono text-[10px] text-slate-400 truncate" title={v.videoId}>{v.videoId}</p>
                        )}
                      </td>
                      <td className="px-5 py-2.5 text-xs text-slate-600 capitalize">{v.provider ?? "—"}</td>
                      <td className="px-5 py-2.5 text-right font-bold text-slate-900 tabular-nums">{v.plays.toLocaleString()}</td>
                      <td className="px-5 py-2.5 text-right tabular-nums">
                        <span className={`text-xs font-semibold ${completionTone(v.completionRate)}`}>{v.completionRate}%</span>
                      </td>
                      <td className="px-5 py-2.5 text-right text-xs text-slate-600 tabular-nums">
                        {v.avgWatchTimeMs > 0 ? fmtMs(v.avgWatchTimeMs) : "—"}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50/60 px-5 py-4 text-[11px] text-slate-500">
              Plays have been captured but no per-video breakdown is available yet — videos without a detectable video_id roll up into a single unlabelled bucket.
            </div>
          )}
        </div>
      ) : (
        <div className="bg-white rounded-xl border border-dashed border-slate-200 p-8 text-center">
          <Play className="w-8 h-8 text-slate-300 mx-auto mb-2" />
          <p className="text-sm font-semibold text-slate-700">No video plays yet</p>
          <p className="text-xs text-slate-400 mt-1 max-w-sm mx-auto">
            The Site Tag watches for YouTube, Vimeo, HTML5, Wistia, Vidyard, and Loom players. Once a visitor plays one, stats appear here.
          </p>
        </div>
      )}

      {/* ── Chat Stats ──────────────────────────────────────── */}
      {chatLive && (
        <div className="space-y-3">
          <h2 className="text-base font-bold text-slate-900 flex items-center gap-2">
            <MessageSquare className="w-4 h-4 text-slate-500" />
            Chat Interactions
          </h2>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
            <MiniStat icon={MessageSquare}  label="Chat Opens"         value={stats!.chatOpens.toLocaleString()}             accent="text-cyan-700"    bg="bg-cyan-50" />
            <MiniStat icon={MessageSquare}  label="Widgets Detected"   value={stats!.chatWidgetsDetected.toLocaleString()}   accent="text-indigo-700"  bg="bg-indigo-50" />
            <MiniStat icon={MessageSquare}  label="Messages Sent"      value={stats!.chatMessages.toLocaleString()}          accent="text-slate-700"   bg="bg-slate-50" />
            <div className="bg-white rounded-xl border border-slate-200 px-4 py-4">
              <div className="flex items-center gap-2 mb-2">
                <span className="w-7 h-7 rounded-lg bg-slate-100 text-slate-600 flex items-center justify-center">
                  <MessageSquare className="w-3.5 h-3.5" />
                </span>
                <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500">Top Chat Page</p>
              </div>
              <p className="font-mono text-xs text-brand-600 truncate" title={chat?.topPage ?? ""}>
                {chat?.topPage ?? "—"}
              </p>
            </div>
          </div>

          {chat && chat.events.length > 0 && (
            <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
              <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
                <MessageSquare className="w-4 h-4 text-brand-600" />
                <h3 className="font-bold text-slate-800 text-sm">Recent Chat Events</h3>
              </div>
              <table className="w-full text-sm">
                <thead>
                  <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100 bg-slate-50/40">
                    <th className="px-5 py-2.5">Date</th>
                    <th className="px-5 py-2.5">Page</th>
                    <th className="px-5 py-2.5">Platform</th>
                    <th className="px-5 py-2.5">Action</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {chat.events.slice(0, 20).map((e, i) => (
                    <tr key={i}>
                      <td className="px-5 py-2.5 text-xs text-slate-500 tabular-nums">
                        {new Date(e.date).toLocaleString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })}
                      </td>
                      <td className="px-5 py-2.5 font-mono text-xs text-brand-600 truncate max-w-[200px]">{e.page}</td>
                      <td className="px-5 py-2.5 text-xs text-slate-600 capitalize">{e.platform}</td>
                      <td className="px-5 py-2.5 text-xs text-slate-700 capitalize">{e.action.replace(/_/g, " ")}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ─── Reusable mini-stat card ────────────────────────────────────

function MiniStat({
  icon: Icon, label, value, accent, bg,
}: {
  icon: typeof Play;
  label: string;
  value: string;
  accent: string;
  bg: string;
}) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 px-4 py-4">
      <div className="flex items-center gap-2 mb-2">
        <span className={`w-7 h-7 rounded-lg ${bg} ${accent} flex items-center justify-center`}>
          <Icon className="w-3.5 h-3.5" />
        </span>
        <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500">{label}</p>
      </div>
      <p className={`text-2xl font-bold tabular-nums leading-none ${accent}`}>{value}</p>
    </div>
  );
}
