'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { 
  Bot, 
  ShoppingBag, 
  CreditCard, 
  MapPin, 
  Sparkles, 
  CheckCircle2, 
  ArrowRight, 
  ChevronLeft, 
  ChevronRight, 
  X, 
} from 'lucide-react';
import { ONBOARDING_STEPS, useOnboarding } from '@/lib/useOnboarding';

interface SystemTourModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export default function SystemTourModal({ isOpen, onClose }: SystemTourModalProps) {
  const [currentSlide, setCurrentSlide] = useState(0);
  const router = useRouter();
  const { completedSteps, toggleStep } = useOnboarding();

  if (!isOpen) return null;

  const slides = [
    {
      badge: 'System Overview • Slide 1 of 5',
      title: 'Automated WhatsApp Sales Engine',
      subtitle: 'Transform your WhatsApp account into an AI-powered 24/7 sales machine.',
      icon: Bot,
      accentColor: 'from-emerald-500/20 to-teal-500/10 border-emerald-500/30',
      iconColor: 'text-emerald-400',
      highlights: [
        {
          title: '24/7 Customer Assistant',
          desc: 'Replies instantly to product inquiries, checks stock availability, and guides clients to checkout.',
        },
        {
          title: 'Interactive WhatsApp Messages',
          desc: 'Send interactive catalog buttons, product lists, and instant quick-reply buttons.',
        },
        {
          title: 'Zero Technical Overhead',
          desc: 'Connect your WhatsApp Business API once and let orders be handled automatically.',
        },
      ],
    },
    {
      badge: 'Catalog Sync • Slide 2 of 5',
      title: 'Meta Catalog & Product Sync',
      subtitle: 'Keep your stock, prices, and catalog updated across WhatsApp and web stores.',
      icon: ShoppingBag,
      accentColor: 'from-teal-500/20 to-emerald-500/10 border-teal-500/30',
      iconColor: 'text-teal-400',
      highlights: [
        {
          title: 'Meta Commerce Integration',
          desc: 'Automatically sync product images, pricing, and variants to your Meta WhatsApp catalog.',
        },
        {
          title: 'WooCommerce & CSV Import',
          desc: 'Sync existing e-commerce items or import products in bulk via CSV spreadsheets.',
        },
        {
          title: 'Real-Time Inventory Control',
          desc: 'Prevent overselling with automatic stock reservation as orders are created in chat.',
        },
      ],
    },
    {
      badge: 'Payments • Slide 3 of 5',
      title: 'Instant EcoCash, Paynow & Card Payments',
      subtitle: 'Collect customer payments securely directly inside WhatsApp messages.',
      icon: CreditCard,
      accentColor: 'from-purple-500/20 to-pink-500/10 border-purple-500/30',
      iconColor: 'text-purple-400',
      highlights: [
        {
          title: 'Local & Global Payment Gateways',
          desc: 'Accept EcoCash, Paynow, Visa/Mastercard, and PesePay seamlessly.',
        },
        {
          title: 'Instant Automated Receipts',
          desc: 'When payment clears, customer receives an instant WhatsApp confirmation receipt.',
        },
        {
          title: 'Direct Payout Routing',
          desc: 'Funds settle directly to your business wallet or registered merchant bank account.',
        },
      ],
    },
    {
      badge: 'Logistics • Slide 4 of 5',
      title: 'Live GPS Delivery Tracking',
      subtitle: 'Dispatch orders and send real-time driver ETA map tracking links to clients.',
      icon: MapPin,
      accentColor: 'from-amber-500/20 to-orange-500/10 border-amber-500/30',
      iconColor: 'text-amber-400',
      highlights: [
        {
          title: 'Interactive Logistics Dashboard',
          desc: 'Assign drivers, monitor active delivery routes, and update fulfillment status.',
        },
        {
          title: 'Live Customer ETA Map',
          desc: 'Clients receive a custom tracking web link showing real-time driver coordinates on Google Maps.',
        },
        {
          title: 'Automated Status Alerts',
          desc: 'WhatsApp notifications trigger automatically when orders are dispatched or arriving.',
        },
      ],
    },
    {
      badge: 'Roadmap • Slide 5 of 5',
      title: 'Your 5-Step Launch Checklist',
      subtitle: 'Complete these quick steps to launch your fully automated WhatsApp Commerce Hub.',
      icon: CheckCircle2,
      accentColor: 'from-emerald-500/20 to-emerald-600/10 border-emerald-500/40',
      iconColor: 'text-emerald-400',
      isChecklistSlide: true,
      highlights: [],
    },
  ];

  const slide = slides[currentSlide];
  const IconComponent = slide.icon;

  const nextSlide = () => {
    if (currentSlide < slides.length - 1) {
      setCurrentSlide(currentSlide + 1);
    } else {
      onClose();
    }
  };

  const prevSlide = () => {
    if (currentSlide > 0) {
      setCurrentSlide(currentSlide - 1);
    }
  };

  const handleStepAction = (href: string) => {
    onClose();
    router.push(href);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/75 backdrop-blur-md animate-fade-in font-sans">
      <div className="relative w-full max-w-3xl glass-panel bg-[var(--panel-bg)] border border-[var(--panel-border)] rounded-3xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
        {/* Header */}
        <div className="p-5 md:p-6 border-b border-white/10 flex items-center justify-between bg-black/20">
          <div className="flex items-center gap-3">
            <Sparkles className="w-6 h-6 text-emerald-400 shrink-0" />
            <div>
              <span className="text-[10px] font-black uppercase tracking-widest text-emerald-400">
                {slide.badge}
              </span>
              <h2 className="text-base font-extrabold text-[var(--text-title)]">
                System Tour & Interactive Learning Guide
              </h2>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-xl text-gray-400 hover:text-white hover:bg-white/10 transition-colors cursor-pointer"
            aria-label="Close tour modal"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Slide Body */}
        <div className="flex-1 p-6 md:p-8 overflow-y-auto space-y-6 scrollbar-thin">
          {/* Main Slide Title & Icon Banner */}
          <div className={`p-6 rounded-2xl bg-gradient-to-r ${slide.accentColor} border flex flex-col md:flex-row items-start md:items-center gap-4`}>
            <IconComponent className={`w-8 h-8 ${slide.iconColor} shrink-0`} />
            <div className="space-y-1">
              <h3 className="text-xl font-black text-[var(--text-title)]">{slide.title}</h3>
              <p className="text-xs text-[var(--text-muted)] leading-relaxed font-medium">
                {slide.subtitle}
              </p>
            </div>
          </div>

          {/* Regular Feature Highlights */}
          {!slide.isChecklistSlide && (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {slide.highlights.map((item, idx) => (
                <div 
                  key={idx} 
                  className="p-4 rounded-2xl bg-black/20 dark:bg-white/5 border border-white/5 space-y-2 hover:border-emerald-500/30 transition-all"
                >
                  <div className="flex items-center gap-2">
                    <span className="w-6 h-6 rounded-full bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs font-bold flex items-center justify-center shrink-0">
                      {idx + 1}
                    </span>
                    <h4 className="text-xs font-bold text-[var(--text-title)] leading-snug">{item.title}</h4>
                  </div>
                  <p className="text-[11px] text-[var(--text-muted)] leading-relaxed">
                    {item.desc}
                  </p>
                </div>
              ))}
            </div>
          )}

          {/* Final Slide Interactive Checklist */}
          {slide.isChecklistSlide && (
            <div className="space-y-3">
              <p className="text-xs text-[var(--text-muted)] font-semibold">
                Click any step below to launch setup or mark it as completed:
              </p>
              <div className="space-y-2.5">
                {ONBOARDING_STEPS.map((step) => {
                  const isDone = completedSteps[step.id];
                  return (
                    <div
                      key={step.id}
                      className={`p-3.5 rounded-2xl border transition-all flex items-center justify-between gap-3 ${
                        isDone 
                          ? 'bg-emerald-500/10 border-emerald-500/30' 
                          : 'bg-black/20 dark:bg-white/5 border-white/10 hover:border-emerald-500/20'
                      }`}
                    >
                      <div className="flex items-center gap-3 min-w-0">
                        <button
                          onClick={() => toggleStep(step.id)}
                          className={`w-6 h-6 rounded-lg flex items-center justify-center shrink-0 transition-colors ${
                            isDone 
                              ? 'bg-emerald-500 text-white' 
                              : 'border border-white/20 text-transparent hover:border-emerald-400'
                          }`}
                        >
                          <CheckCircle2 className="w-4 h-4" />
                        </button>
                        <div className="truncate">
                          <span className="text-[10px] font-bold uppercase tracking-wider text-emerald-400 mr-2">
                            {step.badge}
                          </span>
                          <span className={`text-xs font-bold ${isDone ? 'line-through text-gray-400' : 'text-[var(--text-title)]'}`}>
                            {step.title}
                          </span>
                          <p className="text-[10px] text-[var(--text-muted)] truncate">{step.shortDesc}</p>
                        </div>
                      </div>

                      <button
                        onClick={() => handleStepAction(step.href)}
                        className="px-3 py-1.5 rounded-xl bg-[#008069] text-white hover:bg-[#006e5a] text-[11px] font-bold flex items-center gap-1 shrink-0 cursor-pointer"
                      >
                        <span>{step.actionText}</span>
                        <ArrowRight className="w-3 h-3" />
                      </button>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>

        {/* Footer Navigation Bar */}
        <div className="p-5 border-t border-white/10 bg-black/30 flex items-center justify-between gap-4">
          {/* Slide Indicator Dots */}
          <div className="flex items-center gap-2">
            {slides.map((_, idx) => (
              <button
                key={idx}
                onClick={() => setCurrentSlide(idx)}
                className={`h-2 rounded-full transition-all cursor-pointer ${
                  currentSlide === idx 
                    ? 'w-6 bg-emerald-500' 
                    : 'w-2 bg-white/20 hover:bg-white/40'
                }`}
                aria-label={`Go to slide ${idx + 1}`}
              />
            ))}
          </div>

          {/* Navigation Buttons */}
          <div className="flex items-center gap-2">
            {currentSlide > 0 && (
              <button
                onClick={prevSlide}
                className="px-4 py-2 rounded-xl bg-black/20 dark:bg-white/5 border border-white/10 hover:bg-white/10 text-xs font-bold text-[var(--text-title)] flex items-center gap-1 transition-all cursor-pointer"
              >
                <ChevronLeft className="w-4 h-4" />
                <span>Previous</span>
              </button>
            )}

            <button
              onClick={nextSlide}
              className="px-5 py-2 rounded-xl bg-[#008069] hover:bg-[#006e5a] text-white text-xs font-black uppercase tracking-wider flex items-center gap-1.5 transition-all shadow-md cursor-pointer"
            >
              <span>{currentSlide === slides.length - 1 ? 'Finish Tour' : 'Next Step'}</span>
              {currentSlide === slides.length - 1 ? (
                <CheckCircle2 className="w-4 h-4" />
              ) : (
                <ChevronRight className="w-4 h-4" />
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
