import { useState, useEffect } from 'react';
import { getBrandLogo } from './BrandLogos';

interface QuizResult {
  id: string;
  slug: string;
  name: string;
  brand: string;
  price: number;
  image: string;
}

// Inline SVG icon components
const icons: Record<string, JSX.Element> = {
  sneaker: (
    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2 18h20v1a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-1Z" />
      <path d="M2 18l1.2-4.8A2 2 0 0 1 5.1 12h1.4l1 2h4l.8-2.4a2 2 0 0 1 1.9-1.4l5.6-.2a2 2 0 0 1 2 1.7L22 18" />
      <path d="M6 12V8a2 2 0 0 1 2-2h1" />
    </svg>
  ),
  flame: (
    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z" />
    </svg>
  ),
  bolt: (
    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />
    </svg>
  ),
  sparkle: (
    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 3l1.912 5.813a2 2 0 0 0 1.275 1.275L21 12l-5.813 1.912a2 2 0 0 0-1.275 1.275L12 21l-1.912-5.813a2 2 0 0 0-1.275-1.275L3 12l5.813-1.912a2 2 0 0 0 1.275-1.275L12 3z" />
    </svg>
  ),
  tag: (
    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z" />
      <circle cx="7.5" cy="7.5" r=".5" fill="currentColor" />
    </svg>
  ),
  euro: (
    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4 10h12M4 14h12M17.5 7.5C16.5 5.5 14.5 4 12 4 8.13 4 5 7.13 5 11v2c0 3.87 3.13 7 7 7 2.5 0 4.5-1.5 5.5-3.5" />
    </svg>
  ),
  diamond: (
    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 3h12l4 6-10 13L2 9z" />
      <path d="M2 9h20" />
      <path d="M10 3l-4 6 6 13 6-13-4-6" />
    </svg>
  ),
  arrowUp: (
    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 19V5M5 12l7-7 7 7" />
    </svg>
  ),
  check: (
    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 6 9 17 4 12" />
    </svg>
  ),
  shuffle: (
    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="16 3 21 3 21 8" />
      <line x1="4" y1="20" x2="21" y2="3" />
      <polyline points="21 16 21 21 16 21" />
      <line x1="15" y1="15" x2="21" y2="21" />
      <line x1="4" y1="4" x2="9" y2="9" />
    </svg>
  ),
  target: (
    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="10" />
      <circle cx="12" cy="12" r="6" />
      <circle cx="12" cy="12" r="2" />
    </svg>
  ),
  checkCircle: (
    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
      <polyline points="22 4 12 14.01 9 11.01" />
    </svg>
  ),
};

interface StepOption {
  label: string;
  value: string;
  icon: string;
  logo?: string;
}

interface Step {
  question: string;
  options: StepOption[];
  gridClass?: string;
  buttonClass?: string;
}

const STEPS: Step[] = [
  {
    question: 'Wat is jouw stijl?',
    options: [
      { label: 'Casual & Relaxed', value: 'casual', icon: 'sneaker' },
      { label: 'Streetwear', value: 'streetwear', icon: 'flame' },
      { label: 'Sportief', value: 'sportief', icon: 'bolt' },
      { label: 'Minimalistisch', value: 'minimalistisch', icon: 'sparkle' },
    ],
  },
  {
    question: 'Wat is je budget?',
    options: [
      { label: 'Onder \u20AC75', value: '75', icon: 'tag' },
      { label: '\u20AC75 - \u20AC125', value: '125', icon: 'euro' },
      { label: '\u20AC125 - \u20AC200', value: '200', icon: 'diamond' },
      { label: 'Maakt niet uit', value: '999', icon: 'arrowUp' },
    ],
  },
  {
    question: 'Welk merk spreekt je aan?',
    options: [
      { label: 'Nike', value: 'nike', icon: 'check', logo: 'nike' },
      { label: 'Adidas', value: 'adidas', icon: 'check', logo: 'adidas' },
      { label: 'New Balance', value: 'new-balance', icon: 'check', logo: 'new-balance' },
      { label: 'Verrras me!', value: 'any', icon: 'shuffle' },
    ],
  },
  {
    question: 'Wat is jouw maat?',
    gridClass: 'grid-cols-3 sm:grid-cols-7',
    buttonClass: 'p-3',
    options: [
      { label: '38', value: '38', icon: 'tag' },
      { label: '40', value: '40', icon: 'tag' },
      { label: '42', value: '42', icon: 'tag' },
      { label: '44', value: '44', icon: 'tag' },
      { label: '43', value: '43', icon: 'tag' },
      { label: '45', value: '45', icon: 'tag' },
      { label: 'Geen voorkeur', value: 'any', icon: 'shuffle' },
    ],
  },
];

export default function StyleQuiz() {
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState<string[]>([]);
  const [results, setResults] = useState<QuizResult[]>([]);
  const [loading, setLoading] = useState(false);
  const [started, setStarted] = useState(false);

  const handleAnswer = async (value: string) => {
    const newAnswers = [...answers, value];
    setAnswers(newAnswers);

    if (step < STEPS.length - 1) {
      setStep(step + 1);
    } else {
      // Final step — fetch results
      setLoading(true);
      try {
        const [style, budget, brand, size] = newAnswers;
        let url = `/api/quiz?style=${style}`;
        if (brand !== 'any') url += `&brand=${brand}`;
        if (budget !== '999') url += `&maxPrice=${budget}`;
        if (size && size !== 'any') url += `&size=${size}`;

        const res = await fetch(url);
        if (res.ok) {
          const data = await res.json();
          setResults(data.slice(0, 6));
        }
      } catch {}
      setLoading(false);
      setStep(STEPS.length);
    }
  };

  // Save quiz answers when results are loaded
  useEffect(() => {
    if (step >= STEPS.length && !loading && answers.length === STEPS.length) {
      const [style, budget, brand, size] = answers;
      fetch('/api/user/save-quiz', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          style: style !== 'any' ? style : null,
          budget: budget !== '999' ? budget : null,
          brand: brand !== 'any' ? brand : null,
          size: size !== 'any' ? size : null,
        }),
      }).catch(err => console.error('Failed to save quiz answers:', err));
    }
  }, [step, loading, answers]);

  const reset = () => {
    setStep(0);
    setAnswers([]);
    setResults([]);
    setStarted(false);
  };

  if (!started) {
    return (
      <section className="mx-auto max-w-7xl px-4 py-12 sm:px-6">
        <div className="rounded-3xl border border-[var(--border)]/50 bg-gradient-to-br from-[var(--bg-elevated)] to-[var(--bg-card)] p-6 text-center sm:p-12">
          <div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-[var(--accent)]/10 text-[var(--accent)]">
            {icons.target}
          </div>
          <h2 className="text-2xl font-black text-[var(--text)]">Welke sneaker past bij jou?</h2>
          <p className="mt-2 text-sm text-[var(--text-secondary)]">
            Beantwoord 4 vragen en ontdek jouw perfecte sneaker match
          </p>
          <button
            onClick={() => setStarted(true)}
            className="mt-6 rounded-xl bg-[var(--accent)] px-8 py-3 font-bold text-[var(--bg)] transition-all hover:shadow-lg hover:shadow-[var(--accent)]/20"
          >
            Start de quiz
          </button>
        </div>
      </section>
    );
  }

  // Show results
  if (step >= STEPS.length) {
    return (
      <section className="mx-auto max-w-7xl px-4 py-12 sm:px-6">
        <div className="rounded-3xl border border-[var(--border)]/50 bg-[var(--bg-card)] p-5 sm:p-12">
          <div className="text-center mb-8">
            <div className="mx-auto mb-3 flex h-14 w-14 items-center justify-center rounded-2xl bg-[var(--accent)]/10 text-[var(--accent)]">
              {icons.checkCircle}
            </div>
            <h2 className="text-2xl font-black text-[var(--text)]">Jouw sneaker matches!</h2>
            <p className="mt-1 text-sm text-[var(--text-secondary)]">Op basis van jouw voorkeuren</p>
          </div>

          {loading ? (
            <div className="flex justify-center py-8">
              <div className="h-8 w-8 animate-spin rounded-full border-2 border-[var(--accent)] border-t-transparent"></div>
            </div>
          ) : results.length > 0 ? (
            <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-6">
              {results.map(r => (
                <a
                  key={r.id}
                  href={`/sneakers/${r.slug}`}
                  className="group rounded-2xl border border-[var(--border)]/50 bg-[var(--bg-elevated)] p-3 transition-all hover:border-[var(--accent)]/30 hover:shadow-md"
                >
                  <div className="aspect-square overflow-hidden rounded-xl bg-[var(--bg-card)]">
                    <img
                      src={`/api/img/${r.id}`}
                      alt={`${r.brand} ${r.name}`}
                      className="h-full w-full object-contain transition-transform group-hover:scale-110"
                      loading="lazy"
                    />
                  </div>
                  <div className="mt-2">
                    <p className="text-[10px] font-bold uppercase tracking-widest text-[var(--text-muted)]">{r.brand}</p>
                    <p className="text-xs font-semibold text-[var(--text)] leading-tight truncate">{r.name}</p>
                    <p className="text-sm font-black text-[var(--accent)] mt-1">{'\u20AC'}{r.price.toFixed(2).replace('.', ',')}</p>
                  </div>
                </a>
              ))}
            </div>
          ) : (
            <p className="text-center text-sm text-[var(--text-muted)]">Geen exacte matches gevonden. <a href="/sneakers" className="text-[var(--accent)] hover:underline">Bekijk alle sneakers</a></p>
          )}

          <div className="mt-8 text-center">
            <button
              onClick={reset}
              className="text-sm font-semibold text-[var(--accent)] hover:underline"
            >
              Opnieuw proberen
            </button>
          </div>
        </div>
      </section>
    );
  }

  // Quiz step
  const current = STEPS[step];
  return (
    <section className="mx-auto max-w-7xl px-4 py-12 sm:px-6">
      <div className="rounded-3xl border border-[var(--border)]/50 bg-[var(--bg-card)] p-5 sm:p-12">
        {/* Progress */}
        <div className="mb-8 flex gap-2">
          {STEPS.map((_, i) => (
            <div
              key={i}
              className={`h-1.5 flex-1 rounded-full transition-colors ${
                i <= step ? 'bg-[var(--accent)]' : 'bg-[var(--bg-elevated)]'
              }`}
            />
          ))}
        </div>

        <div className="text-center mb-8">
          <p className="text-xs font-bold uppercase tracking-widest text-[var(--text-muted)] mb-2">
            Vraag {step + 1} van {STEPS.length}
          </p>
          <h2 className="text-2xl font-black text-[var(--text)]">{current.question}</h2>
        </div>

        <div className={`grid gap-3 max-w-2xl mx-auto ${current.gridClass ?? 'grid-cols-2 sm:grid-cols-4'}`}>
          {current.options.map(opt => (
            <button
              key={opt.value}
              onClick={() => handleAnswer(opt.value)}
              className={`flex flex-col items-center gap-2 rounded-2xl border border-[var(--border)]/50 bg-[var(--bg-elevated)] transition-all hover:border-[var(--accent)]/50 hover:shadow-md hover:shadow-[var(--accent)]/5 active:scale-95 text-[var(--text-muted)] ${current.buttonClass ?? 'p-4 sm:p-5'}`}
            >
              {opt.logo ? (
                <div
                  className="h-8 w-full flex items-center justify-center text-[var(--text)]"
                  dangerouslySetInnerHTML={{ __html: getBrandLogo(opt.logo) ?? '' }}
                />
              ) : (
                <span className="text-[var(--accent)]">{icons[opt.icon]}</span>
              )}
              <span className="text-sm font-semibold text-[var(--text)]">{opt.label}</span>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}
