const { useState, useEffect } = React;

const PRIORITIES = ['高', '中', '低'];
const FILTERS = ['全部', '高', '中', '低'];

const PRIORITY_CLASS = { '高': 'p-high', '中': 'p-mid', '低': 'p-low' };

function App() {
  const [tasks, setTasks] = useState([]);
  const [title, setTitle] = useState('');
  const [priority, setPriority] = useState('中');
  const [filter, setFilter] = useState('全部');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [mode, setMode] = useState('');
  const [busyId, setBusyId] = useState(null);

  async function load(f) {
    setLoading(true);
    try {
      const res = await fetch('/api/tasks?priority=' + encodeURIComponent(f));
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || '加载失败');
      setTasks(data);
      setError('');
    } catch (e) {
      setError(e.message);
    }
    setLoading(false);
  }

  useEffect(() => {
    fetch('/api/health').then((r) => r.json()).then((d) => setMode(d.mode)).catch(() => {});
  }, []);

  useEffect(() => {
    load(filter);
  }, [filter]);

  async function handleAdd(e) {
    e.preventDefault();
    if (!title.trim()) return;
    try {
      const res = await fetch('/api/tasks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title, priority }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || '添加失败');
      setTitle('');
      await load(filter);
    } catch (e) {
      setError(e.message);
    }
  }

  async function handleToggle(id) {
    setBusyId(id);
    try {
      const res = await fetch('/api/tasks/' + id, { method: 'PATCH' });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || '更新失败');
      setTasks((ts) => ts.map((t) => (t.id === data.id ? data : t)));
      setError('');
    } catch (e) {
      setError(e.message);
    }
    setBusyId(null);
  }

  async function handleDelete(id) {
    setBusyId(id);
    try {
      const res = await fetch('/api/tasks/' + id, { method: 'DELETE' });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || '删除失败');
      }
      setTasks((ts) => ts.filter((t) => t.id !== id));
      setError('');
    } catch (e) {
      setError(e.message);
    }
    setBusyId(null);
  }

  const doneCount = tasks.filter((t) => t.completed).length;

  return (
    <div className="container">
      <header className="header">
        <h1>智能任务管理系统</h1>
        <p className="subtitle">Node.js + React + Supabase</p>
        {mode && (
          <span className={'mode-badge ' + (mode === 'supabase' ? 'mode-ok' : 'mode-demo')}>
            {mode === 'supabase'
              ? '● 已连接 Supabase 云端数据库'
              : '● 演示模式（配置 .env 中的 SUPABASE_URL / SUPABASE_ANON_KEY 后即接入云端）'}
          </span>
        )}
      </header>

      <form className="add-form" onSubmit={handleAdd}>
        <input
          className="input"
          type="text"
          placeholder="写点什么任务…（如：完成数据结构作业）"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          maxLength={100}
        />
        <select
          className="select"
          value={priority}
          onChange={(e) => setPriority(e.target.value)}
        >
          {PRIORITIES.map((p) => (
            <option key={p} value={p}>优先级：{p}</option>
          ))}
        </select>
        <button className="btn btn-add" type="submit">添加</button>
      </form>

      <div className="toolbar">
        <div className="filters">
          {FILTERS.map((f) => (
            <button
              key={f}
              className={'filter-btn' + (filter === f ? ' active' : '')}
              onClick={() => setFilter(f)}
            >
              {f === '全部' ? '全部' : f + '优先级'}
            </button>
          ))}
        </div>
        <span className="stat">
          共 {tasks.length} 条 · 已完成 {doneCount} 条
        </span>
      </div>

      {error && <div className="error">{error}</div>}

      {loading ? (
        <div className="empty">加载中…</div>
      ) : tasks.length === 0 ? (
        <div className="empty">
          {filter === '全部' ? '还没有任务，先添加一条吧！' : '没有这个优先级的任务'}
        </div>
      ) : (
        <ul className="task-list">
          {tasks.map((t) => (
            <li key={t.id} className={'task' + (t.completed ? ' done' : '')}>
              <span className={'tag ' + PRIORITY_CLASS[t.priority]}>{t.priority}</span>
              <span className="title">{t.title}</span>
              <span className="actions">
                <button
                  className="btn btn-toggle"
                  disabled={busyId === t.id}
                  onClick={() => handleToggle(t.id)}
                >
                  {t.completed ? '标记未完成' : '完成'}
                </button>
                <button
                  className="btn btn-delete"
                  disabled={busyId === t.id}
                  onClick={() => handleDelete(t.id)}
                >
                  删除
                </button>
              </span>
            </li>
          ))}
        </ul>
      )}

      <footer className="footer">关掉浏览器再打开，数据还在 —— 因为它存在数据库里。</footer>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
