import React, { useState } from 'react';

export default function PollCreator({ onSubmit, onClose }) {
  const [question, setQuestion] = useState('');
  const [options, setOptions] = useState(['', '']);
  const [duration, setDuration] = useState('24h');
  const [multiSelect, setMultiSelect] = useState(false);

  const durations = [
    { value: '1h', label: '1 Hour' },
    { value: '4h', label: '4 Hours' },
    { value: '8h', label: '8 Hours' },
    { value: '24h', label: '24 Hours' },
    { value: '3d', label: '3 Days' },
    { value: '7d', label: '1 Week' },
  ];

  const addOption = () => {
    if (options.length < 10) {
      setOptions([...options, '']);
    }
  };

  const removeOption = (index) => {
    if (options.length > 2) {
      setOptions(options.filter((_, i) => i !== index));
    }
  };

  const updateOption = (index, value) => {
    setOptions(options.map((opt, i) => i === index ? value : opt));
  };

  const handleSubmit = () => {
    if (!question.trim() || options.filter(o => o.trim()).length < 2) return;
    
    onSubmit?.({
      question,
      options: options.filter(o => o.trim()),
      duration,
      multiSelect,
    });
    onClose?.();
  };

  const validOptions = options.filter(o => o.trim()).length;

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="poll-creator" onClick={(e) => e.stopPropagation()}>
        <div className="poll-header">
          <h2>Create Poll</h2>
          <button className="poll-close" onClick={onClose}>✕</button>
        </div>

        <div className="poll-content">
          <div className="poll-field">
            <label>Question</label>
            <textarea
              placeholder="Ask something..."
              value={question}
              onChange={(e) => setQuestion(e.target.value)}
              maxLength={300}
              rows={2}
            />
            <span className="char-count">{question.length}/300</span>
          </div>

          <div className="poll-field">
            <label>Answers</label>
            <div className="poll-options">
              {options.map((opt, idx) => (
                <div key={idx} className="poll-option">
                  <span className="option-number">{idx + 1}</span>
                  <input
                    type="text"
                    placeholder={`Option ${idx + 1}`}
                    value={opt}
                    onChange={(e) => updateOption(idx, e.target.value)}
                    maxLength={55}
                  />
                  {options.length > 2 && (
                    <button 
                      className="remove-option"
                      onClick={() => removeOption(idx)}
                    >
                      ✕
                    </button>
                  )}
                </div>
              ))}
            </div>
            {options.length < 10 && (
              <button className="add-option" onClick={addOption}>
                + Add another answer
              </button>
            )}
          </div>

          <div className="poll-field">
            <label>Duration</label>
            <select 
              value={duration} 
              onChange={(e) => setDuration(e.target.value)}
              className="poll-select"
            >
              {durations.map(d => (
                <option key={d.value} value={d.value}>{d.label}</option>
              ))}
            </select>
          </div>

          <div className="poll-toggle">
            <label className="toggle-label">
              <input
                type="checkbox"
                checked={multiSelect}
                onChange={(e) => setMultiSelect(e.target.checked)}
              />
              <span className="toggle-switch"></span>
              <span>Allow multiple answers</span>
            </label>
          </div>
        </div>

        <div className="poll-preview">
          <h4>Preview</h4>
          <div className="preview-card">
            <div className="preview-question">{question || 'Your question here'}</div>
            <div className="preview-options">
              {options.filter(o => o.trim()).map((opt, idx) => (
                <div key={idx} className="preview-option">
                  <div className="option-circle" />
                  <span>{opt}</span>
                </div>
              ))}
            </div>
            <div className="preview-footer">
              <span>0 votes</span>
              <span>•</span>
              <span>{durations.find(d => d.value === duration)?.label} remaining</span>
            </div>
          </div>
        </div>

        <div className="poll-footer">
          <button className="poll-cancel" onClick={onClose}>Cancel</button>
          <button 
            className="poll-submit" 
            onClick={handleSubmit}
            disabled={!question.trim() || validOptions < 2}
          >
            Create Poll
          </button>
        </div>
      </div>
    </div>
  );
}

// Poll display component for messages
export function Poll({ poll, onVote }) {
  const [selected, setSelected] = useState([]);
  const [hasVoted, setHasVoted] = useState(false);

  const totalVotes = poll.options.reduce((sum, opt) => sum + (opt.votes || 0), 0);

  const handleVote = (optionIndex) => {
    if (hasVoted) return;
    
    if (poll.multiSelect) {
      setSelected(prev => 
        prev.includes(optionIndex)
          ? prev.filter(i => i !== optionIndex)
          : [...prev, optionIndex]
      );
    } else {
      setSelected([optionIndex]);
    }
  };

  const submitVote = () => {
    if (selected.length === 0) return;
    onVote?.(selected);
    setHasVoted(true);
  };

  return (
    <div className="poll-message">
      <div className="poll-question">{poll.question}</div>
      <div className="poll-options-list">
        {poll.options.map((opt, idx) => {
          const percentage = hasVoted && totalVotes > 0 
            ? Math.round((opt.votes / totalVotes) * 100) 
            : 0;
          
          return (
            <button
              key={idx}
              className={`poll-vote-option ${selected.includes(idx) ? 'selected' : ''} ${hasVoted ? 'voted' : ''}`}
              onClick={() => handleVote(idx)}
              disabled={hasVoted}
            >
              {hasVoted && (
                <div className="vote-bar" style={{ width: `${percentage}%` }} />
              )}
              <div className="vote-content">
                {!hasVoted && (
                  <div className={`vote-checkbox ${poll.multiSelect ? 'multi' : ''}`}>
                    {selected.includes(idx) && '✓'}
                  </div>
                )}
                <span className="vote-text">{opt.text}</span>
                {hasVoted && (
                  <span className="vote-percentage">{percentage}%</span>
                )}
              </div>
            </button>
          );
        })}
      </div>
      {!hasVoted && selected.length > 0 && (
        <button className="submit-vote" onClick={submitVote}>
          Vote
        </button>
      )}
      <div className="poll-info">
        <span>{totalVotes} vote{totalVotes !== 1 ? 's' : ''}</span>
        <span>•</span>
        <span>{poll.timeLeft}</span>
      </div>
    </div>
  );
}
