"use client";

import { useRef, useState, useEffect } from "react";
import { motion, useInView } from "framer-motion";
import { Code2, Server, Database, GitBranch } from "lucide-react";

const skills = [
  "Next.js",
  "NestJS",
  "TypeScript",
  "React",
  "Node.js",
  "PostgreSQL",
  "Prisma",
  "TypeORM",
  "Redis",
  "Docker",
  "REST API",
  "Git",
  "Microservices",
];

const stats = [
  { label: "Years Experience", value: "3+", icon: Code2 },
  { label: "System Built", value: "15+", icon: GitBranch },
  { label: "Modules Delivered", value: "15+", icon: Server },
  { label: "Production Deployments", value: "10+", icon: Database },
];

const containerVariants = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: { staggerChildren: 0.08, delayChildren: 0.1 },
  },
};

const itemVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.5, ease: "easeOut" } },
};

// Custom hook for counting animation
const useCountingAnimation = (target: number, isInView: boolean, duration: number = 2000, delay: number = 0) => {
  const [count, setCount] = useState(0);
  const [shouldStart, setShouldStart] = useState(false);

  useEffect(() => {
    if (!isInView) {
      setCount(0);
      setShouldStart(false);
      return;
    }

    // Start counting after delay
    const timer = setTimeout(() => {
      setShouldStart(true);
    }, delay);

    return () => clearTimeout(timer);
  }, [isInView, delay]);

  useEffect(() => {
    if (!shouldStart) {
      setCount(0);
      return;
    }

    const startTime = Date.now();
    const endTime = startTime + duration;

    const animate = () => {
      const now = Date.now();
      const progress = Math.min((now - startTime) / duration, 1);
      
      // Easing function for smooth animation
      const easeOutQuad = 1 - Math.pow(1 - progress, 2);
      const currentCount = Math.floor(easeOutQuad * target);
      
      setCount(currentCount);

      if (progress < 1) {
        requestAnimationFrame(animate);
      }
    };

    requestAnimationFrame(animate);
  }, [shouldStart, target, duration]);

  return count;
};

export function AboutSection() {
  const ref = useRef(null);
  const statsRef = useRef(null);
  const quoteRef = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-10%" });
  const statsInView = useInView(statsRef, { once: true, margin: "-10%" });
  const quoteInView = useInView(quoteRef, { once: true, margin: "-10%" });

  // Extract numeric values and use counting animation
  // Calculate delay: staggerChildren: 0.08, delayChildren: 0.1, item duration: 0.5
  // Stats are in the right column, so they appear after left column items
  const entranceDelay = 600; // Reduced delay - after entrance animation completes
  const yearsCount = useCountingAnimation(3, statsInView, 1500, entranceDelay);
  const systemsCount = useCountingAnimation(15, statsInView, 2000, entranceDelay + 100);
  const modulesCount = useCountingAnimation(15, statsInView, 2000, entranceDelay + 200);
  const deploymentsCount = useCountingAnimation(10, statsInView, 1800, entranceDelay + 300);

  return (
    <section id="about" className="py-5 lg:py-32 relative overflow-hidden">
      <div className="absolute inset-0 bg-gradient-to-b from-background via-surface/30 to-background" />

      <div className="relative z-10 max-w-6xl mx-auto px-6">
        <motion.div
          ref={ref}
          variants={containerVariants}
          initial="hidden"
          animate={isInView ? "visible" : "hidden"}
          className="grid lg:grid-cols-2 gap-16 items-start"
        >
          {/* Left: Text content */}
          <div>
            <motion.div variants={itemVariants} className="mb-3">
              <span className="text-accent font-mono text-sm tracking-widest uppercase">
                About Me
              </span>
            </motion.div>

            <motion.h2
              variants={itemVariants}
              className="font-display font-bold text-4xl md:text-5xl text-foreground mb-6 leading-tight"
            >
              Engineering Beyond
              <br />
              <span className="gradient-text-blue">Just Code</span>
            </motion.h2>

            <motion.div
              variants={itemVariants}
              className="space-y-4 text-foreground-muted leading-relaxed"
            >
              <p>
                I'm a Fullstack Developer with 3+ years of experience building production-ready web applications using{" "}
                <span className="text-foreground font-medium">Next.js</span> and{" "}
                <span className="text-foreground font-medium">NestJS</span>.
                My experience includes developing WhatsApp chatbot integrations,
                building high-traffic lottery web applications, creating internal business dashboards,
                and contributing to ERP-based POS systems.

              </p>

              <p>
                My expertise spans scalable frontend architecture with Next.js,
                Zustand, Tailwind CSS, and Framer Motion, as well as secure
                backend systems using{" "}
                <span className="text-foreground font-medium">NestJS</span>,{" "}
                <span className="text-foreground font-medium">PostgreSQL</span>,
                and <span className="text-foreground font-medium">MongoDB</span>
                .
              </p>

              <p>
                I focus on writing clean, maintainable code while ensuring
                performance, validation, and system reliability. Every feature I
                build is designed with scalability and long-term maintainability
                in mind.
              </p>

              <p>
                Whether it's architecting an internal dashboard from scratch,
                optimizing complex database queries, or designing modular
                backend systems — I bring both execution and engineering
                thinking to every project.
              </p>
            </motion.div>

            {/* Skill badges */}
            <motion.div
              variants={containerVariants}
              className="flex flex-wrap gap-2 mt-8"
            >
              {skills.map((skill) => (
                <motion.span
                  key={skill}
                  variants={itemVariants}
                  className="px-3 py-1.5 text-xs font-mono font-medium bg-surface-elevated border border-border text-foreground-muted rounded-lg hover:border-accent/40 hover:text-accent hover:bg-accent/5 transition-all duration-200 cursor-default"
                >
                  {skill}
                </motion.span>
              ))}
            </motion.div>
          </div>

          {/* Right: Stats grid */}
          <motion.div 
            ref={statsRef}
            variants={containerVariants}
            initial="hidden"
            animate={statsInView ? "visible" : "hidden"}
            className="grid grid-cols-2 gap-4"
          >
            {stats.map((stat, index) => {
              const Icon = stat.icon;
              let displayValue = stat.value;
              
              // Use animated values based on index
              if (index === 0) displayValue = `${yearsCount}+`;
              else if (index === 1) displayValue = `${systemsCount}+`;
              else if (index === 2) displayValue = `${modulesCount}+`;
              else if (index === 3) displayValue = `${deploymentsCount}+`;
              
              return (
                <motion.div
                  key={stat.label}
                  variants={itemVariants}
                  className="p-6 rounded-2xl bg-surface-elevated border border-border hover:border-accent/30 hover:shadow-glow transition-all duration-300 group"
                >
                  <div className="w-10 h-10 rounded-xl bg-accent/10 border border-border flex items-center justify-center mb-4 group-hover:bg-accent/20 transition-colors">
                    <Icon size={18} className="text-accent" />
                  </div>
                  <p className="font-display font-bold text-4xl text-foreground mb-1">
                    {displayValue}
                  </p>
                  <p className="text-sm text-foreground-muted">{stat.label}</p>
                </motion.div>
              );
            })}

            {/* Quote card */}
            <motion.div
              ref={quoteRef}
              variants={itemVariants}
              className="col-span-2 p-6 rounded-2xl bg-gradient-to-br from-accent/10 to-purple-500/5 border border-border"
              initial="hidden"
              animate={quoteInView ? "visible" : "hidden"}
            >
              <p className="text-foreground-muted text-sm leading-relaxed italic">
                "I focus on writing clean, maintainable code while thinking about how systems grow over time. I value good architecture, scalability, and building solutions that are easy for teams to maintain."
              </p>
              <p className="text-accent text-sm font-medium mt-3">
                — Engineering Philosophy
              </p>
            </motion.div>
          </motion.div>
        </motion.div>
      </div>
    </section>
  );
}
