import { useState, useEffect } from "react";
import { motion, AnimatePresence, PanInfo } from "motion/react";
import { 
  Wallet, 
  Sparkles, 
  PiggyBank, 
  Users, 
  Shield, 
  ArrowRight, 
  ChevronLeft, 
  ChevronRight,
  Coins,
  TrendingUp,
  Lock,
  Smartphone,
  Target,
  RefreshCw
} from "lucide-react";
import { Button } from "./ui/button";
import { ImageWithFallback } from "./figma/ImageWithFallback";
import enamelLogo from 'figma:asset/2e2e3fad7673e8eef9a255215dd6ac2cf27cc590.png';

interface WelcomePageProps {
  onGetStarted: () => void;
  onSignUp?: () => void;
  onSignIn?: () => void;
  onGoogleAuth?: () => void;
}

interface OnboardingSlide {
  id: number;
  title: string;
  subtitle: string;
  icon: React.ReactNode;
  illustration: React.ReactNode;
  color: string;
}

export function WelcomePage({ onGetStarted, onSignUp, onSignIn, onGoogleAuth }: WelcomePageProps) {
  const [currentSlide, setCurrentSlide] = useState(0);

  const slides: OnboardingSlide[] = [
    {
      id: 1,
      title: "Welcome to Enamel Wallets",
      subtitle: "The easiest way to save daily, weekly, or monthly.",
      icon: <Wallet className="w-16 h-16 text-white" />,
      illustration: (
        <div className="relative flex items-center justify-center">
          <motion.div
            animate={{ rotate: 360 }}
            transition={{ duration: 20, repeat: Infinity, ease: "linear" }}
            className="absolute"
          >
            <div className="w-32 h-32 border-4 border-dashed border-white/30 rounded-full"></div>
          </motion.div>
          <motion.div
            animate={{ y: [0, -10, 0] }}
            transition={{ duration: 2, repeat: Infinity, ease: "easeInOut" }}
            className="bg-white/20 backdrop-blur-sm rounded-2xl p-6 border border-white/30"
          >
            <Wallet className="w-12 h-12 text-white" />
          </motion.div>
          {/* Floating coins */}
          {[...Array(6)].map((_, i) => (
            <motion.div
              key={i}
              className="absolute w-4 h-4 bg-yellow-400 rounded-full"
              animate={{
                y: [0, -40, -60, -40, 0],
                x: [0, Math.sin(i) * 20, Math.sin(i) * 30, Math.sin(i) * 20, 0],
                opacity: [0, 1, 1, 1, 0],
              }}
              transition={{
                duration: 3,
                repeat: Infinity,
                delay: i * 0.3,
                ease: "easeInOut"
              }}
              style={{
                left: `${50 + Math.cos(i * 60 * Math.PI / 180) * 80}px`,
                top: `${50 + Math.sin(i * 60 * Math.PI / 180) * 80}px`,
              }}
            />
          ))}
        </div>
      ),
      color: "from-blue-600 to-blue-700"
    },
    {
      id: 2,
      title: "Save Smart",
      subtitle: "Choose your saving style – daily, weekly, or monthly with ease.",
      icon: <PiggyBank className="w-16 h-16 text-white" />,
      illustration: (
        <div className="relative flex items-center justify-center">
          <motion.div
            className="w-24 h-32 bg-white/20 backdrop-blur-sm rounded-3xl border border-white/30 relative overflow-hidden"
          >
            {/* Progress bar filling animation */}
            <motion.div
              className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-yellow-400 to-yellow-300"
              animate={{ height: ["10%", "70%", "10%"] }}
              transition={{ duration: 4, repeat: Infinity, ease: "easeInOut" }}
            />
            <div className="absolute top-2 left-2 right-2">
              <Target className="w-6 h-6 text-white mx-auto" />
            </div>
          </motion.div>
          {/* Coins stacking animation */}
          {[...Array(5)].map((_, i) => (
            <motion.div
              key={i}
              className="absolute w-6 h-2 bg-yellow-400 rounded-full"
              animate={{
                y: [20, -10 - i * 6],
                opacity: [0, 1],
                scale: [0.5, 1]
              }}
              transition={{
                duration: 2,
                repeat: Infinity,
                delay: i * 0.4,
                ease: "easeOut"
              }}
              style={{
                left: "calc(50% - 12px)",
                bottom: `${20 + i * 6}px`,
              }}
            />
          ))}
        </div>
      ),
      color: "from-green-600 to-emerald-600"
    },
    {
      id: 3,
      title: "Join Group Contributions",
      subtitle: "Save together and take turns receiving payouts.",
      icon: <Users className="w-16 h-16 text-white" />,
      illustration: (
        <div className="relative flex items-center justify-center">
          {/* Circle of people */}
          {[...Array(8)].map((_, i) => (
            <motion.div
              key={i}
              className="absolute w-8 h-8 bg-white/30 rounded-full border-2 border-white/50 flex items-center justify-center"
              animate={{
                scale: [1, 1.1, 1],
              }}
              transition={{
                duration: 2,
                repeat: Infinity,
                delay: i * 0.25,
                ease: "easeInOut"
              }}
              style={{
                left: `${50 + Math.cos(i * 45 * Math.PI / 180) * 60}px`,
                top: `${50 + Math.sin(i * 45 * Math.PI / 180) * 60}px`,
                transform: "translate(-50%, -50%)"
              }}
            >
              <Users className="w-4 h-4 text-white" />
            </motion.div>
          ))}
          {/* Center money circulation */}
          <motion.div
            animate={{ rotate: 360 }}
            transition={{ duration: 8, repeat: Infinity, ease: "linear" }}
            className="w-16 h-16 border-2 border-dashed border-yellow-400 rounded-full flex items-center justify-center"
          >
            <Coins className="w-6 h-6 text-yellow-400" />
          </motion.div>
        </div>
      ),
      color: "from-purple-600 to-violet-600"
    },
    {
      id: 4,
      title: "Safe and Transparent",
      subtitle: "Your money is secured with bank-grade encryption and instant payouts.",
      icon: <Shield className="w-16 h-16 text-white" />,
      illustration: (
        <div className="relative flex items-center justify-center">
          <motion.div
            className="w-20 h-28 bg-white/20 backdrop-blur-sm rounded-2xl border border-white/30 relative"
            animate={{ scale: [1, 1.05, 1] }}
            transition={{ duration: 3, repeat: Infinity, ease: "easeInOut" }}
          >
            <Smartphone className="w-8 h-8 text-white absolute top-2 left-1/2 transform -translate-x-1/2" />
            <Wallet className="w-6 h-6 text-white absolute bottom-6 left-1/2 transform -translate-x-1/2" />
          </motion.div>
          {/* Shield overlay */}
          <motion.div
            className="absolute w-16 h-16 bg-green-500/80 rounded-full flex items-center justify-center -top-2 -right-2"
            animate={{ 
              scale: [1, 1.2, 1],
              boxShadow: ["0 0 0 0 rgba(34, 197, 94, 0.4)", "0 0 0 20px rgba(34, 197, 94, 0)", "0 0 0 0 rgba(34, 197, 94, 0)"]
            }}
            transition={{ duration: 2, repeat: Infinity, ease: "easeInOut" }}
          >
            <Lock className="w-8 h-8 text-white" />
          </motion.div>
        </div>
      ),
      color: "from-teal-600 to-cyan-600"
    },
    {
      id: 5,
      title: "Ready to Begin?",
      subtitle: "Create an account and start saving today!",
      icon: <TrendingUp className="w-16 h-16 text-white" />,
      illustration: (
        <div className="relative flex items-center justify-center">
          <motion.div
            className="w-24 h-16 bg-gradient-to-r from-white/20 to-white/30 backdrop-blur-sm rounded-2xl border border-white/30 flex items-center justify-center cursor-pointer relative overflow-hidden"
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
          >
            <motion.div
              className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent"
              animate={{ x: ["-100%", "100%"] }}
              transition={{ duration: 2, repeat: Infinity, ease: "easeInOut" }}
            />
            <span className="text-white font-semibold relative z-10">Start Saving</span>
          </motion.div>
          {/* Hand pointer animation */}
          <motion.div
            className="absolute -bottom-4 -right-4"
            animate={{ 
              x: [10, 0, 10],
              y: [10, 0, 10]
            }}
            transition={{ duration: 1.5, repeat: Infinity, ease: "easeInOut" }}
          >
            <div className="w-8 h-8 bg-white/30 rounded-full flex items-center justify-center border border-white/50">
              👆
            </div>
          </motion.div>
        </div>
      ),
      color: "from-orange-600 to-red-600"
    }
  ];

  const nextSlide = () => {
    setCurrentSlide((prev) => (prev + 1) % slides.length);
  };

  const prevSlide = () => {
    setCurrentSlide((prev) => (prev - 1 + slides.length) % slides.length);
  };

  const goToSlide = (index: number) => {
    setCurrentSlide(index);
  };

  const handleGetStarted = () => {
    if (onSignUp) {
      onSignUp();
    } else {
      onGetStarted();
    }
  };

  const currentSlideData = slides[currentSlide];

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentSlide((prev) => (prev + 1) % slides.length);
    }, 5000);

    return () => clearInterval(timer);
  }, [slides.length]);

  const handleDragEnd = (event: any, info: PanInfo) => {
    const swipeThreshold = 50;
    
    if (info.offset.x > swipeThreshold) {
      prevSlide();
    } else if (info.offset.x < -swipeThreshold) {
      nextSlide();
    }
  };

  return (
    <div className={`min-h-screen bg-gradient-to-br ${currentSlideData.color} relative overflow-hidden`}>
      {/* Background Image */}
      <div className="absolute inset-0 opacity-20">
        <ImageWithFallback
          src={enamelLogo}
          alt="People saving together"
          className="w-full h-full object-cover"
        />
      </div>

      {/* Animated Background Elements */}
      <div className="absolute inset-0 overflow-hidden">
        <motion.div
          className="absolute -top-20 -left-20 w-96 h-96 bg-white/5 rounded-full"
          animate={{
            scale: [1, 1.2, 1],
            x: [0, 30, 0],
            y: [0, -20, 0],
          }}
          transition={{
            duration: 8,
            repeat: Infinity,
            ease: "easeInOut",
          }}
        />
        <motion.div
          className="absolute -bottom-20 -right-20 w-80 h-80 bg-white/5 rounded-full"
          animate={{
            scale: [1, 1.3, 1],
            x: [0, -40, 0],
            y: [0, 30, 0],
          }}
          transition={{
            duration: 10,
            repeat: Infinity,
            ease: "easeInOut",
          }}
        />
      </div>

      {/* Navigation Arrows */}
      <div className="absolute top-1/2 left-4 transform -translate-y-1/2 z-20">
        <Button
          variant="ghost"
          size="icon"
          onClick={prevSlide}
          className="w-12 h-12 rounded-full bg-white/10 backdrop-blur-sm border border-white/20 text-white hover:bg-white/20"
        >
          <ChevronLeft className="w-6 h-6" />
        </Button>
      </div>

      <div className="absolute top-1/2 right-4 transform -translate-y-1/2 z-20">
        <Button
          variant="ghost"
          size="icon"
          onClick={nextSlide}
          className="w-12 h-12 rounded-full bg-white/10 backdrop-blur-sm border border-white/20 text-white hover:bg-white/20"
        >
          <ChevronRight className="w-6 h-6" />
        </Button>
      </div>

      {/* Floating Logo */}
      <motion.div
        className="absolute top-8 left-1/2 transform -translate-x-1/2 z-20"
        animate={{ y: [0, -5, 0] }}
        transition={{ duration: 3, repeat: Infinity, ease: "easeInOut" }}
      >
        <div className="w-20 h-20 bg-white/15 backdrop-blur-sm rounded-2xl flex items-center justify-center shadow-lg border border-white/20 p-2">
          <ImageWithFallback
            src={enamelLogo}
            alt="Enamel Wallets Logo"
            className="w-full h-full object-contain"
          />
        </div>
      </motion.div>

      {/* Main Content */}
      <div className="relative z-10 flex flex-col h-screen">
        <div className="flex-1 flex flex-col items-center justify-center px-6 pt-24 pb-32">
          <motion.div
            className="w-full h-full flex items-center justify-center"
            drag="x"
            dragConstraints={{ left: 0, right: 0 }}
            dragElastic={0.3}
            onDragEnd={handleDragEnd}
            whileDrag={{ cursor: "grabbing" }}
          >
            <AnimatePresence mode="wait">
              <motion.div
                key={currentSlide}
                initial={{ opacity: 0, x: 100 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -100 }}
                transition={{ duration: 0.5, ease: "easeInOut" }}
                className="text-center max-w-sm w-full"
              >
                {/* Illustration */}
                <motion.div
                  initial={{ scale: 0.8, opacity: 0 }}
                  animate={{ scale: 1, opacity: 1 }}
                  transition={{ delay: 0.2, duration: 0.6 }}
                  className="mb-8 h-48 flex items-center justify-center"
                >
                  {currentSlideData.illustration}
                </motion.div>

                {/* Title */}
                <motion.h1
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.3, duration: 0.6 }}
                  className="text-3xl font-bold text-white mb-4 leading-tight"
                >
                  {currentSlideData.title}
                </motion.h1>

                {/* Subtitle */}
                <motion.p
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.4, duration: 0.6 }}
                  className="text-white/90 text-lg leading-relaxed mb-8"
                >
                  {currentSlideData.subtitle}
                </motion.p>

                {/* Action Button for last slide */}
                {currentSlide === slides.length - 1 && (
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.5, duration: 0.6 }}
                    className="space-y-4"
                  >
                    <Button
                      onClick={handleGetStarted}
                      size="lg"
                      className="w-full bg-white text-primary hover:bg-white/90 font-semibold py-4 rounded-2xl shadow-xl"
                    >
                      Get Started
                      <ArrowRight className="w-5 h-5 ml-2" />
                    </Button>
                    
                    <div className="flex gap-2 justify-center">
                      <Button
                        onClick={onSignIn}
                        variant="ghost"
                        className="text-white hover:bg-white/10 font-medium"
                      >
                        Already have an account?
                      </Button>
                    </div>
                  </motion.div>
                )}
              </motion.div>
            </AnimatePresence>
          </motion.div>
        </div>

        {/* Slide Indicators */}
        <div className="absolute bottom-8 left-1/2 transform -translate-x-1/2 flex space-x-2 z-20">
          {slides.map((_, index) => (
            <button
              key={index}
              onClick={() => goToSlide(index)}
              className={`w-3 h-3 rounded-full transition-all duration-300 ${
                index === currentSlide
                  ? "bg-white scale-125"
                  : "bg-white/40 hover:bg-white/60"
              }`}
            />
          ))}
        </div>

        {/* Skip button */}
        <div className="absolute top-8 right-6 z-20">
          <Button
            onClick={handleGetStarted}
            variant="ghost"
            className="text-white hover:bg-white/10 font-medium"
          >
            Skip
          </Button>
        </div>
      </div>
    </div>
  );
}