App.PollList = function PollList() {
    const [polls, setPolls] = React.useState([]);
    const [loading, setLoading] = React.useState(true);

    const loadPolls = () => {
        setLoading(true);
        App.API.get('polls?fingerprint=' + App.fingerprint).then(data => {
            setPolls(data);
            setLoading(false);
        });
    };

    React.useEffect(() => { loadPolls(); }, []);

    const handleDelete = (shareCode, title) => {
        if (!confirm('Delete poll "' + title + '"? All votes will be lost.')) return;
        App.API.post('polls/' + shareCode, {
            _action: 'delete',
            fingerprint: App.fingerprint,
        })
            .then(() => loadPolls())
            .catch(err => alert(err.message));
    };

    if (loading) return <App.Loading />;

    return (
        <div className="page">
            <div className="page-header">
                <h1>Polls</h1>
                <a href="#/create-poll" className="btn btn-primary">Create Poll</a>
            </div>
            <p className="page-subtitle">Active polls for voting on race combinations</p>

            {polls.length === 0 ? (
                <div className="empty-state">
                    <p>No active polls yet.</p>
                    <a href="#/create-poll" className="btn btn-primary">Create Poll</a>
                </div>
            ) : (
                <div className="poll-list">
                    {polls.map(poll => {
                        var voteStatus = '';
                        if (typeof poll.user_voted !== 'undefined') {
                            if (poll.user_voted === 0) voteStatus = 'poll-status-none';
                            else if (poll.user_voted >= poll.user_total) voteStatus = 'poll-status-complete';
                            else voteStatus = 'poll-status-partial';
                        }
                        return (
                        <div key={poll.id} className={'poll-list-card' + (voteStatus ? ' ' + voteStatus : '')}>
                            <div className="poll-list-body">
                                <h3>{poll.title}</h3>
                                <div className="poll-list-meta">
                                    <span>{poll.combo_count} combo{poll.combo_count != 1 ? 's' : ''}</span>
                                    <span>Created {new Date(poll.created_at).toLocaleDateString()}</span>
                                    {(poll.creator_nickname || poll.creator_id) && (
                                        <span className="poll-creator-meta">
                                            by <App.UserBadge userId={poll.creator_id} nickname={poll.creator_nickname} size="small" />
                                        </span>
                                    )}
                                    {typeof poll.user_voted !== 'undefined' && (
                                        voteStatus === 'poll-status-complete'
                                            ? <span style={{color: 'var(--success)'}}>All voted</span>
                                            : <span>{poll.user_total - poll.user_voted} vote{poll.user_total - poll.user_voted !== 1 ? 's' : ''} remaining</span>
                                    )}
                                </div>
                                {poll.combos && poll.combos.length > 0 && (
                                    <div className="poll-combo-list">
                                        {poll.combos.map((combo, i) => (
                                            <div key={i} className="poll-combo-row">
                                                <span className="poll-combo-track">{combo.track_name}</span>
                                                {combo.car_names.length > 0 && (
                                                    <span className="poll-combo-cars"> — {combo.car_names.join(' / ')}</span>
                                                )}
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </div>
                            <div className="poll-list-actions">
                                <a href={'#/poll/' + poll.share_code} className="btn btn-primary">Vote</a>
                                <a href={'#/results/' + poll.share_code} className="btn">Results</a>
                                <button className="btn" onClick={() => App.sharePoll(poll.share_code)}>Share</button>
                                {poll.creator_fingerprint === App.fingerprint && (
                                    <button
                                        className="btn btn-danger"
                                        onClick={() => handleDelete(poll.share_code, poll.title)}
                                    >
                                        Delete
                                    </button>
                                )}
                            </div>
                        </div>
                        );
                    })}
                </div>
            )}
        </div>
    );
};
