// Right-side editor panel for the selected task

function isValidColor(str) {
  if (!str || !str.trim()) return false;
  const s = new Option().style;
  s.color = str.trim();
  return s.color !== '';
}

function Editor({ task, tasks, swatches, onChange, onClose, onDelete }) {
  const [colorDraft, setColorDraft] = React.useState(task ? task.color : '');
  const [colorError, setColorError] = React.useState(false);
  const [activeSlot, setActiveSlot] = React.useState(1);

  React.useEffect(() => {
    if (task) {
      setActiveSlot(1);
      setColorDraft(task.color);
      setColorError(false);
    }
  }, [task && task.id]);

  React.useEffect(() => {
    if (task) {
      setColorDraft(activeSlot === 1 ? task.color : (task.color2 || ''));
      setColorError(false);
    }
  }, [task && task.color, task && task.color2, activeSlot]);

  if (!task) return <div className="editor"></div>;

  const update = (patch) => onChange(task.id, patch);
  const isMilestone = task.type === 'milestone';
  const otherTasks = (tasks || []).filter((t) => t.id !== task.id);
  const taskDeps = task.deps || [];
  const activeColor = activeSlot === 1 ? task.color : (task.color2 || task.color);
  const updateColor = (val) => {
    if (activeSlot === 1) update({ color: val });
    else update({ color2: val });
  };

  const handleColorText = (val) => {
    setColorDraft(val);
    if (isValidColor(val)) {
      setColorError(false);
      updateColor(val.trim());
    } else {
      setColorError(true);
    }
  };

  return (
    <div className={`editor ${task ? 'open' : ''}`}>
      <div className="editor-header">
        <div className="editor-title">Modifica attività</div>
        <button className="close-btn" onClick={onClose} aria-label="Chiudi">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M3 3L13 13M13 3L3 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
          </svg>
        </button>
      </div>

      <div className="editor-body">
        <div className="field">
          <label className="field-label">Nome</label>
          <input
            type="text"
            className="field-input"
            value={task.name}
            onChange={(e) => update({ name: e.target.value })}
            placeholder="Nome attività"
          />
        </div>

        <div className="editor-toggle-row">
          <span className="field-label">Milestone</span>
          <label className="toggle">
            <input
              type="checkbox"
              checked={isMilestone}
              aria-label="Milestone"
              onChange={(e) => {
                if (e.target.checked) {
                  update({ type: 'milestone', end: task.start });
                } else {
                  update({ type: 'task', end: window.fmtISO(window.addDays(window.parseISO(task.start), 7)) });
                }
              }}
            />
            <span className="toggle-track"><span className="toggle-thumb"></span></span>
          </label>
        </div>

        <div className={`field-row${isMilestone ? ' field-row--single' : ''}`}>
          <div className="field">
            <label className="field-label">{isMilestone ? 'Data' : 'Inizio'}</label>
            <input
              type="date"
              className="field-date"
              aria-label={isMilestone ? 'Data milestone' : 'Data inizio'}
              value={task.start}
              onChange={(e) => {
                const ns = e.target.value;
                const patch = { start: ns };
                if (isMilestone) {
                  patch.end = ns;
                } else if (window.parseISO(ns) > window.parseISO(task.end)) {
                  patch.end = ns;
                }
                update(patch);
              }}
            />
          </div>
          {!isMilestone && (
            <div className="field">
              <label className="field-label">Fine</label>
              <input
                type="date"
                className="field-date"
                aria-label="Data fine"
                value={task.end}
                onChange={(e) => {
                  const ne = e.target.value;
                  const patch = { end: ne };
                  if (window.parseISO(ne) < window.parseISO(task.start)) {
                    patch.start = ne;
                  }
                  update(patch);
                }}
              />
            </div>
          )}
        </div>

        <div className="field">
          <label className="field-label">Colori</label>
          <div className="color-slots">
            <button
              type="button"
              className={`color-slot${activeSlot === 1 ? ' color-slot--active' : ''}`}
              style={{ '--slot-color': task.color }}
              onClick={() => setActiveSlot(1)}
              aria-label="Colore principale"
            />
            <button
              type="button"
              className={`color-slot${activeSlot === 2 ? ' color-slot--active' : ''}${!task.color2 ? ' color-slot--empty' : ''}`}
              style={task.color2 ? { '--slot-color': task.color2 } : {}}
              onClick={() => setActiveSlot(2)}
              aria-label="Secondo colore"
            />
            {task.color2 && (
              <button
                type="button"
                className="color-slot-clear"
                onClick={() => { update({ color2: '' }); if (activeSlot === 2) setActiveSlot(1); }}
                aria-label="Rimuovi gradiente"
              >×</button>
            )}
          </div>
          <div className="swatch-grid">
            {swatches.map((c, i) => (
              <button
                key={i}
                type="button"
                className={`swatch ${activeColor === c ? 'active' : ''}`}
                style={{ background: c }}
                onClick={() => updateColor(c)}
                aria-label={`Colore ${i + 1}`}
              ></button>
            ))}
          </div>
          <div className="custom-color-row">
            <label className="custom-color-preview" style={{ '--custom-color': activeColor }}>
              <input
                type="color"
                className="custom-color-input"
                aria-label="Selettore colore"
                value={/^#[0-9a-fA-F]{6}$/.test(activeColor) ? activeColor : '#000000'}
                onChange={(e) => {
                  const v = e.target.value;
                  setColorDraft(v);
                  setColorError(false);
                  updateColor(v);
                }}
              />
            </label>
            <input
              type="text"
              className={`custom-color-text${colorError ? ' custom-color-text--error' : ''}`}
              value={colorDraft}
              onChange={(e) => handleColorText(e.target.value)}
              onBlur={() => {
                if (colorError) {
                  setColorDraft(activeSlot === 1 ? task.color : (task.color2 || ''));
                  setColorError(false);
                }
              }}
              spellCheck={false}
              placeholder="#rrggbb"
              aria-label="Valore colore"
            />
          </div>
        </div>

        <div className="field">
          <label className="field-label">Avanzamento</label>
          <div className="progress-row">
            <input
              type="range"
              className="progress-slider"
              min="0"
              max="100"
              step="5"
              value={task.progress}
              onChange={(e) => update({ progress: Number(e.target.value) })}
            />
            <span className="progress-value">{task.progress}%</span>
          </div>
        </div>

        {!isMilestone && (
          <div className="field">
            <label className="field-label">Durata</label>
            <div className="status-pill">
              {durationLabel(task.start, task.end)}
            </div>
          </div>
        )}

        <div className="field">
          <label className="field-label">Dipendenze</label>
          {otherTasks.length === 0 ? (
            <span className="dep-empty">Nessun'altra attività</span>
          ) : (
            <div className="dep-list">
              {otherTasks.map((t) => (
                <label key={t.id} className="dep-row">
                  <input
                    type="checkbox"
                    className="dep-check"
                    checked={taskDeps.includes(t.id)}
                    aria-label={t.name}
                    onChange={(e) => {
                      const next = e.target.checked
                        ? [...taskDeps, t.id]
                        : taskDeps.filter((id) => id !== t.id);
                      update({ deps: next });
                    }}
                  />
                  <span className="dep-dot" style={{ '--dep-color': t.color }}></span>
                  <span className="dep-name">{t.name}</span>
                  {t.type === 'milestone' && <span className="dep-badge">◆</span>}
                </label>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="editor-footer">
        <button className="btn btn-danger" onClick={() => onDelete(task.id)} style={{ flex: 1 }}>
          Elimina
        </button>
        <button className="btn btn-primary" onClick={onClose} style={{ flex: 1 }}>
          Fatto
        </button>
      </div>
    </div>
  );
}

function durationLabel(startISO, endISO) {
  const s = window.parseISO(startISO);
  const e = window.parseISO(endISO);
  const days = Math.round((window.startOfDay(e) - window.startOfDay(s)) / 86400000) + 1;
  if (days < 7) return `${days} ${days === 1 ? 'giorno' : 'giorni'}`;
  const weeks = Math.floor(days / 7);
  const rem = days % 7;
  if (rem === 0) return `${weeks} ${weeks === 1 ? 'settimana' : 'settimane'} · ${days} giorni`;
  return `${weeks}s ${rem}g · ${days} giorni`;
}

window.Editor = Editor;
