import React, { useState } from 'react';
import PollList from './Poll/PollList';
import PollBuilder from './Poll/PollBuilder';
import PollResults from './Poll/PollResults';

type View = 'list' | 'create' | 'edit' | 'results';

interface Poll {
    id: number;
    poll_name: string;
    description: string;
    featured_image: string;
    initial_form_id: number | null;
    answers: any[];
    settings: any;
    created_at: string;
    updated_at: string;
}

const Polls: React.FC = () => {
    const [currentView, setCurrentView] = useState<View>('list');
    const [selectedPoll, setSelectedPoll] = useState<Poll | null>(null);

    const handleCreatePoll = () => {
        setSelectedPoll(null);
        setCurrentView('create');
    };

    const handleEditPoll = (poll: Poll) => {
        setSelectedPoll(poll);
        setCurrentView('edit');
    };

    const handleViewResults = (poll: Poll) => {
        setSelectedPoll(poll);
        setCurrentView('results');
    };

    const handleBackToList = () => {
        setSelectedPoll(null);
        setCurrentView('list');
    };

    const handleSavePoll = () => {
        // Refresh list after save
        setCurrentView('list');
        setSelectedPoll(null);
    };

    return (
        <div className="polls-container">
            {currentView === 'list' && (
                <PollList
                    onCreatePoll={handleCreatePoll}
                    onEditPoll={handleEditPoll}
                    onViewResults={handleViewResults}
                />
            )}

            {(currentView === 'create' || currentView === 'edit') && (
                <PollBuilder
                    pollId={selectedPoll?.id}
                    onBack={handleBackToList}
                    onSave={handleSavePoll}
                />
            )}

            {currentView === 'results' && selectedPoll && (
                <PollResults
                    pollId={selectedPoll.id}
                    pollName={selectedPoll.poll_name}
                    onBack={handleBackToList}
                />
            )}
        </div>
    );
};

export default Polls;
