'use client';

import { ArrowLeft, ArrowRight, Check, RotateCcw, Sparkles } from 'lucide-react';
import { useMemo, useState } from 'react';
import { AddToCartButton } from '@/components/add-to-cart-button';
import { Breadcrumbs } from '@/components/breadcrumbs';
import { useI18n } from '@/lib/i18n';
import { translateProduct } from '@/lib/i18n-content';
import { formatVnd } from '@/lib/format';
import type { Catalog, Product } from '@/lib/types';

type QuestionId = 'experience' | 'project' | 'pace' | 'budget';
type Answers = Partial<Record<QuestionId, string>>;

const questions: Array<{
  id: QuestionId;
  promptKey: string;
  options: Array<{ value: string; labelKey: string }>;
}> = [
  {
    id: 'experience',
    promptKey: 'quiz.question.experience',
    options: [
      { value: 'beginner', labelKey: 'quiz.option.experience.beginner' },
      { value: 'some', labelKey: 'quiz.option.experience.some' },
    ],
  },
  {
    id: 'project',
    promptKey: 'quiz.question.project',
    options: [
      { value: 'flower', labelKey: 'quiz.option.project.flower' },
      { value: 'coaster', labelKey: 'quiz.option.project.coaster' },
      { value: 'keychain', labelKey: 'quiz.option.project.keychain' },
      { value: 'tools', labelKey: 'quiz.option.project.tools' },
    ],
  },
  {
    id: 'pace',
    promptKey: 'quiz.question.pace',
    options: [
      { value: 'quick', labelKey: 'quiz.option.pace.quick' },
      { value: 'calm', labelKey: 'quiz.option.pace.calm' },
    ],
  },
  {
    id: 'budget',
    promptKey: 'quiz.question.budget',
    options: [
      { value: 'low', labelKey: 'quiz.option.budget.low' },
      { value: 'standard', labelKey: 'quiz.option.budget.standard' },
    ],
  },
];

const projectProductIds: Record<string, string> = {
  flower: 'kit-hoa-len',
  coaster: 'kit-de-lot-ly',
  keychain: 'kit-moc-khoa',
  tools: 'kit-co-ban',
};

function scoreProduct(product: Product, answers: Answers) {
  let score = product.categorySlug === 'bo-kit-nguoi-moi' ? 2 : 0;
  const preferredProductId = projectProductIds[answers.project ?? ''];
  if (product.id === preferredProductId) score += 8;
  if (answers.experience === 'beginner' && product.level === 'Mới bắt đầu') score += 3;
  if (answers.experience === 'some' && product.categorySlug === 'bo-kit-nguoi-moi') score += 1;
  if (answers.pace === 'quick' && ['kit-moc-khoa', 'kit-hoa-len'].includes(product.id)) score += 3;
  if (answers.pace === 'calm' && ['kit-co-ban', 'kit-de-lot-ly'].includes(product.id)) score += 3;
  if (answers.budget === 'low' && product.price <= 200000) score += 3;
  if (answers.budget === 'standard' && product.price > 200000) score += 2;
  return score;
}

export function KitQuizPage({ catalog }: { catalog: Catalog }) {
  const { language, t } = useI18n();
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState<Answers>({});

  const recommendations = useMemo(() => {
    return [...catalog.products]
      .sort((a, b) => scoreProduct(b, answers) - scoreProduct(a, answers) || a.price - b.price)
      .filter((product) => product.categorySlug === 'bo-kit-nguoi-moi')
      .slice(0, 3);
  }, [answers, catalog.products]);

  function choose(value: string) {
    const question = questions[step];
    if (!question) return;
    setAnswers((current) => ({ ...current, [question.id]: value }));
  }

  function next() {
    if (!answers[questions[step]?.id]) return;
    setStep((current) => Math.min(current + 1, questions.length));
  }

  function previous() {
    setStep((current) => Math.max(current - 1, 0));
  }

  function reset() {
    setAnswers({});
    setStep(0);
  }

  const question = questions[step];
  const isResult = step >= questions.length;
  const progress = isResult ? 100 : ((step + 1) / questions.length) * 100;

  return (
    <>
      <div className="page-container"><Breadcrumbs items={[{ name: 'Trang chủ', href: '/' }, { name: 'Chọn bộ kit' }]} /></div>
      <section className="page-intro tool-page-intro">
        <div className="page-container">
          <span className="eyebrow">{t('quiz.eyebrow')}</span>
          <h1>{t('quiz.title')}</h1>
          <p>{t('quiz.description')}</p>
        </div>
      </section>

      <section className="tool-section">
        <div className="page-container">
          {!isResult && question ? (
            <div className="quiz-panel">
              <div className="quiz-progress-row">
                <span>{t('quiz.progress', { current: step + 1, total: questions.length })}</span>
                <span>{Math.round(progress)}%</span>
              </div>
              <div className="quiz-progress"><span style={{ width: `${progress}%` }} /></div>
              <div className="quiz-question" key={question.id}>
                <span className="tool-step-number">0{step + 1}</span>
                <h2>{t(question.promptKey)}</h2>
                <div className={`quiz-options${question.options.length > 2 ? ' is-four' : ''}`}>
                  {question.options.map((option) => {
                    const selected = answers[question.id] === option.value;
                    return (
                      <button key={option.value} type="button" className={`quiz-option${selected ? ' is-selected' : ''}`} aria-pressed={selected} onClick={() => choose(option.value)}>
                        <span className="quiz-option-check">{selected ? <Check size={15} aria-hidden="true" /> : null}</span>
                        <span>{t(option.labelKey)}</span>
                      </button>
                    );
                  })}
                </div>
              </div>
              <div className="quiz-actions">
                <button className="button-quiet" type="button" onClick={previous} disabled={step === 0}><ArrowLeft size={16} aria-hidden="true" /> {t('quiz.previous')}</button>
                <button className="button-primary" type="button" onClick={next} disabled={!answers[question.id]}>{t('quiz.next')} <ArrowRight size={16} aria-hidden="true" /></button>
              </div>
            </div>
          ) : (
            <div className="quiz-result">
              <div className="tool-result-heading">
                <span className="eyebrow"><Sparkles size={14} aria-hidden="true" /> {t('quiz.resultEyebrow')}</span>
                <h2>{t('quiz.resultTitle')}</h2>
                <p>{t('quiz.resultDescription')}</p>
              </div>
              {recommendations.length > 0 ? (
                <div className="recommendation-grid">
                  {recommendations.map((product, index) => {
                    const localizedProduct = translateProduct(product, language);
                    return (
                      <article className={`recommendation-card${index === 0 ? ' is-best' : ''}`} key={product.id}>
                        {index === 0 ? <span className="recommendation-badge">{language === 'en' ? 'Best match' : 'Hợp nhất'}</span> : null}
                        <img src={localizedProduct.image} alt={localizedProduct.alt} loading="lazy" />
                        <div className="recommendation-content">
                          <span className="product-card-meta">{localizedProduct.level}</span>
                          <h3>{localizedProduct.name}</h3>
                          <p>{localizedProduct.shortDescription}</p>
                          <div className="recommendation-bottom">
                            <strong>{formatVnd(localizedProduct.price)}</strong>
                            <AddToCartButton productId={product.id} compact label={t('quiz.addKit')} />
                          </div>
                          <a className="article-card-link" href={`/san-pham/${localizedProduct.slug}`}>{t('quiz.viewKit')} <ArrowRight size={14} aria-hidden="true" /></a>
                        </div>
                      </article>
                    );
                  })}
                </div>
              ) : <div className="empty-state"><p>{t('quiz.noProducts')}</p></div>}
              <button className="button-secondary quiz-reset" type="button" onClick={reset}><RotateCcw size={16} aria-hidden="true" /> {t('quiz.startOver')}</button>
            </div>
          )}
        </div>
      </section>
    </>
  );
}
