'use client';

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

interface TopicsSectionPickerProps {
  section: TopicSection;
  nextSection?: string;
  slug: string;
}

export default function TopicsSectionPicker({ section, nextSection, slug }: TopicsSectionPickerProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const qs = searchParams.toString();
  const suffix = qs ? `?${qs}` : '';
  const [selected, setSelected] = useState<string[]>([]);
  const [saving, setSaving] = useState(false);

  const toggle = (id: string) => {
    setSelected((prev) =>
      prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
    );
  };

  const handleContinue = async () => {
    if (!selected.length || !nextSection) return;
    setSaving(true);
    await saveSessionChoice(slug, selected);
    router.push(`/onboarding/${nextSection}${suffix}`);
  };

  return (
    <>
      <ProgressBar currentSlug={slug} />
      <main className="topics-page">
        <div className="topics-header">
          <h1 className="topics-title">{section.title}</h1>
          <p className="topics-subtitle">{section.subtitle}</p>
        </div>

        <div className="topics-list">
          {section.topics.map((topic) => {
            const isSelected = selected.includes(topic.id);
            return (
              <button
                key={topic.id}
                type="button"
                className={`topic-option${isSelected ? ' selected' : ''}`}
                onClick={() => toggle(topic.id)}
              >
                <span>{topic.label}</span>
                <span className="topic-checkbox">
                  <span className="topic-checkbox-check" />
                </span>
              </button>
            );
          })}
        </div>

        <div className="topics-footer">
          <button
            type="button"
            className="cta-gold"
            disabled={!selected.length || saving}
            onClick={handleContinue}
          >
            Continue
          </button>
        </div>
      </main>
    </>
  );
}
