'use client';

import React, { useState, useEffect } from 'react';
import { 
  X, 
  ChevronLeft, 
  ChevronRight, 
  CheckCircle2, 
  Lightbulb, 
} from 'lucide-react';
import Icons8Icon from '@/components/icons/Icons8Icon';
import { useOnboarding } from '@/lib/useOnboarding';
import { PAGE_TOURS_DATA } from './pageToursData';

type Icons8Name = 'overview' | '1sync' | 'shopping-cart' | 'customers' | 'prototype' | 'settings' | 'user' | 'delivery' | 'billing';

const ROUTE_ICONS8: Record<string, Icons8Name> = {
  '/dashboard': 'overview',
  '/dashboard/products': '1sync',
  '/dashboard/integrations': 'settings',
  '/dashboard/templates': 'prototype',
  '/dashboard/orders': 'shopping-cart',
  '/dashboard/deliveries': 'delivery',
  '/dashboard/customers': 'customers',
  '/dashboard/profile': 'user',
  '/dashboard/billing': 'billing',
};

interface PageWalkthroughModalProps {
  route: string;
  isOpen?: boolean;
  onClose?: () => void;
}

export default function PageWalkthroughModal({ route, isOpen, onClose }: PageWalkthroughModalProps) {
  const { hasSeenPageTour, markPageTourSeen, initialized } = useOnboarding();
  const [currentStep, setCurrentStep] = useState(0);
  const [modalVisible, setModalVisible] = useState(false);

  const tourData = PAGE_TOURS_DATA[route];
  const iconName: Icons8Name = ROUTE_ICONS8[route] || 'overview';

  useEffect(() => {
    if (!initialized || !tourData) return;

    if (typeof isOpen === 'boolean') {
      setModalVisible(isOpen);
    } else {
      // Auto-open on first time visit
      if (!hasSeenPageTour(route)) {
        setModalVisible(true);
      }
    }
  }, [initialized, route, isOpen, hasSeenPageTour, tourData]);

  if (!tourData || !modalVisible) return null;

  const steps = tourData.steps;
  const currentStepData = steps[currentStep] || steps[0];

  const handleClose = () => {
    markPageTourSeen(route);
    setModalVisible(false);
    if (onClose) onClose();
  };

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

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

  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-xl glass-panel bg-[var(--panel-bg)] border border-emerald-500/30 rounded-3xl shadow-2xl overflow-hidden flex flex-col">
        
        {/* Header */}
        <div className="p-5 border-b border-white/10 flex items-center justify-between bg-black/20">
          <div className="flex items-center gap-3">
            <Icons8Icon name={iconName} className="h-6 w-6 text-emerald-400 shrink-0" />
            <div>
              <span className="text-[10px] font-black uppercase tracking-widest text-emerald-400">
                {tourData.badge}
              </span>
              <h2 className="text-base font-black text-[var(--text-title)]">
                {tourData.title}
              </h2>
            </div>
          </div>
          <button
            onClick={handleClose}
            className="p-2 rounded-xl text-gray-400 hover:text-white hover:bg-white/10 transition-colors cursor-pointer"
            aria-label="Close walkthrough"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Slide Content */}
        <div className="p-6 md:p-8 space-y-6">
          <div className="space-y-1.5">
            <p className="text-xs text-[var(--text-muted)] font-medium">
              {tourData.subtitle}
            </p>
          </div>

          {/* Current Step Spotlight Card */}
          <div className="p-5 rounded-2xl bg-black/30 dark:bg-white/5 border border-white/10 space-y-3 relative overflow-hidden">
            <div className="flex items-center gap-3">
              <span className="w-7 h-7 rounded-full bg-emerald-500/20 border border-emerald-500/40 text-emerald-400 font-bold text-xs flex items-center justify-center shrink-0">
                {currentStep + 1}
              </span>
              <h3 className="text-sm font-extrabold text-[var(--text-title)]">
                {currentStepData.title}
              </h3>
            </div>

            <p className="text-xs text-[var(--text-muted)] leading-relaxed pl-10">
              {currentStepData.description}
            </p>

            <div className="pt-2 pl-10 flex items-start gap-2 text-xs text-emerald-600 dark:text-emerald-400 font-medium">
              <Lightbulb className="w-4 h-4 text-emerald-400 shrink-0 mt-0.5" />
              <span>{currentStepData.tip}</span>
            </div>
          </div>
        </div>

        {/* Footer Navigation */}
        <div className="p-5 border-t border-white/10 bg-black/30 flex items-center justify-between gap-4">
          {/* Step Indicator */}
          <div className="flex items-center gap-2">
            {steps.map((_, idx) => (
              <button
                key={idx}
                onClick={() => setCurrentStep(idx)}
                className={`h-2 rounded-full transition-all cursor-pointer ${
                  currentStep === idx 
                    ? 'w-6 bg-emerald-500' 
                    : 'w-2 bg-white/20 hover:bg-white/40'
                }`}
                aria-label={`Go to step ${idx + 1}`}
              />
            ))}
            <span className="text-[11px] text-[var(--text-muted)] font-mono ml-1 font-bold">
              {currentStep + 1}/{steps.length}
            </span>
          </div>

          {/* Buttons */}
          <div className="flex items-center gap-2">
            {currentStep > 0 && (
              <button
                onClick={handlePrev}
                className="px-3.5 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>Back</span>
              </button>
            )}

            <button
              onClick={handleNext}
              className="px-4 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>{currentStep === steps.length - 1 ? 'Got it! Close' : 'Next'}</span>
              {currentStep === steps.length - 1 ? (
                <CheckCircle2 className="w-4 h-4" />
              ) : (
                <ChevronRight className="w-4 h-4" />
              )}
            </button>
          </div>
        </div>

      </div>
    </div>
  );
}
