import React, { useRef, useState, useEffect } from 'react';
import { HashRouter as Router, Link, NavLink, useHistory } from 'react-router-dom';
import { Navbar, Nav } from 'react-bootstrap';
import Routes from './router/index'; // 引入Routes组件
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-icons/font/bootstrap-icons.css'; // Import Bootstrap Icons
import 'react-toastify/dist/ReactToastify.css';
import LocalDataService from './api/LocalDataService';
import './css/index.css'
import { ToastContainer } from 'react-toastify';
import ApiService from './api/ApiService';
import { initDb } from './db';
import { toast } from 'react-toastify';

let ipcRenderer;
if (typeof window !== 'undefined' && window.require) {
  ipcRenderer = window.require('electron').ipcRenderer;
}

function App () {
  const userProfileRef = useRef(null);
  const apiService = new ApiService();
  const [dbInitialized, setDbInitialized] = useState(false);

  useEffect(() => {
    // 初始化数据库
    const initDatabase = async () => {
      try {
        const result = await initDb();
        setDbInitialized(result);
        if (result) {
          console.log('数据库初始化成功');
        } else {
          console.error('数据库初始化失败');
          toast.error('数据库初始化失败，部分功能可能无法正常使用');
        }
      } catch (error) {
        console.error('数据库初始化失败:', error);
        toast.error(`数据库初始化失败: ${error.message}，部分功能可能无法正常使用`);
        setDbInitialized(false);
      }
    };
    
    initDatabase();
    
    let user_info = LocalDataService.load_user_data();
    if (!user_info) {
      userProfileRef.current.showLoginModal();
    }
    apiService.setUserProfileRef(userProfileRef);
  }, []);


  return (
    <div className='app'>
      <Router>
        <Navbar expand="lg" className='navigation'>
          <Navbar.Brand as={Link} to="/" style={{ color: 'white', marginLeft: '12px', display: 'flex', alignItems: 'center' }}>
          视频对口型
          </Navbar.Brand>
          <Navbar.Toggle aria-controls="basic-navbar-nav" className="custom-toggler" />
          <Navbar.Collapse id="basic-navbar-nav" >
            <Nav className="navigation-tab" >
              <NavLink className='tab-info' to='/histList' activeClassName="active-link">历史记录</NavLink>
            </Nav>
          </Navbar.Collapse>
        </Navbar>
        <div className='content'>
          <Routes userProfileRef={userProfileRef} /> {/* 使用Routes组件 */}
        </div>
        <ToastContainer style={{ top: '55px' }} />
      </Router>
    </div>
  );
}

export default App;
