import { useState, useRef } from 'react';
import type { NewTaskInput } from '../types';
import { useLanguage } from '../i18n/LanguageContext';
import './CreateTaskForm.css';

interface CreateTaskFormProps {
  onCreateTask: (task: NewTaskInput) => void;
}

export default function CreateTaskForm({ onCreateTask }: CreateTaskFormProps) {
  const { t } = useLanguage();
  const [isOpen, setIsOpen] = useState(false);
  const [name, setName] = useState('');
  const [doesRepeat, setDoesRepeat] = useState(true);
  const [repeatAmount, setRepeatAmount] = useState('1');
  const [repeatUnit, setRepeatUnit] = useState<'WEEKS' | 'MONTHS' | 'YEARS'>('WEEKS');
  const [toDoToday, setToDoToday] = useState(true);
  const [priority, setPriority] = useState<'ESSENTIAL' | 'WHEN_I_HAVE_TIME'>('ESSENTIAL');
  const inputRef = useRef<HTMLInputElement>(null);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) return;
    const taskInput: NewTaskInput = {
      name: name.trim(),
      doesRepeat,
      repeatsEvery: doesRepeat ? `${repeatAmount}_${repeatUnit}` : undefined,
      priority,
      toDoToday,
    };
    onCreateTask(taskInput);
    setName('');
    setDoesRepeat(true);
    setRepeatAmount('1');
    setRepeatUnit('WEEKS');
    setToDoToday(true);
    setPriority('ESSENTIAL');
    setIsOpen(false);
  };

  return (
    <div className="create-task-form">
      {!isOpen ? (
        <button className="open-form-btn" onClick={() => setIsOpen(true)}>
          {t.createNewTask}
        </button>
      ) : (
        <form onSubmit={handleSubmit} className="task-form">
          <h3>{t.createNewTaskTitle}</h3>

          <div className="form-group">
            <label>{t.taskLabel}</label>
            <div className="name-input-row">
              <input
                ref={inputRef}
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value.slice(0, 60))}
                placeholder={t.taskPlaceholder}
                maxLength={60}
                autoFocus
              />
              <button
                type="button"
                className="name-confirm-btn"
                onClick={() => inputRef.current?.blur()}
                tabIndex={-1}
              >
                ✓
              </button>
            </div>
            <span className="char-count">{name.length}/60</span>
          </div>

          <div className="form-group">
            <label>{t.repeats}</label>
            <div className="btn-group">
              <button type="button" className={`btn-option${doesRepeat ? ' btn-option--active' : ''}`} onClick={() => setDoesRepeat(true)}>{t.yes}</button>
              <button type="button" className={`btn-option${!doesRepeat ? ' btn-option--active' : ''}`} onClick={() => setDoesRepeat(false)}>{t.no}</button>
            </div>
          </div>

          {doesRepeat && (
            <div className="form-group">
              <label>{t.every}</label>
              <div className="repeat-input">
                <input
                  type="number"
                  value={repeatAmount}
                  onChange={(e) => setRepeatAmount(e.target.value)}
                  min="1"
                  max="999"
                  className="repeat-amount"
                />
                <select
                  value={repeatUnit}
                  onChange={(e) => setRepeatUnit(e.target.value as any)}
                  className="repeat-unit"
                >
                  <option value="DAYS">{repeatAmount !== '1' ? t.days : t.day}</option>
                  <option value="WEEKS">{repeatAmount !== '1' ? t.weeks : t.week}</option>
                  <option value="MONTHS">{repeatAmount !== '1' ? t.months : t.month}</option>
                  <option value="YEARS">{repeatAmount !== '1' ? t.years : t.year}</option>
                </select>
              </div>
            </div>
          )}

          <div className="form-group">
            <label>{t.toDoRightNow}</label>
            <div className="btn-group">
              <button type="button" className={`btn-option${toDoToday ? ' btn-option--active' : ''}`} onClick={() => setToDoToday(true)}>{t.yes}</button>
              <button type="button" className={`btn-option${!toDoToday ? ' btn-option--active' : ''}`} onClick={() => setToDoToday(false)}>{t.no}</button>
            </div>
          </div>

          <div className="form-group">
            <label>{t.priority}</label>
            <div className="btn-group">
              <button type="button" className={`btn-option${priority === 'ESSENTIAL' ? ' btn-option--active' : ''}`} onClick={() => setPriority('ESSENTIAL')}>{t.essential}</button>
              <button type="button" className={`btn-option${priority === 'WHEN_I_HAVE_TIME' ? ' btn-option--active' : ''}`} onClick={() => setPriority('WHEN_I_HAVE_TIME')}>{t.whenIHaveTimePriority}</button>
            </div>
          </div>

          <div className="form-actions">
            <button type="submit" className="submit-btn">{t.createTask}</button>
            <button type="button" className="cancel-btn" onClick={() => setIsOpen(false)}>{t.cancel}</button>
          </div>
        </form>
      )}
    </div>
  );
}
