import React, { useState } from 'react';
import { useInbox } from '../store.js';

const COLOR_PALETTE = ['#0a4b80', '#236b1a', '#946100', '#a55', '#5a3a8c', '#1a5b6e'];

export function NotebookCreateModal({ onClose }: { onClose: () => void }): React.ReactElement {
  const createNotebook = useInbox((s) => s.createNotebook);
  const [name, setName] = useState('');
  const [color, setColor] = useState<string>(COLOR_PALETTE[0]!);
  const [err, setErr] = useState<string | null>(null);

  async function onSubmit() {
    const r = await createNotebook(name.trim(), color);
    if (r.ok) onClose();
    else setErr(r.reason === 'duplicate_name' ? '같은 이름의 노트북이 이미 있어요.' : (r.reason ?? '저장 실패'));
  }

  return (
    <div
      onClick={onClose}
      style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 120 }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{ background: '#fff', padding: 20, borderRadius: 8, width: 360 }}
      >
        <h3 style={{ margin: '0 0 12px 0', fontSize: 15 }}>새 노트북</h3>
        <input
          aria-label="노트북 이름"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="예: 회사, 학습"
          autoFocus
          style={{ width: '100%', padding: '6px 8px', fontSize: 13, border: '1px solid #ccc', borderRadius: 4, boxSizing: 'border-box' }}
        />
        <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
          {COLOR_PALETTE.map((c) => (
            <button
              key={c}
              onClick={() => setColor(c)}
              aria-label={`색 ${c}`}
              style={{
                width: 24, height: 24, borderRadius: '50%',
                background: c, border: c === color ? '2px solid #333' : '1px solid #ccc',
                cursor: 'pointer', padding: 0
              }}
            />
          ))}
        </div>
        {err && <div style={{ color: '#c33', fontSize: 12, marginTop: 8 }}>{err}</div>}
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 14 }}>
          <button onClick={onClose} style={{ padding: '5px 12px', fontSize: 12 }}>취소</button>
          <button
            onClick={() => { void onSubmit(); }}
            disabled={name.trim().length === 0}
            style={{ padding: '5px 12px', fontSize: 12, background: '#0a4b80', color: '#fff', border: 'none', borderRadius: 4, cursor: name.trim().length === 0 ? 'not-allowed' : 'pointer', opacity: name.trim().length === 0 ? 0.5 : 1 }}
          >
            만들기
          </button>
        </div>
      </div>
    </div>
  );
}
