'use client';

import { useState, useEffect, useRef } from 'react';
import { 
  Sparkles, 
  ChevronRight, 
  ChevronLeft, 
  X, 
  Zap, 
  TrendingUp, 
  Activity, 
  BarChart3, 
  Trophy, 
  PieChart, 
  Receipt,
  ArrowRight
} from 'lucide-react';
import { cn } from '@/lib/utils';

// Steps list mapping target IDs on the page
interface Step {
  targetId: string;
  title: string;
  description: string;
  iconName: string;
}

const steps: Step[] = [
  {
    targetId: 'tour-header',
    title: 'Aksi Cepat & Navigasi Utama',
    description: 'Di sini Anda dapat melihat status koneksi sistem, memperbarui data secara manual, serta mengakses tombol cepat untuk membuat Transaksi Baru, melihat Laporan, atau membuka Riwayat.',
    iconName: 'Zap',
  },
  {
    targetId: 'tour-stats',
    title: 'Statistik Utama Toko',
    description: 'Pantau Pendapatan Hari Ini, Pesanan Hari Ini, Pendapatan Bulanan, dan Laba Bersih secara real-time. Bagian ini membantu Anda memonitor performa keuangan toko Anda dengan instan.',
    iconName: 'TrendingUp',
  },
  {
    targetId: 'tour-metrics',
    title: 'Metrik Operasional Harian',
    description: 'Menampilkan detail operasional penting: Rata-rata Nilai Order, Laba bersih Hari Ini, jumlah Produk Aktif, dan Peringatan Stok Rendah yang berkedip merah jika ada produk yang hampir habis.',
    iconName: 'Activity',
  },
  {
    targetId: 'tour-chart',
    title: 'Grafik Tren Penjualan',
    description: 'Visualisasi grafik interaktif tren omset harian dan jumlah transaksi dalam 30 hari terakhir. Arahkan kursor Anda ke grafik untuk melihat detail nominal pada tanggal tertentu.',
    iconName: 'BarChart3',
  },
  {
    targetId: 'tour-analytics',
    title: 'Produk Terlaris & Jam Ramai',
    description: 'Ketahui 5 produk terlaris Anda beserta grafik jam-jam sibuk transaksi. Data ini sangat berharga untuk merencanakan stok barang terpopuler dan mengatur jadwal kerja staf kasir.',
    iconName: 'Trophy',
  },
  {
    targetId: 'tour-distribution',
    title: 'Kategori & Metode Pembayaran',
    description: 'Analisis kontribusi omset per kategori produk (dalam grafik donat) serta metode pembayaran terpopuler (QRIS, Tunai, atau Transfer) yang paling sering dipilih oleh pelanggan Anda.',
    iconName: 'PieChart',
  },
  {
    targetId: 'tour-orders',
    title: 'Kelola Pesanan Terbaru',
    description: 'Daftar transaksi kasir terbaru lengkap dengan nama pelanggan, waktu, status pembayaran, dan total belanja. Anda dapat memfilter, mencari pesanan, atau mencetak struk secara langsung.',
    iconName: 'Receipt',
  },
];

interface DashboardTourProps {
  userId?: number;
}

export default function DashboardTour({ userId }: DashboardTourProps) {
  const [status, setStatus] = useState<'idle' | 'welcome' | 'touring' | 'completed'>('idle');
  const [currentStep, setCurrentStep] = useState(0);
  const [coords, setCoords] = useState<{ top: number; left: number; width: number; height: number } | null>(null);
  const [dialogPosition, setDialogPosition] = useState<{ top: number; left: number } | null>(null);
  const [isMobile, setIsMobile] = useState(false);
  const initializedRef = useRef(false);

  // Auto-start tour disabled — keep component for optional manual re-enable later
  const TOUR_ENABLED = false;

  // 1. Check if user has already seen the tour on mount
  useEffect(() => {
    if (!TOUR_ENABLED) return;
    if (!userId) return;

    const tourSeen = localStorage.getItem(`tutorial_seen_${userId}`);
    if (!tourSeen && status === 'idle') {
      setStatus('welcome');
    }
  }, [userId, status]);

  // 2. Handle screen size check
  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth < 768);
    };
    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 3. Track spotlight coordinates and scroll handling
  useEffect(() => {
    if (status !== 'touring') {
      setCoords(null);
      setDialogPosition(null);
      return;
    }

    const step = steps[currentStep];
    if (!step) return;

    const updateCoords = () => {
      const element = document.getElementById(step.targetId);
      if (element) {
        const rect = element.getBoundingClientRect();
        
        // Only spotlight if element has actual rendered content (height > 30)
        if (rect.height > 30) {
          const top = rect.top + window.scrollY;
          const left = rect.left + window.scrollX;
          const width = rect.width;
          const height = rect.height;

          setCoords({ top, left, width, height });

          if (window.innerWidth >= 768) {
            const dialogWidth = 380;
            const dialogHeight = 260;
            const gap = 20;

            const screenHeight = window.innerHeight;
            const screenWidth = window.innerWidth;
            
            let dialogTop = top + height + gap;
            const spaceAbove = rect.top;
            const spaceBelow = screenHeight - rect.bottom;

            if (spaceAbove > spaceBelow && spaceAbove > dialogHeight + gap) {
              dialogTop = top - dialogHeight - gap;
            } else if (spaceBelow >= dialogHeight + gap) {
              dialogTop = top + height + gap;
            } else {
              if (spaceAbove > spaceBelow) {
                dialogTop = top - dialogHeight - gap;
              } else {
                dialogTop = top + height + gap;
              }
            }

            // Clamp vertical position relative to viewport boundaries to prevent cut-off
            const viewportTop = dialogTop - window.scrollY;
            const minViewportTop = 20;
            const maxViewportTop = screenHeight - dialogHeight - 20;
            const clampedViewportTop = Math.max(minViewportTop, Math.min(viewportTop, maxViewportTop));
            dialogTop = clampedViewportTop + window.scrollY;

            let dialogLeft = left + (width - dialogWidth) / 2;
            const margin = 20;
            if (dialogLeft < margin) {
              dialogLeft = margin;
            } else if (dialogLeft + dialogWidth > screenWidth - margin) {
              dialogLeft = screenWidth - dialogWidth - margin;
            }

            setDialogPosition({ top: dialogTop, left: dialogLeft });
          } else {
            setDialogPosition(null);
          }
        } else {
          // Element is empty/not rendered (e.g. empty stats/data)
          setCoords(null);
          if (window.innerWidth >= 768) {
            setDialogPosition({
              top: window.scrollY + (window.innerHeight - 260) / 2,
              left: (window.innerWidth - 380) / 2,
            });
          } else {
            setDialogPosition(null);
          }
        }
      } else {
        // Element not found
        setCoords(null);
        if (window.innerWidth >= 768) {
          setDialogPosition({
            top: window.scrollY + (window.innerHeight - 260) / 2,
            left: (window.innerWidth - 380) / 2,
          });
        } else {
          setDialogPosition(null);
        }
      }
    };

    // Scroll active element to center
    const element = document.getElementById(step.targetId);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }

    // Delay coords update slightly to let scroll finish
    const timer = setTimeout(updateCoords, 400);

    window.addEventListener('resize', updateCoords);
    window.addEventListener('scroll', updateCoords);

    return () => {
      clearTimeout(timer);
      window.removeEventListener('resize', updateCoords);
      window.removeEventListener('scroll', updateCoords);
    };
  }, [currentStep, status]);

  const handleStartTour = () => {
    setStatus('touring');
    setCurrentStep(0);
  };

  const handleNext = () => {
    if (currentStep < steps.length - 1) {
      setCurrentStep((prev) => prev + 1);
    } else {
      handleComplete();
    }
  };

  const handlePrev = () => {
    if (currentStep > 0) {
      setCurrentStep((prev) => prev - 1);
    }
  };

  const handleSkip = () => {
    handleComplete();
  };

  const handleComplete = () => {
    setStatus('completed');
    if (userId) {
      localStorage.setItem(`tutorial_seen_${userId}`, 'true');
    }
  };

  // Helper to render icon based on step
  const renderStepIcon = (name: string) => {
    const iconClass = "h-6 w-6 text-amber-500 animate-float";
    switch (name) {
      case 'Zap': return <Zap className={iconClass} />;
      case 'TrendingUp': return <TrendingUp className={iconClass} />;
      case 'Activity': return <Activity className={iconClass} />;
      case 'BarChart3': return <BarChart3 className={iconClass} />;
      case 'Trophy': return <Trophy className={iconClass} />;
      case 'PieChart': return <PieChart className={iconClass} />;
      case 'Receipt': return <Receipt className={iconClass} />;
      default: return <Sparkles className={iconClass} />;
    }
  };

  if (status === 'idle' || status === 'completed') return null;

  return (
    <>
      {/* ── 1. WELCOME MODAL OVERLAY ── */}
      {status === 'welcome' && (
        <div className="fixed inset-0 z-[10000] flex items-center justify-center p-4">
          {/* Blur background backdrop */}
          <div className="fixed inset-0 bg-brand-900/60 backdrop-blur-md animate-fade-in" />
          
          {/* Welcome card */}
          <div 
            className="relative w-full max-w-lg bg-white rounded-3xl p-8 shadow-elevated border border-brand-100/50 animate-scale-in text-center space-y-6"
            style={{ boxShadow: 'var(--shadow-elevated)' }}
          >
            <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-600 to-indigo-600 shadow-md">
              <Sparkles className="h-8 w-8 text-amber-300 animate-pulse-soft" />
            </div>

            <div className="space-y-2">
              <h2 className="text-2xl font-extrabold text-brand-900 tracking-tight font-heading">
                Selamat Datang di LasminiShop! 🚀
              </h2>
              <p className="text-sm text-slate-500 font-medium max-w-sm mx-auto leading-relaxed">
                Selamat datang di kasir LasminiShop. Mari kenali area dasbor utama dalam 1 menit.
              </p>
            </div>

            {/* Features preview */}
            <div className="bg-brand-50/50 border border-brand-100 rounded-2xl p-4 text-left space-y-3">
              <div className="flex gap-3 items-start">
                <div className="h-2 w-2 rounded-full bg-brand-500 mt-1.5 shrink-0" />
                <p className="text-xs font-semibold text-brand-900">
                  Pantau omset, jumlah pesanan, dan laba bersih secara real-time.
                </p>
              </div>
              <div className="flex gap-3 items-start">
                <div className="h-2 w-2 rounded-full bg-brand-500 mt-1.5 shrink-0" />
                <p className="text-xs font-semibold text-brand-900">
                  Lihat tren per jam ramai dan produk terlaris untuk analisis stok.
                </p>
              </div>
              <div className="flex gap-3 items-start">
                <div className="h-2 w-2 rounded-full bg-brand-500 mt-1.5 shrink-0" />
                <p className="text-xs font-semibold text-brand-900">
                  Kelola transaksi masuk dan cetak struk kasir terbaru langsung.
                </p>
              </div>
            </div>

            <div className="flex flex-col sm:flex-row gap-3 pt-2">
              <button
                onClick={handleSkip}
                className="flex-1 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-700 font-bold py-3 text-sm cursor-pointer"
              >
                Lewati Tur
              </button>
              <button
                onClick={handleStartTour}
                className="flex-1 rounded-xl bg-gradient-to-r from-brand-600 to-brand-700 hover:from-brand-700 hover:to-brand-800 text-white font-bold py-3 text-sm shadow-md flex items-center justify-center gap-2 cursor-pointer"
              >
                <span>Mulai Tur</span>
                <ArrowRight className="h-4 w-4" />
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ── 2. ACTIVE TOUR: BACKDROP & SPOTLIGHT EFFECT ── */}
      {status === 'touring' && (
        <div className="fixed inset-0 z-[9990] pointer-events-none">
          {/* Solid backdrop if element is not rendered/empty */}
          {!coords && (
            <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-[1px] animate-fade-in pointer-events-auto" />
          )}

          {/* Spotlight Highlight Element */}
          {coords && (
            <div
              className="absolute z-[9991] border-2 border-amber-400 bg-transparent rounded-3xl transition-all duration-300 pointer-events-none animate-pulse-soft shadow-[0_0_15px_rgba(245,158,11,0.4)]"
              style={{
                top: coords.top - 8,
                left: coords.left - 8,
                width: coords.width + 16,
                height: coords.height + 16,
                boxShadow: '0 0 0 9999px rgba(15, 23, 42, 0.65), 0 0 20px rgba(245,158,11,0.4)',
              }}
            />
          )}

          {/* Block clicks overlay everywhere except interactive tutorial box */}
          <div className="fixed inset-0 pointer-events-auto bg-transparent z-[9992]" />

          {/* ── 3. TUTORIAL DIALOG TOOLTIP (DESKTOP OR MOBILE) ── */}
          <div
            className={cn(
              "z-[9995] pointer-events-auto bg-white/95 backdrop-blur-md border border-brand-100 shadow-elevated transition-all duration-300",
              isMobile 
                ? "fixed bottom-0 left-0 right-0 rounded-t-3xl p-6 border-t" 
                : "absolute rounded-2xl p-6 w-[380px] scale-100 shadow-2xl"
            )}
            style={
              !isMobile && dialogPosition
                ? { top: dialogPosition.top, left: dialogPosition.left }
                : undefined
            }
          >
            {/* Header / Step Progress */}
            <div className="flex items-center justify-between gap-4 mb-4">
              <div className="flex items-center gap-2.5">
                <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-amber-50 border border-amber-100">
                  {renderStepIcon(steps[currentStep].iconName)}
                </div>
                <div>
                  <h4 className="text-sm font-bold text-brand-900 font-heading">
                    {steps[currentStep].title}
                  </h4>
                  <p className="text-[10px] text-brand-500 font-bold uppercase tracking-wider">
                    Langkah {currentStep + 1} dari {steps.length}
                  </p>
                </div>
              </div>
              <button
                onClick={handleSkip}
                className="h-7 w-7 rounded-lg text-slate-400 hover:text-slate-700 hover:bg-slate-50 flex items-center justify-center cursor-pointer transition-colors"
                title="Tutup & Lewati Tur"
              >
                <X className="h-4 w-4" />
              </button>
            </div>

            {/* Description */}
            <p className="text-xs text-slate-600 font-medium leading-relaxed mb-5">
              {steps[currentStep].description}
            </p>

            {/* Footer Navigation Controls */}
            <div className="flex items-center justify-between gap-4 pt-3 border-t border-slate-100">
              <button
                onClick={handleSkip}
                className="text-[11px] font-bold text-slate-400 hover:text-slate-600 transition-colors cursor-pointer"
              >
                Lewati Tur
              </button>

              <div className="flex items-center gap-2">
                {currentStep > 0 && (
                  <button
                    onClick={handlePrev}
                    className="flex h-8 w-8 items-center justify-center rounded-lg border border-slate-200 text-slate-600 hover:bg-slate-50 transition-colors cursor-pointer"
                    title="Kembali"
                  >
                    <ChevronLeft className="h-4 w-4" />
                  </button>
                )}

                <button
                  onClick={handleNext}
                  className="flex items-center gap-1.5 rounded-lg bg-brand-900 hover:bg-brand-800 text-white font-bold px-3.5 py-1.5 text-xs shadow-md transition-colors cursor-pointer"
                >
                  <span>{currentStep === steps.length - 1 ? 'Selesai' : 'Lanjut'}</span>
                  <ChevronRight className="h-3.5 w-3.5" />
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
