'use client';

import { useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import type { WholethingPageData } from '../wholethingConfig';
import { saveSessionChoice } from '../session';
import ProgressBar from './ProgressBar';

interface WholethingSectionProps {
  data: WholethingPageData;
  nextSection?: string;
  slug: string;
}

export default function WholethingSection({ data, nextSection, slug }: WholethingSectionProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const qs = searchParams.toString();
  const suffix = qs ? `?${qs}` : '';
  const [choice, setChoice] = useState<'yes' | 'no' | null>(null);

  const handleClick = async (value: 'yes' | 'no') => {
    if (choice) return;
    setChoice(value);
    await saveSessionChoice(slug, value);
    if (nextSection) {
      setTimeout(() => {
        router.push(`/onboarding/${nextSection}${suffix}`);
      }, 400);
    }
  };

  return (
    <>
      <ProgressBar currentSlug={slug} />
      <main className="wholething-page">
        <div className="wholething-content">
          <h1 className="wholething-question">{data.question}</h1>

          <div className="wholething-image">
            <img src={data.image} alt="" />
          </div>
        </div>

        <div className="wholething-buttons">
          <button
            type="button"
            className={`wholething-btn${choice === 'no' ? ' active' : ''}`}
            onClick={() => handleClick('no')}
            disabled={choice !== null}
          >
            <span className="emoji">👎</span>
            <span>No</span>
          </button>
          <button
            type="button"
            className={`wholething-btn${choice === 'yes' ? ' active' : ''}`}
            onClick={() => handleClick('yes')}
            disabled={choice !== null}
          >
            <span className="emoji">👍</span>
            <span>Yes</span>
          </button>
        </div>
      </main>
    </>
  );
}
