/**
 * Multi-page survey component.
 *
 * ✅ YOUR CODE - Safe to modify, will not be overwritten.
 * This file was generated once by Prism and is yours to customize.
 *
 * Features:
 *  - Paginated question groups with a progress bar
 *  - Question types: multiple_choice, text, yes_no
 *  - Final page collects contact details
 *  - Submit handler ready to wire to your API
 */

import { useState, useCallback, useMemo } from 'react';
import type { JSX, FormEvent } from 'react';
import { Link } from 'react-router-dom';
{% if dark_mode %}import { ThemeToggle } from '../ui/ThemeToggle';
{% endif %}
const APP_NAME = "{{ project_title }}";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

type QuestionType = 'multiple_choice' | 'text' | 'yes_no';

interface Question {
  id: string;
  label: string;
  type: QuestionType;
  required?: boolean;
  /** Options for multiple_choice questions */
  options?: string[];
  /** Placeholder for text questions */
  placeholder?: string;
}

interface QuestionGroup {
  title: string;
  description?: string;
  questions: Question[];
}

interface ContactDetails {
  name: string;
  email: string;
  company: string;
  phone: string;
}

// ---------------------------------------------------------------------------
// Sample survey definition — customise to suit your needs
// ---------------------------------------------------------------------------

const SURVEY_GROUPS: QuestionGroup[] = [
  {
    title: 'About You',
    description: 'Help us understand your background.',
    questions: [
      {
        id: 'role',
        label: 'What best describes your role?',
        type: 'multiple_choice',
        required: true,
        options: ['Developer', 'Designer', 'Product Manager', 'Executive', 'Other'],
      },
      {
        id: 'experience',
        label: 'How many years of experience do you have?',
        type: 'multiple_choice',
        required: true,
        options: ['0-1', '2-5', '6-10', '10+'],
      },
    ],
  },
  {
    title: 'Your Needs',
    description: 'Tell us what you are looking for.',
    questions: [
      {
        id: 'use_case',
        label: 'What would you primarily use this product for?',
        type: 'text',
        required: true,
        placeholder: 'Describe your main use-case…',
      },
      {
        id: 'team_size',
        label: 'Do you work in a team of more than 5 people?',
        type: 'yes_no',
        required: true,
      },
    ],
  },
  {
    title: 'Feedback',
    description: 'We value your opinion.',
    questions: [
      {
        id: 'satisfaction',
        label: 'How satisfied are you with current solutions?',
        type: 'multiple_choice',
        required: true,
        options: ['Very satisfied', 'Satisfied', 'Neutral', 'Dissatisfied', 'Very dissatisfied'],
      },
      {
        id: 'comments',
        label: 'Any additional comments?',
        type: 'text',
        placeholder: 'Share your thoughts…',
      },
    ],
  },
];

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export default function SurveyPage(): JSX.Element {
  // Current page index: 0..N-1 = question groups, N = contact page
  const totalPages = SURVEY_GROUPS.length + 1; // +1 for contact details
  const [currentPage, setCurrentPage] = useState(0);

  // Answers keyed by question id
  const [answers, setAnswers] = useState<Record<string, string>>({});

  // Contact details (last page)
  const [contact, setContact] = useState<ContactDetails>({
    name: '',
    email: '',
    company: '',
    phone: '',
  });

  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [validationError, setValidationError] = useState<string | null>(null);

  // ---- helpers ----

  const setAnswer = useCallback((id: string, value: string) => {
    setAnswers((prev) => ({ ...prev, [id]: value }));
    setValidationError(null);
  }, []);

  const isContactPage = currentPage === SURVEY_GROUPS.length;

  /** Validate required questions on the current question-group page. */
  const validateCurrentPage = useCallback((): boolean => {
    if (isContactPage) {
      if (!contact.name.trim() || !contact.email.trim()) {
        setValidationError('Name and email are required.');
        return false;
      }
      return true;
    }
    const group = SURVEY_GROUPS[currentPage];
    for (const q of group.questions) {
      if (q.required && !answers[q.id]?.trim()) {
        setValidationError(`Please answer: "${q.label}"`);
        return false;
      }
    }
    return true;
  }, [currentPage, answers, contact, isContactPage]);

  const handleNext = useCallback(() => {
    if (!validateCurrentPage()) return;
    setValidationError(null);
    setCurrentPage((p) => Math.min(p + 1, totalPages - 1));
  }, [validateCurrentPage, totalPages]);

  const handlePrev = useCallback(() => {
    setValidationError(null);
    setCurrentPage((p) => Math.max(p - 1, 0));
  }, []);

  const handleSubmit = useCallback(
    async (e: FormEvent) => {
      e.preventDefault();
      if (!validateCurrentPage()) return;
      setSubmitting(true);
      // TODO: Wire up to your backend API endpoint
      // await fetch('/api/v1/surveys', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify({ answers, contact }),
      // });
      await new Promise((resolve) => setTimeout(resolve, 1000));
      setSubmitted(true);
      setSubmitting(false);
    },
    [validateCurrentPage, answers, contact],
  );

  // ---- progress ----

  const progressPct = useMemo(
    () => Math.round(((currentPage + 1) / totalPages) * 100),
    [currentPage, totalPages],
  );

  // ---- submitted state ----

  if (submitted) {
    return (
      <SurveyShell>
        <div className="max-w-xl mx-auto px-4 py-20 text-center">
          <div className="card p-10 rounded-lg">
            <div className="w-16 h-16 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg className="w-8 h-8 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <h2 className="text-2xl font-bold text-foreground">Thank you!</h2>
            <p className="mt-3 text-muted">Your survey response has been submitted successfully.</p>
            <Link to="/" className="inline-block mt-8 btn-primary px-6 py-2 rounded-md">
              Back to Home
            </Link>
          </div>
        </div>
      </SurveyShell>
    );
  }

  // ---- render ----

  return (
    <SurveyShell>
      <div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* Progress bar */}
        <div className="mb-10">
          <div className="flex items-center justify-between text-sm text-muted mb-2">
            <span>Page {currentPage + 1} of {totalPages}</span>
            <span>{progressPct}% complete</span>
          </div>
          <div className="w-full h-2 bg-surface-sunken rounded-full overflow-hidden">
            <div
              className="h-full bg-primary rounded-full transition-all duration-300"
              style={% raw %}{{ width: `${progressPct}%` }}{% endraw %}
            />
          </div>
        </div>

        <form onSubmit={handleSubmit}>
          {/* Question group pages */}
          {!isContactPage && (
            <QuestionGroupCard
              group={SURVEY_GROUPS[currentPage]}
              answers={answers}
              setAnswer={setAnswer}
            />
          )}

          {/* Contact details page */}
          {isContactPage && (
            <div className="card p-8 rounded-lg">
              <h2 className="text-2xl font-bold text-foreground">Contact Details</h2>
              <p className="mt-2 text-muted mb-6">
                Finally, let us know how to reach you.
              </p>
              <div className="space-y-5">
                <InputField
                  id="contact-name"
                  label="Name"
                  required
                  value={contact.name}
                  onChange={(v) => { setContact((p) => ({ ...p, name: v })); setValidationError(null); }}
                  placeholder="Your name"
                />
                <InputField
                  id="contact-email"
                  label="Email"
                  required
                  type="email"
                  value={contact.email}
                  onChange={(v) => { setContact((p) => ({ ...p, email: v })); setValidationError(null); }}
                  placeholder="you@example.com"
                />
                <InputField
                  id="contact-company"
                  label="Company"
                  value={contact.company}
                  onChange={(v) => setContact((p) => ({ ...p, company: v }))}
                  placeholder="Your company (optional)"
                />
                <InputField
                  id="contact-phone"
                  label="Phone"
                  type="tel"
                  value={contact.phone}
                  onChange={(v) => setContact((p) => ({ ...p, phone: v }))}
                  placeholder="Phone number (optional)"
                />
              </div>
            </div>
          )}

          {/* Validation error */}
          {validationError && (
            <p className="mt-4 text-sm text-red-600 dark:text-red-400">{validationError}</p>
          )}

          {/* Navigation */}
          <div className="mt-8 flex items-center justify-between">
            <button
              type="button"
              onClick={handlePrev}
              disabled={currentPage === 0}
              className="btn-ghost px-5 py-2 rounded-md text-sm disabled:opacity-30 disabled:cursor-not-allowed"
            >
              &larr; Previous
            </button>

            {isContactPage ? (
              <button
                type="submit"
                disabled={submitting}
                className="btn-primary px-8 py-2 rounded-md font-medium disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {submitting ? 'Submitting…' : 'Submit Survey'}
              </button>
            ) : (
              <button
                type="button"
                onClick={handleNext}
                className="btn-primary px-6 py-2 rounded-md text-sm"
              >
                Next &rarr;
              </button>
            )}
          </div>
        </form>
      </div>
    </SurveyShell>
  );
}

// ---------------------------------------------------------------------------
// Sub-components
// ---------------------------------------------------------------------------

/** Shared page shell with header + footer. */
function SurveyShell({ children }: { children: React.ReactNode }): JSX.Element {
  return (
    <div className="min-h-screen bg-surface text-foreground flex flex-col">
      {/* Header */}
      <header className="sticky top-0 z-50 bg-surface-elevated/80 backdrop-blur border-b border-border">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex items-center justify-between h-16">
          <Link to="/" className="flex items-center gap-2">
            <div className="w-8 h-8 bg-primary rounded-md flex items-center justify-center">
              <span className="text-white font-bold text-sm">{APP_NAME.charAt(0).toUpperCase()}</span>
            </div>
            <span className="font-semibold text-foreground">{APP_NAME}</span>
          </Link>
          <div className="flex items-center gap-3">
{% if dark_mode %}            <ThemeToggle size="sm" />
{% endif %}            <Link to="/" className="btn-ghost text-sm px-4 py-2">Home</Link>
          </div>
        </div>
      </header>

      {/* Content */}
      <main className="flex-1">{children}</main>

      {/* Footer */}
      <footer className="border-t border-border py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex flex-col sm:flex-row items-center justify-between gap-4">
          <div className="flex items-center gap-2">
            <div className="w-6 h-6 bg-primary rounded-md flex items-center justify-center">
              <span className="text-white font-bold text-xs">{APP_NAME.charAt(0).toUpperCase()}</span>
            </div>
            <span className="text-sm font-medium text-foreground">{APP_NAME}</span>
          </div>
          <p className="text-xs text-muted">&copy; {new Date().getFullYear()} {APP_NAME}. All rights reserved.</p>
        </div>
      </footer>
    </div>
  );
}

/** Renders a single group of questions inside a card. */
function QuestionGroupCard({
  group,
  answers,
  setAnswer,
}: {
  group: QuestionGroup;
  answers: Record<string, string>;
  setAnswer: (id: string, value: string) => void;
}): JSX.Element {
  return (
    <div className="card p-8 rounded-lg">
      <h2 className="text-2xl font-bold text-foreground">{group.title}</h2>
      {group.description && (
        <p className="mt-2 text-muted">{group.description}</p>
      )}
      <div className="mt-6 space-y-8">
        {group.questions.map((q) => (
          <QuestionField key={q.id} question={q} value={answers[q.id] ?? ''} onChange={(v) => setAnswer(q.id, v)} />
        ))}
      </div>
    </div>
  );
}

/** Renders a single question based on its type. */
function QuestionField({
  question,
  value,
  onChange,
}: {
  question: Question;
  value: string;
  onChange: (value: string) => void;
}): JSX.Element {
  const { id, label, type, required, options, placeholder } = question;

  return (
    <fieldset>
      <legend className="block text-sm font-medium text-foreground mb-2">
        {label}
        {required && <span className="text-red-500 ml-1">*</span>}
      </legend>

      {/* Multiple choice */}
      {type === 'multiple_choice' && options && (
        <div className="space-y-2">
          {options.map((opt) => (
            <label
              key={opt}
              className={`flex items-center gap-3 px-4 py-3 border rounded-md cursor-pointer transition-colors ${
                value === opt
                  ? 'border-primary bg-primary/5'
                  : 'border-border hover:border-primary/30'
              }`}
            >
              <input
                type="radio"
                name={id}
                value={opt}
                checked={value === opt}
                onChange={() => onChange(opt)}
                className="accent-primary"
              />
              <span className="text-sm text-foreground">{opt}</span>
            </label>
          ))}
        </div>
      )}

      {/* Text / textarea */}
      {type === 'text' && (
        <textarea
          id={id}
          rows={3}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder ?? ''}
          className="w-full px-4 py-2 border border-border rounded-md bg-surface text-foreground placeholder:text-muted focus:outline-none focus:ring-2 focus:ring-primary/50 resize-y"
        />
      )}

      {/* Yes / No */}
      {type === 'yes_no' && (
        <div className="flex gap-4">
          {['Yes', 'No'].map((opt) => (
            <button
              key={opt}
              type="button"
              onClick={() => onChange(opt)}
              className={`flex-1 py-3 border rounded-md text-sm font-medium transition-colors ${
                value === opt
                  ? 'border-primary bg-primary/5 text-primary'
                  : 'border-border text-muted hover:border-primary/30'
              }`}
            >
              {opt}
            </button>
          ))}
        </div>
      )}
    </fieldset>
  );
}

/** Simple labelled input wrapper. */
function InputField({
  id,
  label,
  required,
  type = 'text',
  value,
  onChange,
  placeholder,
}: {
  id: string;
  label: string;
  required?: boolean;
  type?: string;
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
}): JSX.Element {
  return (
    <div>
      <label htmlFor={id} className="block text-sm font-medium text-foreground mb-1">
        {label}
        {required && <span className="text-red-500 ml-1">*</span>}
      </label>
      <input
        id={id}
        type={type}
        required={required}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="w-full px-4 py-2 border border-border rounded-md bg-surface text-foreground placeholder:text-muted focus:outline-none focus:ring-2 focus:ring-primary/50"
        placeholder={placeholder}
      />
    </div>
  );
}
