import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Plus, Trash2, BarChart2 } from 'lucide-react';
import { createPortal } from 'react-dom';
import { useLang } from '../../../../core/infrastructure/i18n';

interface CreatePollModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSend: (data: {
    question: string;
    options: string[];
    isAnonymous: boolean;
    allowMultiple: boolean;
  }) => void;
}

export default function CreatePollModal({ isOpen, onClose, onSend }: CreatePollModalProps) {
  const { t } = useLang();
  const [question, setQuestion] = useState('');
  const [options, setOptions] = useState(['', '']);
  const [isAnonymous, setIsAnonymous] = useState(true);
  const [allowMultiple, setAllowMultiple] = useState(false);

  if (!isOpen) return null;

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

  const handleRemoveOption = (index: number) => {
    if (options.length > 2) {
      const newOptions = [...options];
      newOptions.splice(index, 1);
      setOptions(newOptions);
    }
  };

  const handleOptionChange = (index: number, value: string) => {
    const newOptions = [...options];
    newOptions[index] = value;
    setOptions(newOptions);
  };

  const isValid = question.trim() && options.filter(o => o.trim()).length >= 2;

  const handleSubmit = () => {
    if (!isValid) return;
    onSend({
      question: question.trim(),
      options: options.filter(o => o.trim()),
      isAnonymous,
      allowMultiple
    });
    // Reset and close
    setQuestion('');
    setOptions(['', '']);
    setIsAnonymous(true);
    setAllowMultiple(false);
    onClose();
  };

  const modalContent = (
    <AnimatePresence>
      {isOpen && (
        <div className="fixed inset-0 z-[100000] flex items-center justify-center p-4 isolate">
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="absolute inset-0 bg-black/80 backdrop-blur-md"
          />
          <motion.div
            initial={{ opacity: 0, scale: 0.9, y: 30 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.9, y: 30 }}
            className="relative w-full max-w-md max-h-[85vh] bg-[#1a1a1a] rounded-[2.5rem] shadow-2xl flex flex-col overflow-hidden border border-white/10"
          >
            {/* Header */}
            <div className="flex items-center justify-between px-6 py-5 border-b border-white/5">
              <div className="flex items-center gap-3">
                <div className="w-11 h-11 rounded-full bg-primary/20 flex items-center justify-center">
                  <BarChart2 className="text-primary" size={22} />
                </div>
                <h3 className="text-xl font-bold text-white tracking-tight">
                  {t('createPoll')}
                </h3>
              </div>
              <button
                onClick={onClose}
                className="w-10 h-10 rounded-full flex items-center justify-center text-zinc-400 hover:bg-white/5 hover:text-white transition-all"
              >
                <X size={22} />
              </button>
            </div>

            {/* Content */}
            <div className="flex-1 p-6 space-y-7 overflow-y-auto custom-scrollbar">
              {/* Question */}
              <div className="space-y-2.5">
                <label className="text-[11px] font-black uppercase tracking-[0.1em] text-primary/80 px-1">
                  {t('pollQuestion')}
                </label>
                <textarea
                  autoFocus
                  placeholder={t('pollQuestionPlaceholder')}
                  value={question}
                  onChange={(e) => setQuestion(e.target.value)}
                  className="w-full bg-white/[0.03] border border-white/5 rounded-2xl p-4 text-sm text-white placeholder:text-white/20 focus:outline-none focus:border-primary/30 focus:bg-white/[0.06] transition-all resize-none min-h-[120px]"
                />
              </div>

              {/* Options */}
              <div className="space-y-4">
                <label className="text-[11px] font-black uppercase tracking-[0.1em] text-primary/80 px-1">
                  {t('pollOptions')}
                </label>
                <div className="space-y-2.5">
                  {options.map((option, idx) => (
                    <div key={idx} className="flex gap-2.5 group">
                      <input
                        placeholder={`${t('pollOption')} ${idx + 1}`}
                        value={option}
                        onChange={(e) => handleOptionChange(idx, e.target.value)}
                        className="flex-1 bg-white/[0.03] border border-white/5 rounded-2xl px-5 py-3.5 text-sm text-white placeholder:text-white/20 focus:outline-none focus:border-primary/30 focus:bg-white/[0.06] transition-all"
                      />
                      {options.length > 2 && (
                        <button
                          onClick={() => handleRemoveOption(idx)}
                          className="w-12 h-12 rounded-2xl bg-red-500/10 text-red-400 flex items-center justify-center hover:bg-red-500/20 transition-all opacity-0 group-hover:opacity-100"
                        >
                          <Trash2 size={20} />
                        </button>
                      )}
                    </div>
                  ))}
                </div>
                {options.length < 10 && (
                  <button
                    onClick={handleAddOption}
                    className="flex items-center gap-2.5 text-sm font-bold text-primary hover:text-primary/80 transition-colors px-1 h-10"
                  >
                    <Plus size={20} />
                    <span>{t('addOption')}</span>
                  </button>
                )}
              </div>

              {/* Settings */}
              <div className="pt-2 space-y-4">
                <label className="text-[11px] font-black uppercase tracking-[0.1em] text-zinc-500 px-1">
                  {t('pollSettings')}
                </label>
                <div className="space-y-3">
                  <label className="flex items-center justify-between p-4.5 rounded-[1.25rem] bg-white/[0.02] border border-white/5 cursor-pointer hover:bg-white/[0.05] transition-all group">
                    <span className="text-[15px] font-medium text-zinc-300 group-hover:text-white transition-colors">{t('anonymousVoting')}</span>
                    <input
                      type="checkbox"
                      checked={isAnonymous}
                      onChange={(e) => setIsAnonymous(e.target.checked)}
                      className="w-5 h-5 rounded-md accent-primary"
                    />
                  </label>
                  <label className="flex items-center justify-between p-4.5 rounded-[1.25rem] bg-white/[0.02] border border-white/5 cursor-pointer hover:bg-white/[0.05] transition-all group">
                    <span className="text-[15px] font-medium text-zinc-300 group-hover:text-white transition-colors">{t('multipleAnswers')}</span>
                    <input
                      type="checkbox"
                      checked={allowMultiple}
                      onChange={(e) => setAllowMultiple(e.target.checked)}
                      className="w-5 h-5 rounded-md accent-primary"
                    />
                  </label>
                </div>
              </div>
            </div>

            {/* Footer */}
            <div className="p-6 pt-3">
              <button
                disabled={!isValid}
                onClick={handleSubmit}
                className="w-full h-14 rounded-2xl bg-primary text-white text-[16px] font-black shadow-2xl shadow-primary/20 hover:scale-[1.02] active:scale-[0.98] disabled:opacity-30 disabled:grayscale disabled:scale-100 transition-all flex items-center justify-center gap-3"
              >
                <BarChart2 size={22} className="fill-white/20" />
                {t('createPoll')}
              </button>
            </div>
          </motion.div>
        </div>
      )}
    </AnimatePresence>
  );

  return createPortal(modalContent, document.body);
}
