import 'package:flutter/material.dart';
import 'package:eanapo/screens/LoginScreen.dart';
import 'package:eanapo/screens/DiagnosisScreen.dart';
import 'package:eanapo/screens/HealthTip.dart';
import 'package:eanapo/screens/ScheduleScreen.dart';
import 'package:eanapo/screens/MapScreen.dart';

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int _currentIndex = 0;
  bool _isLoggedIn = false;
  String _username = '';

  void _onTabTapped(int index) {
    if (!_isLoggedIn && index != 0) {
      _showLoginRequiredDialog();
      return;
    }

    setState(() {
      _currentIndex = index;
    });
  }

  void _login(String username) {
    setState(() {
      _isLoggedIn = true;
      _username = username;
      _currentIndex = 0; // 로그인 후 홈 화면으로 이동
    });
  }

  void _logout() {
    setState(() {
      _isLoggedIn = false;
      _username = '';
    });

    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (context) => HomeScreen()),
    );
  }

  void _showLoginRequiredDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('로그인 필요'),
          content: Text('로그인 후 접근할 수 있습니다.'),
          actions: <Widget>[
            TextButton(
              child: Text('확인'),
              onPressed: () {
                Navigator.of(context).pop();
                setState(() {
                  _currentIndex = 0; // 홈 화면으로 이동
                });
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    Widget body;
    switch (_currentIndex) {
      case 0:
        body = _isLoggedIn ? HealthTip() : LoginScreen(onLogin: _login);
        break;
      case 1:
        body = _isLoggedIn ? DiagnosisScreen() : Container();
        break;
      case 2:
        body = _isLoggedIn ? ScheduleScreen() : Container();
        break;
      case 3:
        body = _isLoggedIn ? MapScreen() : Container();
        break;
      default:
        body = Container();
    }

    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(50.0), // 앱바 높이 조절
        child: AppBar(
          backgroundColor: Color(0xFF7AA8DA),
          flexibleSpace: Align(
            alignment: Alignment.bottomCenter,
            child: Padding(
              padding: const EdgeInsets.all(0.0),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset(
                    'assets/images/home.jpg',
                    width: 40,
                    height: 40,
                  ),
                  SizedBox(width: 8),
                  Text(
                    'EANAPO',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Spacer(),
                  if (_isLoggedIn)
                    Padding(
                      padding: const EdgeInsets.all(1.0),
                      child: Row(
                        children: [
                          ClipOval(
                            child: Image.asset(
                              'assets/images/child.png',
                              width: 40,
                              height: 40,
                              fit: BoxFit.cover,
                            ),
                          ),
                          SizedBox(width: 8),
                          Text(
                            '$_username',
                            style: TextStyle(color: Colors.white),
                          ),
                        ],
                      ),
                    ),
                  if (!_isLoggedIn)
                    Padding(
                      padding: const EdgeInsets.all(1.0),
                      child: Text(
                        '로그인 상태가 아닙니다.',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  if (_isLoggedIn)
                    IconButton(
                      icon: Icon(Icons.logout, color: Colors.white),
                      onPressed: _logout,
                    ),
                ],
              ),
            ),
          ),
        ),
      ),
      body: body,
      bottomNavigationBar: BottomNavigationBar(
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: '홈',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.health_and_safety),
            label: '진단',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.schedule),
            label: '일정',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.map),
            label: '지도',
          ),
        ],
        currentIndex: _currentIndex,
        onTap: _onTabTapped,
        backgroundColor: Colors.lightBlue[50],
        selectedItemColor: Colors.lightBlue[800],
        unselectedItemColor: Colors.blueGrey,
        showSelectedLabels: true,
        showUnselectedLabels: true,
      ),
    );
  }
}
