import { motion, AnimatePresence } from "framer-motion";
import { Building2, ArrowRight, TrendingUp } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useState, useMemo } from "react";
import { useSeoMeta } from "@/lib/use-seo-meta";
import { fetchWithFormProtection } from "@/lib/submission-protection";

export default function Onboarding() {
  const [investorEmail, setInvestorEmail] = useState("");
  const [prospectEmail, setProspectEmail] = useState("");
  const [showEmailPrompt, setShowEmailPrompt] = useState(false);

  // Memoize animation variants to prevent recreation on each render
  const containerVariants = useMemo(() => ({
    initial: { opacity: 0, y: 30 },
    animate: { opacity: 1, y: 0 }
  }), []);

  const headerVariants = useMemo(() => ({
    initial: { opacity: 0, y: 20 },
    animate: { opacity: 1, y: 0 }
  }), []);

  const cardVariants = useMemo(() => ({
    initial: { opacity: 0, x: -50 },
    animate: { opacity: 1, x: 0 }
  }), []);

  const handleSelection = async (type: 'investor' | 'prospect') => {
    const email = type === 'investor' ? investorEmail : prospectEmail;

    // Validate email before submission
    if (!email || !email.trim()) {
      // Show the human-friendly prompt instead of a basic alert
      setShowEmailPrompt(true);
      return;
    }

    if (!/\S+@\S+\.\S+/.test(email)) {
      // Show the human-friendly prompt instead of a basic alert
      setShowEmailPrompt(true);
      return;
    }

    try {
      // Submit email to backend
      const response = await fetchWithFormProtection('/api/onboarding-email', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email,
          userType: type,
        }),
      });

      if (!response.ok) {
        throw new Error('Failed to submit email');
      }

      // Store email and user type in localStorage
      localStorage.setItem('userEmail', email);
      localStorage.setItem('userType', type);

      // Store in type-specific keys as well for backward compatibility
      if (type === 'investor') {
        localStorage.setItem('investorEmail', email);
        window.location.href = '/investor-form';
      } else {
        localStorage.setItem('enterpriseEmail', email);
        window.location.href = '/enterprise-assessment-form';
      }
    } catch (error) {
      console.error('Error submitting email:', error);
      // Show the human-friendly prompt on error as well
      setShowEmailPrompt(true);
    }
  };

  useSeoMeta({ title: "Onboarding | OktoPeople", description: "Welcome to OktoPeople. Complete your onboarding to get started.", noindex: true });
  return (
    <div className="min-h-screen bg-dark-primary text-white font-['Poppins',sans-serif]">
      {/* Background effects */}
      <div className="absolute inset-0 bg-gradient-to-br from-dark-primary via-purple-900/10 to-emerald-900/10">
        <div className="absolute top-1/4 left-1/3 w-96 h-96 bg-purple-500/5 rounded-full blur-3xl"></div>
        <div className="absolute bottom-1/3 right-1/4 w-80 h-80 bg-emerald-500/5 rounded-full blur-3xl"></div>
      </div>

      <div className="relative z-10 min-h-screen flex items-center justify-center px-4 sm:px-6 lg:px-8">
        <motion.div
          variants={containerVariants}
          initial="initial"
          animate="animate"
          transition={{ duration: 0.5 }}
          className="max-w-5xl w-full"
        >
          {/* Header */}
          <div className="text-center mb-10 mt-8">
            <motion.h1
              className="text-4xl sm:text-5xl md:text-6xl font-semibold text-white mb-2"
              variants={headerVariants}
              initial="initial"
              animate="animate"
              transition={{ delay: 0.1 }}
            >
              Welcome to <span className="bg-gradient-to-r from-purple-400 to-emerald-400 bg-clip-text text-transparent">OktoPeople</span>
            </motion.h1>
            <motion.p
              className="text-xl text-white/70 max-w-2xl mx-auto"
              variants={headerVariants}
              initial="initial"
              animate="animate"
              transition={{ delay: 0.15 }}
            >
              Let us know how you'd like to engage with our platform
            </motion.p>
          </div>

          {/* Selection Cards */}
          <div className="grid md:grid-cols-2 gap-8">
            {/* Investor Card */}
            <motion.div
              variants={cardVariants}
              initial="initial"
              animate="animate"
              transition={{ delay: 0.2, duration: 0.4 }}
              whileHover={{ scale: 1.01 }}
              className="group"
            >
              <div className="bg-gradient-to-br from-purple-500/10 to-purple-600/5 backdrop-blur-lg border border-purple-500/20 rounded-2xl p-8 h-full hover:border-purple-400/40 transition-all duration-300"
              >
                <div className="flex flex-col h-full">
                  {/* Icon */}
                  <div className="w-16 h-16 bg-gradient-to-br from-purple-500 to-purple-600 rounded-2xl flex items-center justify-center mb-4">
                    <TrendingUp className="w-8 h-8 text-white" />
                  </div>

                  {/* Title */}
                  <h2 className="text-3xl font-semibold text-white mb-3">
                    I'm an Investor
                  </h2>

                  {/* Early Adopter Badge */}
                  <div className="mb-3">
                    <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-purple-500/20 text-purple-300 border border-purple-500/30">
                      ⭐ Early Investor Access
                    </span>
                  </div>

                  {/* Description */}
                  <p className="text-white/70 text-lg mb-4 flex-grow">
                    Get first access to our angel and pre-seed rounds with exclusive terms and early-stage opportunities.
                  </p>

                  {/* Features */}
                  <ul className="space-y-2 mb-6">
                    <li className="flex items-start text-white/80">
                      <ArrowRight className="w-5 h-5 text-purple-400 mt-1 mr-3 flex-shrink-0" />
                      <span>First access to angel and pre-seed rounds</span>
                    </li>
                    <li className="flex items-start text-white/80">
                      <ArrowRight className="w-5 h-5 text-purple-400 mt-1 mr-3 flex-shrink-0" />
                      <span>Exclusive early-stage investor terms</span>
                    </li>
                    <li className="flex items-start text-white/80">
                      <ArrowRight className="w-5 h-5 text-purple-400 mt-1 mr-3 flex-shrink-0" />
                      <span>Direct access to founders and pitch deck</span>
                    </li>
                  </ul>

                  {/* Email Input */}
                  <div className="mb-4">
                    <input
                      type="email"
                      value={investorEmail}
                      onChange={(e) => setInvestorEmail(e.target.value)}
                      placeholder="Enter your email address"
                      className="w-full bg-purple-900/20 border border-purple-500/30 text-white placeholder-white/50 rounded-xl px-4 py-3 focus:outline-none focus:border-purple-400 focus:ring-2 focus:ring-purple-400/20 transition-all duration-300"
                    />
                  </div>

                  {/* CTA */}
                  <Button
                    onClick={() => handleSelection('investor')}
                    disabled={!investorEmail || !/\S+@\S+\.\S+/.test(investorEmail)}
                    className="w-full bg-gradient-to-r from-purple-600 to-purple-500 hover:from-purple-700 hover:to-purple-600 text-white font-medium h-14 text-lg rounded-xl group-hover:shadow-lg group-hover:shadow-purple-500/30 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    Continue as Investor
                    <ArrowRight className="ml-2 w-5 h-5" />
                  </Button>
                </div>
              </div>
            </motion.div>

            {/* Prospect/Enterprise Card */}
            <motion.div
              initial={{ opacity: 0, x: 50 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.25, duration: 0.4 }}
              whileHover={{ scale: 1.01 }}
              className="group"
            >
              <div className="bg-gradient-to-br from-emerald-500/10 to-emerald-600/5 backdrop-blur-lg border border-emerald-500/20 rounded-2xl p-8 h-full hover:border-emerald-400/40 transition-all duration-300"
              >
                <div className="flex flex-col h-full">
                  {/* Icon */}
                  <div className="w-16 h-16 bg-gradient-to-br from-emerald-500 to-emerald-600 rounded-2xl flex items-center justify-center mb-4">
                    <Building2 className="w-8 h-8 text-white" />
                  </div>

                  {/* Title */}
                  <h2 className="text-3xl font-semibold text-white mb-3">
                    I'm Looking for Solutions
                  </h2>

                  {/* Early Adopter Badge */}
                  <div className="mb-3">
                    <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">
                      🚀 Early Adopter Program
                    </span>
                  </div>

                  {/* Description */}
                  <p className="text-white/70 text-lg mb-4 flex-grow">
                    Join as an <strong className="text-emerald-300">Early Adopter</strong> and transform your business with AI-driven intelligence and automation tailored to your needs.
                  </p>

                  {/* Features */}
                  <ul className="space-y-2 mb-6">
                    <li className="flex items-start text-white/80">
                      <ArrowRight className="w-5 h-5 text-emerald-400 mt-1 mr-3 flex-shrink-0" />
                      <span>Custom AI implementation assessment</span>
                    </li>
                    <li className="flex items-start text-white/80">
                      <ArrowRight className="w-5 h-5 text-emerald-400 mt-1 mr-3 flex-shrink-0" />
                      <span>No-code automation solutions</span>
                    </li>
                    <li className="flex items-start text-white/80">
                      <ArrowRight className="w-5 h-5 text-emerald-400 mt-1 mr-3 flex-shrink-0" />
                      <span>Expert consultation and support</span>
                    </li>
                  </ul>

                  {/* Email Input */}
                  <div className="mb-4">
                    <input
                      type="email"
                      value={prospectEmail}
                      onChange={(e) => setProspectEmail(e.target.value)}
                      placeholder="Enter your email address"
                      className="w-full bg-emerald-900/20 border border-emerald-500/30 text-white placeholder-white/50 rounded-xl px-4 py-3 focus:outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-400/20 transition-all duration-300"
                    />
                  </div>

                  {/* CTA */}
                  <Button
                    onClick={() => handleSelection('prospect')}
                    disabled={!prospectEmail || !/\S+@\S+\.\S+/.test(prospectEmail)}
                    className="w-full bg-gradient-to-r from-emerald-600 to-emerald-500 hover:from-emerald-700 hover:to-emerald-600 text-white font-medium h-14 text-lg rounded-xl group-hover:shadow-lg group-hover:shadow-emerald-500/30 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    Explore Solutions
                    <ArrowRight className="ml-2 w-5 h-5" />
                  </Button>
                </div>
              </div>
            </motion.div>
          </div>
        </motion.div>
      </div>

      {/* Email Prompt Modal */}
      {showEmailPrompt && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="bg-gradient-to-br from-slate-900 to-slate-800 rounded-2xl p-8 max-w-md w-full shadow-2xl border border-purple-500/20"
          >
            <div className="text-center mb-6">
              <div className="w-16 h-16 bg-gradient-to-r from-purple-500 to-blue-500 rounded-full flex items-center justify-center mx-auto mb-4">
                <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
              </div>
              <h3 className="text-2xl font-semibold text-white mb-3">
                One More Step! 🚀
              </h3>
              <p className="text-gray-300 leading-relaxed">
                Please enter your email address above to continue your journey with us. We'll keep you updated on exclusive opportunities!
              </p>
            </div>
            <Button
              onClick={() => setShowEmailPrompt(false)}
              className="w-full bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 text-white py-6 text-lg rounded-xl shadow-lg hover:shadow-purple-500/50 transition-all duration-300"
            >
              Got it! ✓
            </Button>
          </motion.div>
        </div>
      )}
    </div>
  );
}