// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import 'package:qadirneyriz/config/config.dart';
import 'package:qadirneyriz/screens/aboutUs/screen.dart';
import 'package:qadirneyriz/screens/auth/state/state.dart';
import 'package:qadirneyriz/screens/change_pass/screen.dart';
import 'package:qadirneyriz/screens/home/screen.dart';
import 'package:qadirneyriz/screens/home/state.dart';
import 'package:qadirneyriz/screens/meeting/screen.dart';
import 'package:qadirneyriz/screens/private_meeting/screen.dart';
import 'package:qadirneyriz/screens/report/screen.dart';

import 'package:qadirneyriz/setting/setting.dart';

class CustomDrawerNavigation extends StatefulWidget {
  final int activeTab;

  const CustomDrawerNavigation({super.key, required this.activeTab});

  @override
  _CustomDrawerNavigationState createState() => _CustomDrawerNavigationState();
}

class _CustomDrawerNavigationState extends State<CustomDrawerNavigation> {
  late final PageController _pageController;
  int _selectedIndex = 0;
  final String language = setting.userLocalDb.getUser().language;
  String? selectedLanguage; // زبان پیش‌فرض فارسی
  late AuthState state;
  @override
  void initState() {
    super.initState();
    state = Provider.of(context, listen: false);
    selectedLanguage = language;
    _selectedIndex = widget.activeTab;
    _pageController = PageController(initialPage: _selectedIndex);
  }

  final List<Widget> _bottomBarPages = [
    const HomeScreen(),
    const MeetingsScreen(),
    const PrivateMeetingsScreen(),
    const ReportScreen(),
    const ChangePassScreen(),
    const AboutUsScreen()
    // Add more screens here
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
    _pageController.jumpToPage(index);
    Navigator.pop(context); // Close the drawer
  }

  @override
  Widget build(BuildContext context) {
    final userRole = setting.userLocalDb.getUser().role;
    return Scaffold(
      // backgroundColor: Colors.green.withOpacity(.2),
      drawer: Consumer<AuthState>(
        builder: (context, value, child) {
          return Drawer(
            backgroundColor: config.ui.backGroundColor,
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 10, vertical: 35),
                    child: Image.asset(
                      'assets/images/D2.png', // مسیر لوگوی شما
                      height: 60,
                    ),
                  ),
                  if (userRole == 0 || userRole == 2)
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 5),
                      child: Row(
                        children: [
                          Expanded(
                            child: Consumer<HomeState>(
                              builder: (context, value, child) {
                                return NewSessionButton(
                                  title:
                                      AppLocalizations.of(context)!.newmeeting,
                                  icon: Icons.person_outlined,
                                  onPressed: () async {
                                    await context.pushNamed('meetingadd');
                                    value.getTodayMeetings();
                                  },
                                );
                              },
                            ),
                          ),
                          Expanded(
                            child: NewSessionButton(
                              title: AppLocalizations.of(context)!
                                  .newprivatemeeting,
                              icon: Icons.people_outlined,
                              onPressed: () {
                                context.pushNamed('privatemeetingadd');
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 50),
                    child: ListView(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      padding: EdgeInsets.zero,
                      children: <Widget>[
                        _buildDrawerItem(
                          icon: FontAwesomeIcons.house,
                          text: AppLocalizations.of(context)!.home,
                          index: 0,
                        ),
                        _buildDrawerItem(
                          icon: FontAwesomeIcons.peopleGroup,
                          text: AppLocalizations.of(context)!.meetings,
                          index: 1,
                        ),
                        _buildDrawerItem(
                          icon: FontAwesomeIcons.calendar,
                          text: AppLocalizations.of(context)!.privatemeeting,
                          index: 2,
                        ),
                        _buildDrawerItem(
                          icon: FontAwesomeIcons.chartColumn,
                          text: AppLocalizations.of(context)!.reports,
                          index: 3,
                        ),
                        _buildDrawerItem(
                          icon: FontAwesomeIcons.person,
                          text: AppLocalizations.of(context)!.profile,
                          index: 4,
                        ),
                        _buildDrawerItem(
                          icon: FontAwesomeIcons.info,
                          text: AppLocalizations.of(context)!.aboutus,
                          index: 5,
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Container(
                      decoration: BoxDecoration(
                        color: config.ui.secendGreen.withOpacity(.1),
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            _buildLanguageButton('fa', 'فارسی', () {
                              value.setLocale('fa');
                            }),
                            _buildLanguageButton('en', 'English', () {
                              value.setLocale('en');
                            }),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
      body: Container(
        decoration: BoxDecoration(
          color: config.ui.backGroundColor,
        ),
        child: PageView(
          controller: _pageController,
          physics: const NeverScrollableScrollPhysics(),
          children: _bottomBarPages,
        ),
      ),
    );
  }

  Widget _buildDrawerItem(
      {required IconData icon, required String text, required int index}) {
    bool isSelected = _selectedIndex == index;
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
      child: Material(
        color: isSelected
            ? config.ui.secendGreen.withOpacity(.1)
            : Colors.transparent,
        borderRadius: BorderRadius.circular(8),
        child: InkWell(
          borderRadius: BorderRadius.circular(8),
          onTap: () => _onItemTapped(index),
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
            ),
            child: ListTile(
              leading: FaIcon(
                icon,
                size: 19,
                color: isSelected ? config.ui.secendGreen : config.ui.mainGray,
              ),
              title: Text(
                text,
                style: TextStyle(
                    color:
                        isSelected ? config.ui.secendGreen : config.ui.mainGray,
                    fontWeight:
                        isSelected ? FontWeight.bold : FontWeight.normal,
                    fontSize: 15),
              ),
              selected: isSelected,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildLanguageButton(
      String language, String text, void Function() onPressed) {
    bool isSelected = selectedLanguage == language;

    return ElevatedButton(
      onPressed: () {
        setState(() {
          selectedLanguage = language; // به‌روز کردن زبان انتخاب شده
        });
        onPressed(); // اجرای متد تغییر زبان
      },
      style: ElevatedButton.styleFrom(
        backgroundColor: isSelected ? Colors.green : Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(5.0),
        ),
      ),
      child: Text(
        text,
        style: TextStyle(
            color: isSelected ? Colors.white : Colors.black, fontSize: 13),
      ),
    );
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }
}

class NewSessionButton extends StatelessWidget {
  final void Function()? onPressed;
  final String title;
  final IconData icon;
  const NewSessionButton({
    Key? key,
    this.onPressed,
    required this.title,
    required this.icon,
  }) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 5),
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: config.ui.mainGreen, // رنگ لبه‌ها
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8), // گرد کردن گوشه‌ها
          ),
          elevation: 0, // بدون سایه
          padding: EdgeInsets.symmetric(vertical: 20, horizontal: 16),
        ),
        onPressed: onPressed,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              icon,
              color: Colors.white, // رنگ آیکون
              size: 40,
            ),
            SizedBox(height: 8),
            Text(
              title,
              style: TextStyle(
                color: Colors.white, // رنگ متن
                fontSize: 11,
                fontWeight: FontWeight.normal,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
