import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Check, ArrowRight, Play, Clock, ShieldCheck, Star, BadgeCheck, DollarSign, Hammer, Briefcase, TrendingUp } from "lucide-react";
import chalet3 from "@assets/chalet-3-DYRaIf8i_1771001037626.jpg";
import chalet4 from "@assets/chalet-4-Cvlo-Dai_1771001037627.jpg";
import chaletAFrame from "@assets/e265d1e6-af84-4e15-a83c-a06bea4718bc_1771001065678.jpg";
import checkoutImg from "@assets/chalet-4-Cvlo-Dai_1771001037627.jpg";
import { Carousel, CarouselContent, CarouselItem } from "@/components/ui/carousel";
import Autoplay from "embla-carousel-autoplay";

type Step = "landing" | "quiz" | "analyzing" | "capture" | "sales";

type QuizData = {
  goal: string;
  profile: string;
  attraction: string;
  firstAction: string;
  structure: string[];
  marketInterest: string[];
  name: string;
};

const questions = [
  {
    id: 1,
    question: "Qual é seu principal objetivo com chalés?",
    image: chaletAFrame,
    options: ["Vender", "Alugar", "Morar", "Fabricar"],
    multi: false
  },
  {
    id: 2,
    question: "Com qual perfil você mais se identifica?",
    options: ["Serralheiro / Carpinteiro", "Arquiteto / Engenheiro", "Empreendedor / Investidor", "Pessoa comum"],
    multi: false
  },
  {
    id: 3,
    question: "O que mais te atrai nos projetos de chalé?",
    options: [
      { label: "Nova fonte de renda", icon: <DollarSign className="w-4 h-4 text-orange-500" /> },
      { label: "Oferecer projetos prontos", icon: <Briefcase className="w-4 h-4 text-orange-500" /> },
      { label: "Construir com menor custo", icon: <Hammer className="w-4 h-4 text-orange-500" /> },
      { label: "Criar novos modelos", icon: <Star className="w-4 h-4 text-yellow-500" /> },
      { label: "Valorizar seu trabalho", icon: <TrendingUp className="w-4 h-4 text-blue-500" /> }
    ],
    multi: false
  },
  {
    id: 4,
    question: "Se tivesse os projetos hoje, o que faria primeiro?",
    options: ["Escolher modelo ideal", "Construir para aluguel", "Mostrar a investidores", "Fechar parceria", "Criar seu próprio projeto", "Adaptar com profissional"],
    multi: false
  },
  {
    id: 5,
    question: "Qual sua estrutura atual? (pode marcar mais de uma)",
    options: ["Tenho terreno", "Quero alugar terreno", "Tenho parceiro com terreno", "Só quero o projeto", "Tenho equipe", "Tenho ferramentas"],
    multi: true
  },
  {
    id: 6,
    question: "O que mais te chama atenção nesse mercado?",
    options: [
      { label: "Alto lucro", icon: <DollarSign className="w-4 h-4 text-orange-500" /> },
      { label: "Design fácil de vender", icon: <Briefcase className="w-4 h-4 text-orange-500" /> },
      { label: "Crescimento Airbnb", icon: <TrendingUp className="w-4 h-4 text-green-500" /> },
      { label: "Portfólio valorizado", icon: <Star className="w-4 h-4 text-orange-500" /> },
      { label: "Parcerias", icon: <ShieldCheck className="w-4 h-4 text-yellow-500" /> }
    ],
    multi: true
  }
];

export default function QuizApp() {
  const [step, setStep] = useState<Step>("landing");
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [answers, setAnswers] = useState<QuizData>({
    goal: "", profile: "", attraction: "", firstAction: "", structure: [], marketInterest: [], name: ""
  });
  const [progress, setProgress] = useState(0);

  const handleStart = () => {
    setStep("quiz");
    setProgress(17);
  };

  const handleAnswer = (answer: string | string[]) => {
    const q = questions[currentQuestion];
    const key = Object.keys(answers)[currentQuestion] as keyof QuizData;
    
    // Update answers based on question index mapping
    // This is a simplified mapping for the demo
    setAnswers(prev => ({ ...prev, [key]: answer }));

    if (currentQuestion < questions.length - 1) {
      setCurrentQuestion(prev => prev + 1);
      setProgress(((currentQuestion + 2) / questions.length) * 100);
    } else {
      setStep("capture");
      setProgress(100);
    }
  };

  const handleNameSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (answers.name.trim()) {
      setStep("analyzing");
    }
  };

  return (
    <div className="min-h-screen bg-slate-50 font-sans text-slate-900">
      <AnimatePresence mode="wait">
        {step === "landing" && <LandingPage onStart={handleStart} />}
        {step === "quiz" && (
          <QuizPage 
            question={questions[currentQuestion]} 
            progress={progress} 
            onAnswer={handleAnswer} 
            currentAnswer={undefined}
          />
        )}
        {step === "capture" && (
          <CapturePage 
            name={answers.name} 
            setName={(n: string) => setAnswers(prev => ({ ...prev, name: n }))} 
            onSubmit={handleNameSubmit} 
          />
        )}
        {step === "analyzing" && <AnalyzingPage onComplete={() => setStep("sales")} />}
        {step === "sales" && <SalesPage name={answers.name} />}
      </AnimatePresence>
    </div>
  );
}

function LandingPage({ onStart }: { onStart: () => void }) {
  return (
    <motion.div 
      initial={{ opacity: 0 }} 
      animate={{ opacity: 1 }} 
      exit={{ opacity: 0 }}
      className="flex flex-col items-center justify-center min-h-screen p-4 max-w-4xl mx-auto text-center"
    >
      <h1 className="text-3xl md:text-5xl font-bold mb-4 tracking-tight text-slate-900">
        Pessoas comuns estão faturando alto com projetos de <span className="text-primary">Chalé Suíço</span>
      </h1>
      <p className="text-lg text-slate-600 mb-8 max-w-2xl">
        Responda 6 perguntas rápidas e descubra como usar projetos prontos para lucrar com chalés.
      </p>

      <div className="rounded-2xl overflow-hidden shadow-2xl mb-8 border-4 border-white max-w-2xl w-full">
        <Carousel 
          plugins={[Autoplay({ delay: 3000 })]}
          className="w-full"
        >
          <CarouselContent>
            {[chalet4, chalet3, chaletAFrame].map((img, index) => (
              <CarouselItem key={index}>
                <img src={img} alt={`Chalé Suíço ${index + 1}`} className="w-full h-[300px] md:h-[450px] object-cover" />
              </CarouselItem>
            ))}
          </CarouselContent>
        </Carousel>
      </div>

      <div className="flex flex-col gap-3 items-start md:items-center mb-8 text-left md:text-center text-slate-700">
        <div className="flex items-center gap-2">
          <BadgeCheck className="text-green-600 w-5 h-5 flex-shrink-0" fill="currentColor" color="white" />
          <span>Mercado em crescimento no Airbnb</span>
        </div>
        <div className="flex items-center gap-2">
          <BadgeCheck className="text-green-600 w-5 h-5 flex-shrink-0" fill="currentColor" color="white" />
          <span>Projetos que geram alto retorno</span>
        </div>
        <div className="flex items-center gap-2">
          <BadgeCheck className="text-green-600 w-5 h-5 flex-shrink-0" fill="currentColor" color="white" />
          <span>Ideal para iniciantes ou investidores</span>
        </div>
      </div>

      <Button onClick={onStart} size="lg" className="w-full md:w-auto px-12 py-6 text-lg font-bold shadow-lg shadow-blue-900/20 hover:scale-105 transition-transform bg-[#1e40af] hover:bg-[#1e3a8a]">
        COMEÇAR AGORA
      </Button>
    </motion.div>
  );
}

function QuizPage({ question, progress, onAnswer, currentAnswer }: any) {
  const [selected, setSelected] = useState<string[]>([]);

  // Reset selection when question changes
  useEffect(() => {
    setSelected([]);
  }, [question.id]);

  const handleSelect = (option: any) => {
    const value = typeof option === 'string' ? option : option.label;
    
    if (question.multi) {
      if (selected.includes(value)) {
        setSelected(prev => prev.filter(i => i !== value));
      } else {
        setSelected(prev => [...prev, value]);
      }
    } else {
      onAnswer(value);
    }
  };

  const handleMultiSubmit = () => {
    if (selected.length > 0) {
      onAnswer(selected);
    }
  };

  return (
    <motion.div 
      initial={{ opacity: 0, x: 20 }} 
      animate={{ opacity: 1, x: 0 }} 
      exit={{ opacity: 0, x: -20 }}
      key={question.id}
      className="max-w-2xl mx-auto p-4 min-h-screen flex flex-col pt-12"
    >
      <div className="mb-8 space-y-2">
        <div className="flex justify-between text-sm font-medium text-slate-500">
          <span>Progresso do quiz</span>
          <span>{Math.round(progress)}%</span>
        </div>
        <Progress value={progress} className="h-2 bg-slate-200" indicatorClassName="bg-blue-600" />
      </div>

      <h2 className="text-2xl md:text-3xl font-bold text-center mb-8 text-slate-900 leading-tight">
        {question.question}
      </h2>

      {question.image && (
        <div className="mb-8 flex justify-center">
          <img src={question.image} alt="Question context" className="rounded-xl shadow-md max-h-60 object-cover w-full md:w-2/3" />
        </div>
      )}

      <div className="grid gap-3 w-full max-w-lg mx-auto">
        {question.options.map((opt: any, idx: number) => {
          const value = typeof opt === 'string' ? opt : opt.label;
          const isSelected = selected.includes(value);
          
          return (
            <div 
              key={idx}
              onClick={() => handleSelect(opt)}
              className={`
                bg-white p-4 rounded-xl border-2 cursor-pointer transition-all duration-200 flex items-center gap-3 shadow-sm hover:shadow-md
                ${isSelected 
                  ? "border-blue-600 bg-blue-50 text-blue-900" 
                  : "border-transparent hover:border-slate-200 text-slate-700"
                }
              `}
            >
              {typeof opt !== 'string' && opt.icon}
              <span className="font-medium text-lg">{value}</span>
            </div>
          );
        })}
      </div>

      {question.multi && (
        <div className="mt-8 text-center">
          <p className="text-sm text-slate-400 mb-4">Pode marcar mais de uma opção</p>
          <Button 
            onClick={handleMultiSubmit} 
            disabled={selected.length === 0}
            className="w-full max-w-lg mx-auto bg-blue-700 hover:bg-blue-800"
            size="lg"
          >
            CONTINUAR
          </Button>
        </div>
      )}
    </motion.div>
  );
}

function CapturePage({ name, setName, onSubmit }: any) {
  return (
    <motion.div 
      initial={{ opacity: 0 }} 
      animate={{ opacity: 1 }} 
      className="max-w-2xl mx-auto p-4 min-h-screen flex flex-col pt-12"
    >
       <div className="mb-8 space-y-2">
        <div className="flex justify-between text-sm font-medium text-slate-500">
          <span>Progresso do quiz</span>
          <span>100%</span>
        </div>
        <Progress value={100} className="h-2 bg-slate-200" indicatorClassName="bg-blue-600" />
      </div>

      <div className="flex-1 flex flex-col justify-center items-center max-w-md mx-auto w-full">
        <h2 className="text-2xl font-bold text-center mb-8 text-slate-900">
          Digite seu nome para personalizar sua experiência
        </h2>
        
        <form onSubmit={onSubmit} className="w-full space-y-4">
          <Input 
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Digite seu nome..."
            className="h-14 text-lg bg-white border-slate-200"
            autoFocus
          />
          <Button type="submit" size="lg" className="w-full h-12 text-lg font-bold bg-[#6366f1] hover:bg-[#4f46e5]">
            CONTINUAR
          </Button>
        </form>
      </div>
    </motion.div>
  );
}

function AnalyzingPage({ onComplete }: { onComplete: () => void }) {
  const [prepProgress, setPrepProgress] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setPrepProgress(prev => {
        if (prev >= 100) {
          clearInterval(interval);
          return 100;
        }
        return prev + 2;
      });
    }, 50);
    return () => clearInterval(interval);
  }, []);

  return (
    <motion.div className="min-h-screen flex flex-col items-center justify-center p-6 bg-slate-50 text-center">
      <div className="bg-blue-100 p-8 rounded-2xl max-w-2xl mb-8 border-l-4 border-blue-500 shadow-sm">
        <p className="text-lg md:text-xl text-blue-900 font-medium leading-relaxed">
          Chalés comuns são alugados por mais de <span className="font-bold">R$800 por dia</span>, e tem muita gente garantindo a <span className="font-bold">aposentadoria</span> com chalé.
        </p>
        <div className="mt-4 pt-4 border-t border-blue-200">
          <p className="text-blue-800">
            E o melhor: <span className="font-bold">sem engenheiro, sem arquiteto e sem gastar meses projetando do zero.</span>
          </p>
        </div>
      </div>

      <div className="w-full max-w-md mb-12 space-y-2">
        <div className="flex justify-between text-sm font-medium text-slate-500">
          <span>Preparando sua apostila...</span>
          <span>{prepProgress}%</span>
        </div>
        <Progress value={prepProgress} className="h-3 bg-slate-200" indicatorClassName="bg-green-500" />
      </div>

      <div className="text-center mb-8">
        <h3 className="text-xl font-bold mb-2">Veja o que dizem nossos clientes</h3>
        <p className="text-slate-500 text-sm">Pessoas reais, resultados reais</p>
      </div>

      <div className="w-full max-w-lg mb-8">
        <Carousel 
          plugins={[Autoplay({ delay: 4000 })]}
          className="w-full"
        >
          <CarouselContent>
            <CarouselItem>
              <Card className="shadow-lg border-none">
                <CardContent className="p-6 text-left">
                  <div className="flex gap-1 text-orange-400 mb-3">
                    {[1,2,3,4,5].map(i => <Star key={i} className="w-4 h-4 fill-current" />)}
                  </div>
                  <p className="text-slate-600 italic mb-4">
                    "Os projetos são muito bem detalhados. Economizei semanas de trabalho e meus clientes amaram as opções."
                  </p>
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-full bg-blue-900 text-white flex items-center justify-center font-bold text-sm">
                      AP
                    </div>
                    <div>
                      <p className="font-bold text-sm text-slate-900">Ana Paula S.</p>
                      <p className="text-xs text-slate-500">Arquiteta</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </CarouselItem>
            <CarouselItem>
              <Card className="shadow-lg border-none">
                <CardContent className="p-6 text-left">
                  <div className="flex gap-1 text-orange-400 mb-3">
                    {[1,2,3,4,5].map(i => <Star key={i} className="w-4 h-4 fill-current" />)}
                  </div>
                  <p className="text-slate-600 italic mb-4">
                    "O custo-benefício é imbatível. Já estou no meu segundo chalé usando a planta da apostila."
                  </p>
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-full bg-slate-800 text-white flex items-center justify-center font-bold text-sm">
                      RM
                    </div>
                    <div>
                      <p className="font-bold text-sm text-slate-900">Ricardo M.</p>
                      <p className="text-xs text-slate-500">Investidor</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </CarouselItem>
            <CarouselItem>
              <Card className="shadow-lg border-none">
                <CardContent className="p-6 text-left">
                  <div className="flex gap-1 text-orange-400 mb-3">
                    {[1,2,3,4,5].map(i => <Star key={i} className="w-4 h-4 fill-current" />)}
                  </div>
                  <p className="text-slate-600 italic mb-4">
                    "Finalmente consegui colocar meu sonho em prática sem burocracia. O guia de materiais ajudou muito!"
                  </p>
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-full bg-blue-600 text-white flex items-center justify-center font-bold text-sm">
                      JS
                    </div>
                    <div>
                      <p className="font-bold text-sm text-slate-900">Juliana S.</p>
                      <p className="text-xs text-slate-500">Empreendedora</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </CarouselItem>
          </CarouselContent>
        </Carousel>
      </div>

      <Button 
        onClick={onComplete} 
        disabled={prepProgress < 100}
        className={`px-8 py-6 text-lg font-bold rounded-lg shadow-xl transition-all ${prepProgress < 100 ? 'bg-slate-400' : 'bg-blue-800 hover:bg-blue-900 animate-pulse'}`}
      >
        VER MEU RESULTADO
      </Button>
    </motion.div>
  );
}

function SalesPage({ name }: { name: string }) {
  const [timeLeft, setTimeLeft] = useState(14 * 60 + 51);

  useEffect(() => {
    const timer = setInterval(() => {
      setTimeLeft((prev) => (prev > 0 ? prev - 1 : 0));
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return {
      mins: mins.toString().padStart(2, "0"),
      secs: secs.toString().padStart(2, "0"),
    };
  };

  const time = formatTime(timeLeft);

  return (
    <motion.div 
      initial={{ opacity: 0 }} 
      animate={{ opacity: 1 }}
      className="min-h-screen bg-slate-50 pb-12"
    >
      <div className="bg-orange-100 text-orange-800 px-4 py-3 text-center text-sm font-medium flex items-center justify-center gap-2">
        <span className="bg-orange-200 text-orange-900 rounded p-1">⚠️</span>
        Atenção {name}, essa é a sua chance única.
      </div>

      <div className="max-w-4xl mx-auto p-4 md:pt-8 text-center">
        <h1 className="text-2xl md:text-4xl font-bold mb-2 text-slate-900">
          Por ter respondido ao nosso quiz, você ganhou <span className="text-green-600">50% de desconto exclusivo</span> na Apostila de Chalé Suíço 🎉
        </h1>
        <p className="text-orange-600 font-medium mb-8 text-sm md:text-base bg-orange-50 inline-block px-4 py-1 rounded-full border border-orange-100 mt-2">
          ⚠️ Esse desconto expira ao sair da página.
        </p>

        <div className="rounded-xl overflow-hidden shadow-2xl border-4 border-white mb-12 max-w-3xl mx-auto relative bg-black aspect-video">
          <iframe 
            src="https://player.vimeo.com/video/1164760318?badge=0&amp;autopause=0&amp;player_id=0&amp;app_id=58479" 
            frameBorder="0" 
            allow="autoplay; fullscreen; picture-in-picture; clipboard-write; encrypted-media" 
            className="absolute inset-0 w-full h-full"
            title="Video de Vendas"
          ></iframe>
        </div>

        <div className="bg-white rounded-2xl shadow-xl p-6 md:p-10 max-w-2xl mx-auto mb-8">
          <h3 className="text-xl font-bold mb-6 text-slate-900">O que você vai receber:</h3>
          <div className="space-y-4 text-left">
            {[
              "Pack completo com +30 projetos de chalés",
              "Plantas baixas detalhadas e profissionais",
              "Projetos em 3D para apresentar a clientes",
              "Guia de materiais e estimativa de custos",
              "Acesso vitalício + atualizações gratuitas",
              "Suporte exclusivo via WhatsApp",
              "Bônus: Planilha de orçamento automática",
              "Bônus: Guia de locação no Airbnb"
            ].map((item, i) => (
              <div key={i} className="flex items-start gap-3">
                <div className="mt-0.5 bg-green-100 rounded-full p-0.5">
                  <Check className="w-4 h-4 text-green-600" strokeWidth={3} />
                </div>
                <span className="text-slate-700">{item}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="text-center mb-6">
          <p className="text-sm text-slate-500 mb-2">Oferta expira em:</p>
          <div className="flex justify-center gap-2 font-mono font-bold text-3xl text-white">
            <div className="bg-[#ef4444] rounded px-3 py-1">{time.mins}</div>
            <span className="text-slate-400 py-1">:</span>
            <div className="bg-[#ef4444] rounded px-3 py-1">{time.secs}</div>
          </div>
        </div>

        <div className="bg-slate-100 rounded-xl p-6 max-w-md mx-auto mb-6 border border-slate-200">
          <p className="text-slate-500 line-through text-sm">De R$ 39,80</p>
          <p className="text-4xl font-black text-[#16a34a] mb-1">R$ 19,90</p>
          <p className="text-xs text-slate-500">Pagamento único, sem mensalidade</p>
        </div>

        <Button 
          size="lg" 
          className="w-full max-w-md bg-[#22c55e] hover:bg-[#16a34a] text-white font-bold text-xl py-8 shadow-lg shadow-green-900/10 mb-8 uppercase tracking-wide"
          onClick={() => window.location.href = 'https://checkout.centralconteudo.site/VCCL1O8SCSEK'}
        >
          COMPRAR COM BÔNUS
        </Button>

        <div className="flex items-center justify-center gap-2 text-slate-500 text-xs bg-slate-50 py-4 rounded-lg">
          <ShieldCheck className="w-4 h-4" />
          <span className="font-bold">Garantia de 7 dias</span>
        </div>
        <p className="text-xs text-slate-400 max-w-md mx-auto mt-2">
          Se por qualquer motivo você não ficar satisfeito, devolvemos 100% do seu dinheiro. Sem perguntas.
        </p>
      </div>
    </motion.div>
  );
}
