'use client';

import { useEffect, useState, useCallback } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { SECTION_ORDER } from '../sectionConfig';
import { LOADING_REVIEWS, LOADING_QUESTIONS } from '../payloads';
import { saveSessionChoice } from '../session';

const STAR_PATH = 'M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z';

const PROGRESS_STEPS = [
  { label: 'Setting your spiritual goals', targetPct: 100, pauseAt: 50, questionIdx: 0 },
  { label: 'Identifying focus areas', targetPct: 100, pauseAt: 50, questionIdx: 1 },
  { label: 'Picking stories for you', targetPct: 100, pauseAt: 50, questionIdx: null },
];

export default function LoadingPlanSection() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const qs = searchParams.toString();
  const suffix = qs ? `?${qs}` : '';

  const [stepIdx, setStepIdx] = useState(0);
  const [pcts, setPcts] = useState([0, 0, 0]);
  const [reviewIdx, setReviewIdx] = useState(0);
  const [showOverlay, setShowOverlay] = useState(false);
  const [overlayQuestionIdx, setOverlayQuestionIdx] = useState(0);
  const [paused, setPaused] = useState(false);

  const advanceToNext = useCallback(() => {
    const idx = SECTION_ORDER.indexOf('loading-plan');
    const next = SECTION_ORDER[idx + 1];
    if (next) router.push(`/onboarding/${next}${suffix}`);
  }, [router, suffix]);

  useEffect(() => {
    if (paused) return;

    const interval = setInterval(() => {
      setPcts((prev) => {
        const step = PROGRESS_STEPS[stepIdx];
        if (!step) return prev;

        const current = prev[stepIdx];
        if (current >= step.targetPct) return prev;
        if (step.pauseAt !== null && current === step.pauseAt) return prev;

        const increment = Math.random() * 3 + 1;
        let next = Math.min(current + increment, step.targetPct);

        if (step.pauseAt !== null && current < step.pauseAt && next >= step.pauseAt) {
          next = step.pauseAt;
        }

        if (next === current) return prev;

        const updated = [...prev];
        updated[stepIdx] = next;
        return updated;
      });
    }, 80);

    return () => clearInterval(interval);
  }, [stepIdx, paused]);

  useEffect(() => {
    const step = PROGRESS_STEPS[stepIdx];
    if (!step) return;
    if (paused || showOverlay) return;

    const current = pcts[stepIdx];

    if (step.pauseAt !== null && current === step.pauseAt) {
      if (stepIdx === PROGRESS_STEPS.length - 1) {
        const timer = setTimeout(advanceToNext, 400);
        return () => clearTimeout(timer);
      }
      setOverlayQuestionIdx(step.questionIdx!);
      setShowOverlay(true);
      setPaused(true);
      return;
    }

    if (current >= step.targetPct) {
      if (stepIdx < PROGRESS_STEPS.length - 1) {
        setStepIdx((s) => s + 1);
        setReviewIdx((r) => Math.min(r + 1, LOADING_REVIEWS.length - 1));
      } else {
        const timer = setTimeout(advanceToNext, 1500);
        return () => clearTimeout(timer);
      }
    }
  }, [pcts, stepIdx, paused, showOverlay, advanceToNext]);

  const handleOverlayAnswer = async (answer: 'yes' | 'no') => {
    await saveSessionChoice(`loading-q${overlayQuestionIdx}`, answer);
    setPcts((prev) => {
      const step = PROGRESS_STEPS[stepIdx];
      if (step?.pauseAt == null) return prev;
      const updated = [...prev];
      updated[stepIdx] = Math.min(step.pauseAt + 0.1, step.targetPct);
      return updated;
    });
    setShowOverlay(false);
    setPaused(false);
  };

  const review = LOADING_REVIEWS[reviewIdx];

  return (
    <main className="loading-page">
      <h1 className="loading-title">
        We&apos;re preparing your<br />personalized Quranic story plan...
      </h1>

      <div className="loading-progress-list">
        {PROGRESS_STEPS.map((step, i) => (
          <div key={i} className="loading-progress-item">
            <div className="loading-progress-header">
              <span className={`loading-progress-label${i > stepIdx ? ' inactive' : ''}`}>
                {step.label}
              </span>
              <span className={`loading-progress-pct${i > stepIdx ? ' inactive' : ''}`}>
                {Math.round(pcts[i])}%
              </span>
            </div>
            <div className="loading-progress-bar">
              <div
                className="loading-progress-fill"
                style={{ width: `${pcts[i]}%` }}
              />
            </div>
          </div>
        ))}
      </div>

      <div className="loading-review-card">
        <div className="loading-review-header">
          <div className="loading-review-author">
            <span className="loading-review-name">
              {review.name}, {review.age}
            </span>
            <span className="loading-review-date">
              {review.daysAgo} days ago
            </span>
          </div>
          <div className="loading-review-badge">
            <div className="loading-review-stars">
              {[...Array(5)].map((_, i) => (
                <span key={i} className="loading-review-star">
                  <svg viewBox="0 0 24 24">
                    <path d={STAR_PATH} fill="white" />
                  </svg>
                </span>
              ))}
            </div>
            <span className="loading-review-verified">VERIFIED</span>
          </div>
        </div>
        <p className="loading-review-text">
          {review.text}
          {review.reactions && (
            <span className="loading-review-reactions">{review.reactions}</span>
          )}
        </p>
      </div>

      {showOverlay && (
        <div className="loading-overlay">
          <p className="loading-overlay-prompt">
            {LOADING_QUESTIONS[overlayQuestionIdx]?.prompt}
          </p>
          <h2 className="loading-overlay-question">
            {LOADING_QUESTIONS[overlayQuestionIdx]?.question}
          </h2>
          <div className="loading-overlay-buttons">
            <button
              type="button"
              className="wholething-btn"
              onClick={() => handleOverlayAnswer('no')}
            >
              <span className="emoji">👎</span>
              <span>No</span>
            </button>
            <button
              type="button"
              className="wholething-btn"
              onClick={() => handleOverlayAnswer('yes')}
            >
              <span className="emoji">👍</span>
              <span>Yes</span>
            </button>
          </div>
        </div>
      )}
    </main>
  );
}
