import React, { useEffect, useState } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; import { API } from '../../api/API'; import { toast } from 'sonner'; import { useSelector } from 'react-redux'; import { RootState } from '../../store'; import { User, RefreshCw, HelpCircle, ArrowLeft, Users, FileText, ChevronRight, CheckCircle, Info } from 'lucide-react'; type SubmittedView = 'none' | 'success' | 'already'; const PublicQuestionnairePage: React.FC = () => { const { applicationId } = useParams<{ applicationId: string }>(); const navigate = useNavigate(); const { user } = useSelector((state: RootState) => state.auth); const [loading, setLoading] = useState(true); const [questions, setQuestions] = useState([]); const [sections, setSections] = useState([]); const [activeSection, setActiveSection] = useState(''); const [responses, setResponses] = useState>({}); const [submitting, setSubmitting] = useState(false); /** End-of-flow screen: success = just submitted; already = reopened link / second visit */ const [submittedView, setSubmittedView] = useState('none'); useEffect(() => { const fetchQuestionnaire = async () => { if (!applicationId) return; try { // Determine if we need public or private fetch based on auth // For prospective users, we might want to use the public endpoint or a specific one const res = await API.getPublicQuestionnaire(applicationId); if (res.data.success) { const fetchedQuestions = res.data.data.questions || []; setQuestions(fetchedQuestions); // Extract unique sections const uniqueSections = Array.from(new Set(fetchedQuestions.map((q: any) => q.sectionName))); setSections(uniqueSections as string[]); if (uniqueSections.length > 0) { setActiveSection(uniqueSections[0] as string); } // Check if already submitted (optional, backend might handle) } } catch (error: any) { console.error("Error fetching questionnaire:", error); if (error.response?.data?.code === 'ALREADY_SUBMITTED') { setSubmittedView('already'); } else { toast.error("Failed to load questionnaire"); } } finally { setLoading(false); } }; fetchQuestionnaire(); }, [applicationId]); const handleInputChange = (questionId: string, value: any) => { setResponses(prev => ({ ...prev, [questionId]: value })); }; const handleNextSection = () => { const currentIndex = sections.indexOf(activeSection); if (currentIndex < sections.length - 1) { setActiveSection(sections[currentIndex + 1]); window.scrollTo({ top: 0, behavior: 'smooth' }); } }; const handlePrevSection = () => { const currentIndex = sections.indexOf(activeSection); if (currentIndex > 0) { setActiveSection(sections[currentIndex - 1]); window.scrollTo({ top: 0, behavior: 'smooth' }); } }; const handleSubmit = async () => { // Validate all mandatory questions const missing = questions.filter(q => q.isMandatory && !responses[q.id]); if (missing.length > 0) { toast.error(`Please answer all mandatory questions. Missing: ${missing.length}`); // Provide visual feedback or navigation to missing section? return; } try { setSubmitting(true); const payload = Object.entries(responses).map(([qId, val]) => ({ questionId: qId, value: val })); await API.submitPublicResponse({ applicationId: applicationId!, responses: payload }); toast.success('Responses submitted successfully'); setSubmittedView('success'); } catch (error) { console.error(error); toast.error('Failed to submit responses'); } finally { setSubmitting(false); } }; if (loading) return (
); if (submittedView !== 'none') { const isAlready = submittedView === 'already'; return (
{isAlready ? : }

{isAlready ? 'Already submitted' : 'Thank you'}

{isAlready ? ( <> This questionnaire has already been submitted for your application. You do not need to complete it again. If you think this is a mistake, contact support using the same email you used to apply. You may close this page when you are done. ) : ( <> Your assessment has been submitted successfully. We have received your responses and will review them as part of your application. You may close this page when you are done. )}

); } const activeQuestions = questions.filter(q => q.sectionName === activeSection); const currentSectionIndex = sections.indexOf(activeSection); return (
{/* Header */}

Dealer Questionnaire Form

Answer each section accurately. Your responses are part of the dealership application assessment and may be verified.

{user && (

{user.name || 'Applicant'}

{user.role || 'Prospective Dealer'}

)}
{/* Hero Section */}
Royal Enfield

Dealership Partner Application

Thank you for your interest in becoming a Royal Enfield business partner. Please complete this questionnaire to help us understand your profile and aspirations.

{questions.length}
Questions
{sections.length}
Sections
{/* Section Tabs */}
{sections.map((section) => ( ))}
{/* Question Content */}

{activeSection}

Section {currentSectionIndex + 1} of {sections.length} • {activeQuestions.length} questions

{activeQuestions.map((q, idx) => (
{idx + 1}
{(q.inputType === 'text' || q.inputType === 'email' || q.inputType === 'number') && ( handleInputChange(q.id, e.target.value)} /> )} {q.inputType === 'textarea' && (