import React, { useState, useEffect, useRef } from "react";
import { 
  Tv, 
  Wifi, 
  Maximize2, 
  Volume2, 
  VolumeX, 
  Play, 
  Pause, 
  Radio, 
  Building2, 
  Users, 
  TrendingUp, 
  CheckCircle2, 
  Clock, 
  Zap, 
  ShieldCheck, 
  Pointer, 
  ChevronRight, 
  ChevronLeft, 
  Layers, 
  BarChart3, 
  DollarSign, 
  Activity,
  X
} from "lucide-react";

interface TvPresentationDisplayProps {
  onCloseWindow?: () => void;
}

export default function TvPresentationDisplay({ onCloseWindow }: TvPresentationDisplayProps) {
  const [castMode, setCastMode] = useState<"full" | "presentation" | "dashboard" | "rkap">("full");
  const [isPaused, setIsPaused] = useState(false);
  const [laserPos, setLaserPos] = useState<{ x: number; y: number } | null>({ x: 50, y: 50 });
  const [showLaser, setShowLaser] = useState(true);
  const [audioMuted, setAudioMuted] = useState(false);
  const [activeSlide, setActiveSlide] = useState(0);
  const [currentTime, setCurrentTime] = useState(new Date().toLocaleTimeString("id-ID"));
  const [currentDate, setCurrentDate] = useState("");
  const [isFullscreen, setIsFullscreen] = useState(false);

  // Broadcast Channel listener to sync controls from main app/modal in real-time
  useEffect(() => {
    const bc = new BroadcastChannel("ems_tv_cast");
    
    bc.onmessage = (event) => {
      const data = event.data;
      if (!data) return;

      if (data.type === "SET_MODE" && data.mode) {
        setCastMode(data.mode);
      } else if (data.type === "TOGGLE_PAUSE") {
        setIsPaused(data.isPaused);
      } else if (data.type === "UPDATE_LASER") {
        setLaserPos(data.pos);
        setShowLaser(data.showLaser);
      } else if (data.type === "SET_SLIDE") {
        setActiveSlide(data.slideIndex);
      } else if (data.type === "TOGGLE_AUDIO") {
        setAudioMuted(data.muted);
      }
    };

    return () => {
      bc.close();
    };
  }, []);

  // Live Clock
  useEffect(() => {
    const timer = setInterval(() => {
      const now = new Date();
      setCurrentTime(now.toLocaleTimeString("id-ID", { hour: "2-digit", minute: "2-digit", second: "2-digit" }));
      setCurrentDate(now.toLocaleDateString("id-ID", { weekday: "long", day: "numeric", month: "long", year: "numeric" }));
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  // Mouse move handler for laser pointer when focused on this window
  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!showLaser) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * 100;
    const y = ((e.clientY - rect.top) / rect.height) * 100;
    setLaserPos({ x, y });

    // Broadcast laser pos to modal preview as well
    const bc = new BroadcastChannel("ems_tv_cast");
    bc.postMessage({ type: "LASER_MOVED", pos: { x, y } });
    bc.close();
  };

  const toggleFullscreenMode = () => {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen().then(() => setIsFullscreen(true)).catch(() => {});
    } else {
      document.exitFullscreen().then(() => setIsFullscreen(false)).catch(() => {});
    }
  };

  const SLIDES = [
    {
      title: "Ringkasan Eksekutif & KPI Utama Q3 2026",
      subtitle: "PT Media Ekosistem Digital Aplikasi Nasional (EMS GAN)",
      metrics: [
        { label: "Total Pegawai Aktif", val: "1,248", change: "+12% MoM", icon: Users },
        { label: "Presensi Hari Ini", val: "98.4%", change: "On-Time 94%", icon: CheckCircle2 },
        { label: "Total Pendapatan RKAP", val: "Rp 148.5 M", change: "104% Target", icon: TrendingUp },
        { label: "Workflow SLA Approval", val: "1.2 Jam", change: "Fastest 15m", icon: Zap }
      ]
    },
    {
      title: "Realisasi Anggaran & Kas Perusahaan (RKAP)",
      subtitle: "Analisis Real-time Pendapatan vs Pengeluaran Operasional",
      metrics: [
        { label: "Saldo Kas & Bank", val: "Rp 42.8 M", change: "Liquidity Safe", icon: DollarSign },
        { label: "Capex Terdisbursi", val: "Rp 18.2 M", change: "78% Budget", icon: BarChart3 },
        { label: "Opex Efisiensi", val: "Rp 12.4 M", change: "Saved 6.4%", icon: ShieldCheck },
        { label: "Rasio Profitabilitas", val: "22.8%", change: "+3.2% Target", icon: Activity }
      ]
    },
    {
      title: "Digital Inovasi & Replikasi Infrastructure",
      subtitle: "Multitenant Architecture, Cloud Replication & AI Engine",
      metrics: [
        { label: "Active Tenant SaaS", val: "14 Company", change: "100% Uptime", icon: Building2 },
        { label: "Database Replication Rate", val: "99.98%", change: "PostgreSQL & Supabase", icon: ShieldCheck },
        { label: "AI Decision Processing", val: "4,820 / Day", change: "Gemini 2.0 Flash", icon: Zap },
        { label: "Mobile App Installs", val: "1,180 User", change: "Universal Android", icon: Tv }
      ]
    }
  ];

  return (
    <div 
      onMouseMove={handleMouseMove}
      className="fixed inset-0 bg-[#030712] text-white flex flex-col justify-between p-6 sm:p-10 select-none overflow-hidden font-sans z-[9999]"
    >
      {/* Laser Pointer Glow Dot */}
      {showLaser && laserPos && (
        <div 
          className="pointer-events-none fixed z-[10000] transition-all duration-75"
          style={{ left: `${laserPos.x}%`, top: `${laserPos.y}%` }}
        >
          <div className="w-6 h-6 -ml-3 -mt-3 bg-red-500 rounded-full animate-ping opacity-75"></div>
          <div className="w-4 h-4 -ml-2 -mt-2 bg-red-600 rounded-full shadow-[0_0_20px_#ef4444] border-2 border-white"></div>
        </div>
      )}

      {/* Freeze Frame Overlay Banner */}
      {isPaused && (
        <div className="absolute inset-0 bg-black/75 backdrop-blur-md z-[9998] flex flex-col items-center justify-center gap-4 animate-fade-in">
          <div className="p-4 rounded-full bg-amber-500/20 border-2 border-amber-400 text-amber-300 animate-pulse">
            <Pause className="w-12 h-12" />
          </div>
          <div className="text-center space-y-1">
            <h2 className="text-2xl sm:text-3xl font-black tracking-wider uppercase text-amber-400">
              FREEZE FRAME / PRESENTASI DIJEDA
            </h2>
            <p className="text-slate-300 font-mono text-sm">
              Layar TV dikunci oleh Presenter. Tekan 'Lanjutkan Screen' untuk memutakhirkan tampilan.
            </p>
          </div>
        </div>
      )}

      {/* Broadcast Header Bar */}
      <header className="flex items-center justify-between border-b border-sky-500/30 pb-4 bg-slate-950/60 p-4 rounded-2xl border backdrop-blur-md">
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 rounded-xl bg-gradient-to-tr from-sky-500 via-blue-600 to-indigo-600 flex items-center justify-center text-white shadow-lg shadow-sky-500/40">
            <Tv className="w-6 h-6 animate-pulse" />
          </div>
          <div>
            <div className="flex items-center gap-2">
              <span className="px-2.5 py-0.5 bg-emerald-500 text-slate-950 font-black text-[10px] uppercase tracking-widest rounded-md flex items-center gap-1 shadow-sm">
                <Radio className="w-3 h-3 animate-ping" />
                LIVE 4K PRESENTATION
              </span>
              <span className="px-2 py-0.5 bg-sky-500/20 text-sky-300 border border-sky-400/40 text-[10px] font-mono font-bold uppercase rounded">
                MODE: {castMode.toUpperCase()}
              </span>
            </div>
            <h1 className="text-lg sm:text-2xl font-black text-white tracking-tight mt-0.5">
              PT MEDIA EKOSISTEM DIGITAL APLIKASI NASIONAL
            </h1>
          </div>
        </div>

        {/* Live Controls & Clock */}
        <div className="flex items-center gap-4">
          <div className="text-right font-mono hidden md:block">
            <div className="text-xl sm:text-2xl font-black text-sky-400 tracking-wider">
              {currentTime}
            </div>
            <div className="text-[11px] text-slate-400 uppercase">
              {currentDate}
            </div>
          </div>

          <div className="flex items-center gap-2 border-l border-slate-800 pl-4">
            <button
              onClick={() => setAudioMuted(!audioMuted)}
              className="p-2.5 bg-slate-900 hover:bg-slate-800 text-slate-300 rounded-xl border border-slate-700 transition-colors"
              title={audioMuted ? "Unmute Audio TV" : "Mute Audio TV"}
            >
              {audioMuted ? <VolumeX className="w-5 h-5 text-rose-400" /> : <Volume2 className="w-5 h-5 text-sky-400" />}
            </button>

            <button
              onClick={toggleFullscreenMode}
              className="p-2.5 bg-sky-500 hover:bg-sky-400 text-slate-950 font-bold rounded-xl transition-all shadow-md shadow-sky-500/30"
              title="Toggle Fullscreen TV"
            >
              <Maximize2 className="w-5 h-5" />
            </button>

            {onCloseWindow && (
              <button
                onClick={onCloseWindow}
                className="p-2.5 bg-rose-600 hover:bg-rose-500 text-white rounded-xl transition-colors"
                title="Tutup Jendela TV"
              >
                <X className="w-5 h-5" />
              </button>
            )}
          </div>
        </div>
      </header>

      {/* Main Screen Body View based on Cast Mode */}
      <main className="my-auto py-6 space-y-6">

        {/* MODE 1: FULL DASHBOARD / EXECUTIVE SUMMARY */}
        {castMode === "full" && (
          <div className="space-y-6 animate-fade-in">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-2xl sm:text-3xl font-black text-white uppercase tracking-tight flex items-center gap-2">
                  <BarChart3 className="w-8 h-8 text-sky-400" />
                  Dashboard Eksekutif & Real-Time Monitoring
                </h2>
                <p className="text-sm text-slate-400 mt-1">
                  Sinkronisasi Data Otomatis via Supabase Realtime & Firestore Cluster
                </p>
              </div>

              <div className="px-4 py-2 bg-slate-900/90 border border-sky-500/40 rounded-xl text-xs font-mono text-sky-300 flex items-center gap-2">
                <ShieldCheck className="w-4 h-4 text-emerald-400" />
                SLA System Uptime: <span className="font-black text-white">99.99%</span>
              </div>
            </div>

            {/* KPI Cards Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
              {[
                { title: "Total Pegawai Active", value: "1,248", subtitle: "98.4% Hadir Hari Ini", color: "from-sky-500/20 to-blue-600/20", border: "border-sky-500/50", text: "text-sky-400" },
                { title: "Target RKAP Pendapatan", value: "Rp 148.5 M", subtitle: "Realisasi 104% Target Q3", color: "from-emerald-500/20 to-teal-600/20", border: "border-emerald-500/50", text: "text-emerald-400" },
                { title: "Approval Workflow SLA", value: "18 Request", subtitle: "Rata-rata Respon 1.2 Jam", color: "from-amber-500/20 to-orange-600/20", border: "border-amber-500/50", text: "text-amber-400" },
                { title: "SaaS Multi-tenant Node", value: "14 Tenant", subtitle: "PostgreSQL & Redis Active", color: "from-purple-500/20 to-indigo-600/20", border: "border-purple-500/50", text: "text-purple-400" }
              ].map((card, idx) => (
                <div key={idx} className={`p-6 rounded-2xl bg-gradient-to-br ${card.color} border-2 ${card.border} backdrop-blur-md space-y-2 shadow-xl`}>
                  <div className="text-xs uppercase tracking-wider font-bold text-slate-300 font-mono">
                    {card.title}
                  </div>
                  <div className={`text-3xl sm:text-4xl font-black ${card.text}`}>
                    {card.value}
                  </div>
                  <div className="text-xs font-mono text-slate-300">
                    {card.subtitle}
                  </div>
                </div>
              ))}
            </div>

            {/* Visual Simulated Live Chart Bar */}
            <div className="bg-slate-950/80 border-2 border-sky-500/40 p-6 rounded-2xl space-y-4 shadow-2xl">
              <div className="flex items-center justify-between">
                <h3 className="text-base font-bold text-white uppercase tracking-wider font-mono flex items-center gap-2">
                  <Activity className="w-5 h-5 text-sky-400" />
                  Grafik Tren Kinerja Keuangan & Presensi Bulanan (2026)
                </h3>
                <span className="text-xs text-slate-400 font-mono">Data Terverifikasi SAP & Firestore</span>
              </div>

              <div className="h-44 flex items-end justify-between gap-3 pt-6 px-4 border-b border-slate-800">
                {[
                  { month: "Jan", val: 65 },
                  { month: "Feb", val: 78 },
                  { month: "Mar", val: 82 },
                  { month: "Apr", val: 70 },
                  { month: "Mei", val: 88 },
                  { month: "Jun", val: 94 },
                  { month: "Jul", val: 90 },
                  { month: "Agt", val: 98 }
                ].map((item, i) => (
                  <div key={i} className="flex-1 flex flex-col items-center gap-2 h-full justify-end">
                    <span className="text-[10px] font-mono text-sky-300 font-bold">{item.val}%</span>
                    <div 
                      className="w-full bg-gradient-to-t from-sky-600 to-blue-400 rounded-t-lg transition-all duration-1000 shadow-lg shadow-sky-500/30"
                      style={{ height: `${item.val}%` }}
                    ></div>
                    <span className="text-xs font-mono text-slate-400 uppercase">{item.month}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* MODE 2: MODE RAPAT DIREKSI (PRESENTATION SLIDE MODE) */}
        {castMode === "presentation" && (
          <div className="space-y-6 animate-fade-in max-w-5xl mx-auto w-full">
            <div className="bg-gradient-to-r from-slate-900 via-sky-950 to-slate-900 border-2 border-sky-400 p-8 sm:p-12 rounded-3xl space-y-6 shadow-2xl relative overflow-hidden">
              <div className="flex items-center justify-between border-b border-sky-800/50 pb-4">
                <span className="px-3 py-1 bg-sky-500/20 text-sky-300 border border-sky-400/40 text-xs font-mono font-bold uppercase rounded-lg">
                  SLIDE {activeSlide + 1} DARI {SLIDES.length}
                </span>
                <span className="text-xs font-mono text-slate-400">RAPAT DIREKSI & DEWAN KOMISARIS</span>
              </div>

              <div className="space-y-2">
                <h2 className="text-2xl sm:text-4xl font-black text-white tracking-tight leading-tight">
                  {SLIDES[activeSlide].title}
                </h2>
                <p className="text-base text-sky-300 font-mono">
                  {SLIDES[activeSlide].subtitle}
                </p>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-4">
                {SLIDES[activeSlide].metrics.map((m, idx) => {
                  const IconComp = m.icon;
                  return (
                    <div key={idx} className="bg-slate-950/80 border border-sky-500/30 p-5 rounded-2xl flex items-center justify-between">
                      <div className="space-y-1">
                        <div className="text-xs text-slate-400 font-mono uppercase">{m.label}</div>
                        <div className="text-2xl font-black text-white">{m.val}</div>
                        <div className="text-xs text-emerald-400 font-mono font-bold">{m.change}</div>
                      </div>
                      <div className="w-12 h-12 rounded-xl bg-sky-500/20 border border-sky-400/30 flex items-center justify-center text-sky-300">
                        <IconComp className="w-6 h-6" />
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Slide Navigation Buttons */}
              <div className="flex items-center justify-between pt-6 border-t border-sky-800/50">
                <button
                  onClick={() => setActiveSlide(prev => Math.max(0, prev - 1))}
                  disabled={activeSlide === 0}
                  className="px-5 py-2.5 bg-slate-900 hover:bg-slate-800 disabled:opacity-40 text-white font-bold text-xs uppercase rounded-xl border border-slate-700 flex items-center gap-2 cursor-pointer"
                >
                  <ChevronLeft className="w-4 h-4" /> Slide Sebelumnya
                </button>

                <div className="flex items-center gap-2">
                  {SLIDES.map((_, idx) => (
                    <button
                      key={idx}
                      onClick={() => setActiveSlide(idx)}
                      className={`w-3 h-3 rounded-full transition-all ${activeSlide === idx ? "bg-sky-400 scale-125" : "bg-slate-700"}`}
                    ></button>
                  ))}
                </div>

                <button
                  onClick={() => setActiveSlide(prev => Math.min(SLIDES.length - 1, prev + 1))}
                  disabled={activeSlide === SLIDES.length - 1}
                  className="px-5 py-2.5 bg-sky-500 hover:bg-sky-400 disabled:opacity-40 text-slate-950 font-black text-xs uppercase rounded-xl flex items-center gap-2 cursor-pointer shadow-lg shadow-sky-500/30"
                >
                  Slide Selanjutnya <ChevronRight className="w-4 h-4" />
                </button>
              </div>
            </div>
          </div>
        )}

        {/* MODE 3: DASHBOARD STATISTIK & KPI LIVE */}
        {castMode === "dashboard" && (
          <div className="space-y-6 animate-fade-in">
            <div className="bg-slate-950/90 border-2 border-purple-500/50 p-6 rounded-3xl space-y-6">
              <div className="flex items-center justify-between border-b border-purple-500/30 pb-4">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl bg-purple-500/20 text-purple-300 border border-purple-400/40 flex items-center justify-center">
                    <Activity className="w-5 h-5 animate-pulse" />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold text-white uppercase tracking-wider">
                      Live Telemetry & Server Metrics Monitor
                    </h2>
                    <p className="text-xs text-slate-400 font-mono">
                      Monitoring Infra Cloud Run, Supabase PostgreSQL, & Redis Caching
                    </p>
                  </div>
                </div>

                <span className="px-3 py-1 bg-emerald-500/20 border border-emerald-500/40 text-emerald-300 text-xs font-mono font-bold rounded-lg">
                  HEALTHY (LATENCY 12ms)
                </span>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div className="p-5 bg-slate-900 rounded-2xl border border-slate-800 space-y-2">
                  <span className="text-xs text-slate-400 uppercase font-mono">CPU Usage Cluster</span>
                  <div className="text-3xl font-black text-purple-400">18.4%</div>
                  <div className="w-full bg-slate-800 rounded-full h-2">
                    <div className="bg-purple-500 h-2 rounded-full w-[18%]"></div>
                  </div>
                </div>

                <div className="p-5 bg-slate-900 rounded-2xl border border-slate-800 space-y-2">
                  <span className="text-xs text-slate-400 uppercase font-mono">RAM Allocated</span>
                  <div className="text-3xl font-black text-sky-400">2.1 GB / 8 GB</div>
                  <div className="w-full bg-slate-800 rounded-full h-2">
                    <div className="bg-sky-500 h-2 rounded-full w-[26%]"></div>
                  </div>
                </div>

                <div className="p-5 bg-slate-900 rounded-2xl border border-slate-800 space-y-2">
                  <span className="text-xs text-slate-400 uppercase font-mono">Active WebSockets</span>
                  <div className="text-3xl font-black text-emerald-400">428 Live Conn</div>
                  <div className="w-full bg-slate-800 rounded-full h-2">
                    <div className="bg-emerald-500 h-2 rounded-full w-[85%]"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* MODE 4: LAPORAN KEUANGAN & RKAP */}
        {castMode === "rkap" && (
          <div className="space-y-6 animate-fade-in">
            <div className="bg-slate-950/90 border-2 border-emerald-500/50 p-6 rounded-3xl space-y-6">
              <div className="flex items-center justify-between border-b border-emerald-500/30 pb-4">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl bg-emerald-500/20 text-emerald-300 border border-emerald-400/40 flex items-center justify-center">
                    <DollarSign className="w-5 h-5" />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold text-white uppercase tracking-wider">
                      Ringkasan Keuangan & RKAP PT MEDIAN
                    </h2>
                    <p className="text-xs text-slate-400 font-mono">
                      Diintegrasikan dengan SAP General Ledger & Modul Pembayaran Kas
                    </p>
                  </div>
                </div>

                <span className="px-3 py-1 bg-emerald-500 text-slate-950 font-extrabold text-xs font-mono rounded-lg uppercase">
                  Q3 AUDITED REPORT
                </span>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="p-6 bg-slate-900 border border-emerald-500/30 rounded-2xl space-y-3">
                  <span className="text-xs text-emerald-400 font-mono uppercase font-bold">Total Pemasukan (Revenue)</span>
                  <div className="text-3xl font-black text-white">Rp 148,500,000,000</div>
                  <p className="text-xs text-slate-400 font-mono">Pencapaian 104.2% dari Target RKAP Q3 2026</p>
                </div>

                <div className="p-6 bg-slate-900 border border-slate-800 rounded-2xl space-y-3">
                  <span className="text-xs text-rose-400 font-mono uppercase font-bold">Total Pengeluaran (Opex & Capex)</span>
                  <div className="text-3xl font-black text-white">Rp 30,600,000,000</div>
                  <p className="text-xs text-slate-400 font-mono">Efisiensi Biaya Operasional Sebesar 6.4%</p>
                </div>
              </div>
            </div>
          </div>
        )}

      </main>

      {/* Broadcast Footer Info */}
      <footer className="border-t border-sky-500/30 pt-4 bg-slate-950/80 p-4 rounded-2xl border flex flex-col sm:flex-row items-center justify-between gap-3 text-xs font-mono text-slate-400">
        <div className="flex items-center gap-3">
          <span className="flex items-center gap-1.5 text-emerald-400 font-bold">
            <CheckCircle2 className="w-4 h-4" /> Enkripsi WPA3 Enterprise
          </span>
          <span>•</span>
          <span>Device ID: <code className="text-sky-300">TV-PROJ-4K-01</code></span>
        </div>

        <div className="flex items-center gap-2">
          <span>Sistem Presentasi Wireless PT MEDIAN © 2026</span>
        </div>
      </footer>
    </div>
  );
}
