import React, { useRef } from 'react';

function Home({ setActiveTab, role, setRole }) {
  const fileInputRef = useRef(null);

  // 1. 开始新生活
  const handleNewStart = async () => {
    await fetch('/api/history', { method: 'DELETE' });
    setActiveTab('focus');
  };

  // 2. 自动导入 (使用缓存魔术)
  const handleAutoImport = async () => {
    const backup = localStorage.getItem('focus_magic_backup');
    if (backup) {
      try {
        const sessions = JSON.parse(backup);
        const response = await fetch('/api/import', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(sessions)
        });
        if (response.ok) {
          alert("Auto-recovery successful!");
        } else {
          alert("Auto-recovery failed.");
        }
      } catch (err) {
        alert("Error: " + err.message);
      }
    } else {
      alert("No previous backup found. Please use Manual Import.");
    }
  };

  // 3. 手动导入
  const handleFileChange = async (event) => {
    const file = event.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const sessions = JSON.parse(e.target.result);
        const response = await fetch('/api/import', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(sessions)
        });
        if (response.ok) {
          alert("Import successful!");
        }
      } catch (err) {
        alert("Error: " + err.message);
      }
      event.target.value = '';
    };
    reader.readAsText(file);
  };

  // 4. 切换 Admin/User 模式
  const handleAdminToggle = async () => {
    if (role === 'admin') {
      if (window.confirm("Switch back to User mode? Current data will be cleared.")) {
        await fetch('/api/history', { method: 'DELETE' });
        setRole('user');
        alert("Switched to User mode.");
      }
    } else {
      const pwd = window.prompt("Enter Admin Password:");
      if (pwd === "123") {
        try {
          await fetch('/api/history', { method: 'DELETE' });
          const res = await fetch('/test_data.json');
          if (!res.ok) throw new Error("test_data.json not found");
          const testData = await res.json();
          const importRes = await fetch('/api/import', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(testData)
          });
          if (importRes.ok) {
            setRole('admin');
            alert("Admin mode activated!");
          }
        } catch (error) {
          alert("Admin login failed: " + error.message);
        }
      } else if (pwd !== null) {
        alert("Incorrect password!");
      }
    }
  };

  return (
    <main id="page-a" className="page">
      <h1>FocusGuard</h1>
      <p>Your productivity monitor assistant.</p>

      {/* 🔪 把隐藏的上传框放在网格外面，绝对不让它占格子！ */}
      <input type="file" ref={fileInputRef} style={{ display: 'none' }} accept=".json" onChange={handleFileChange} />

      {/* 使用全新的 2x2 网格容器，里面只放 4 个纯净的按钮 */}
      <div className="home-button-grid">
        
        <button className="btn-main" onClick={handleNewStart}>
          Start Focus
        </button>

        <button className="btn-main" onClick={handleAutoImport}>
          Auto Import History
        </button>

        <button className="btn-main" onClick={() => fileInputRef.current.click()}>
          Manual Import History
        </button>

        <button className="btn-main" onClick={handleAdminToggle}>
          {role === 'admin' ? 'Switch to User Mode' : 'Admin Login'}
        </button>
        
      </div>
    </main>
  );
}

export default Home;