import 'package:fl_ks_smart_society_user/localization/localization_const.dart';
import 'package:fl_ks_smart_society_user/theme/theme.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:iconify_flutter/iconify_flutter.dart';
import 'package:iconify_flutter/icons/icomoon_free.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ProfileScreen extends StatefulWidget {
  const ProfileScreen({super.key});

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: whiteColor,
        centerTitle: true,
        titleSpacing: 20.0,
        title: Text(
          tr(context, 'profile.profile'),
          style: medium20Primary,
        ),
      ),
      body: settingsMain(context),
    );
  }

  /// Handle tap on Logout row
  Future<void> _onLogoutPressed() async {
    final prefs = await SharedPreferences.getInstance();
    final phoneNo = prefs.getString('phone_no') ?? '';

    // If phone_no is empty, directly go to login (user already "logged out")
    if (phoneNo.isEmpty) {
      Navigator.pushNamedAndRemoveUntil(
        context,
        '/login',
            (route) => false,
      );
    } else {
      // User is logged in -> show confirm dialog, then logout
      logoutDialog();
    }
  }

  /// Actually perform logout: clear all SharedPreferences and go to /login
  Future<void> _performLogout() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.clear();

    Navigator.pushNamedAndRemoveUntil(
      context,
      '/login',
          (route) => false,
    );
  }

  /// Main settings screen (full width items)
  Widget settingsMain(BuildContext context) {
    final settings = [
      {
        "icon": Icons.person_outline,
        "title": tr(context, 'profile.edit_profile'),
        "action": () => Navigator.pushNamed(context, '/editProfile'),
      },
      {
        "icon": CupertinoIcons.globe,
        "title": tr(context, 'profile.language'),
        "action": () => Navigator.pushNamed(context, '/language'),
      },
      {
        "icon": Icons.list_alt_outlined,
        "title": tr(context, 'profile.terms_and_condition'),
        "action": () => Navigator.pushNamed(context, '/termsAndCondition'),
      },
      {
        "icon": Icons.privacy_tip_outlined,
        "title": tr(context, 'profile.privacy_policy'),
        "action": () => Navigator.pushNamed(context, '/privacyPolicy'),
      },
      {
        "icon": Icons.privacy_tip_outlined,
        "title": tr(context, 'profile.delete'),
        "action": () => Navigator.pushNamed(context, ''),
      },
      /*{
        "icon": Icons.help_outline,
        "title": tr(context, 'profile.help_and_support'),
        "action": () => Navigator.pushNamed(context, '/helpAndSupport'),
      },*/
    ];

    return SafeArea(
      child: ListView(
        padding: const EdgeInsets.symmetric(vertical: fixPadding * 2.0),
        physics: const BouncingScrollPhysics(),
        children: [
          const SizedBox(height: 6.0),

          // Settings rows
          ...settings.map((item) {
            return Padding(
              padding: const EdgeInsets.fromLTRB(
                  fixPadding * 2.0, 0, fixPadding * 2.0, fixPadding),
              child: GestureDetector(
                onTap: item['action'] as VoidCallback?,
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: fixPadding * 1.4,
                    vertical: fixPadding * 1.6,
                  ),
                  decoration: BoxDecoration(
                    color: whiteColor,
                    borderRadius: BorderRadius.circular(12.0),
                    boxShadow: boxShadow,
                  ),
                  child: Row(
                    children: [
                      Icon(
                        item['icon'] as IconData,
                        color: primaryColor,
                        size: 24.0,
                      ),
                      widthSpace,
                      width5Space,
                      Expanded(
                        child: Text(
                          item['title'].toString(),
                          style: regular16Black,
                        ),
                      ),
                      const Icon(
                        Icons.arrow_forward_ios,
                        size: 16.0,
                        color: greyColor,
                      )
                    ],
                  ),
                ),
              ),
            );
          }).toList(),

          // Logout as a main prominent row
          Padding(
            padding: const EdgeInsets.fromLTRB(
              fixPadding * 2.0,
              fixPadding * 1.5,
              fixPadding * 2.0,
              0,
            ),
            child: GestureDetector(
              onTap: _onLogoutPressed,
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: fixPadding * 1.4,
                  vertical: fixPadding * 1.6,
                ),
                decoration: BoxDecoration(
                  color: whiteColor,
                  borderRadius: BorderRadius.circular(12.0),
                  boxShadow: boxShadow,
                ),
                child: Row(
                  children: [
                    const Icon(
                      Icons.logout,
                      color: redColor,
                      size: 24.0,
                    ),
                    widthSpace,
                    width5Space,
                    Expanded(
                      child: Text(
                        tr(context, 'profile.logout'),
                        style: regular16Black,
                      ),
                    ),
                    const Icon(
                      Icons.arrow_forward_ios,
                      size: 16.0,
                      color: greyColor,
                    )
                  ],
                ),
              ),
            ),
          ),

          SizedBox(height: fixPadding * 2.0),
        ],
      ),
    );
  }

  Future<dynamic> logoutDialog() {
    return showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          backgroundColor: whiteColor,
          surfaceTintColor: Colors.transparent,
          insetPadding: const EdgeInsets.all(fixPadding * 3.0),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
          child: ListView(
            shrinkWrap: true,
            physics: const BouncingScrollPhysics(),
            padding: const EdgeInsets.all(fixPadding * 2.0),
            children: [
              Text(
                tr(context, 'profile.logout'),
                style: medium20Primary,
                textAlign: TextAlign.center,
              ),
              heightSpace,
              height5Space,
              Text(
                tr(context, 'profile.logout_text'),
                style: regular17Grey,
                textAlign: TextAlign.center,
              ),
              heightSpace,
              heightSpace,
              Row(
                children: [
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                      },
                      child: Container(
                        padding: const EdgeInsets.all(fixPadding * 1.1),
                        decoration: BoxDecoration(
                          color: whiteColor,
                          borderRadius: BorderRadius.circular(10.0),
                          boxShadow: boxShadow2,
                        ),
                        child: Text(
                          tr(context, 'profile.cancel'),
                          style: medium18Grey,
                          textAlign: TextAlign.center,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ),
                  ),
                  widthSpace,
                  widthSpace,
                  Expanded(
                    child: GestureDetector(
                      onTap: () async {
                        Navigator.pop(context); // Close dialog first
                        await _performLogout();
                      },
                      child: Container(
                        padding: const EdgeInsets.all(fixPadding * 1.1),
                        decoration: BoxDecoration(
                          color: primaryColor,
                          borderRadius: BorderRadius.circular(10.0),
                          boxShadow: buttonShadow,
                        ),
                        child: Text(
                          tr(context, 'profile.logout'),
                          style: medium18White,
                          textAlign: TextAlign.center,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ),
                  ),
                ],
              )
            ],
          ),
        );
      },
    );
  }
}
