import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:gen_service/Screens/AuthScreen/LoginScreen.dart';
import 'package:gen_service/Utility/CustomSnackbar.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../Notifiers/AuthProvider.dart';
import '../Notifiers/DashboardProvider.dart';
import '../Utility/AppColors.dart';
import '../Utility/SharedpreferencesService.dart';

class ProfileScreen extends StatefulWidget {
  final String accId;
  final String sessionId;

  const ProfileScreen({
    Key? key,
    required this.accId,
    required this.sessionId,
  }) : super(key: key);

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

class _ProfileScreenState extends State<ProfileScreen> {
  bool _stretch = true;
  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      final profileProvider = Provider.of<DashboardProvider>(context, listen: false);
      profileProvider.fetchProfile(widget.accId, widget.sessionId);
    });
  }


  Future<void> onLogout(BuildContext context) async {
    final provider = Provider.of<AuthProvider>(context, listen: false);

    // 🧭 Step 1: Ask confirmation
    final confirm = await showDialog<bool>(
      context: context,
      builder: (context) {
        return Dialog(
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          elevation: 0,
          child: Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 20,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // Icon
                Container(
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                    color: AppColors.buttonColor.withOpacity(0.1),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    Icons.logout_rounded,
                    color: AppColors.buttonColor,
                    size: 30,
                  ),
                ),
                const SizedBox(height: 16),

                // Title
                Text(
                  "Logout",
                  style: TextStyle(
                    fontFamily: "Poppins",
                    fontWeight: FontWeight.w700,
                    fontSize: 20,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 8),

                // Subtitle
                Text(
                  "Are you sure you want to logout?",
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontFamily: "Poppins",
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                    color: Colors.grey[600],
                    height: 1.4,
                  ),
                ),
                const SizedBox(height: 24),

                // Buttons Row
                Row(
                  children: [
                    // Cancel Button
                    Expanded(
                      child: OutlinedButton(
                        onPressed: () => Navigator.pop(context, false),
                        style: OutlinedButton.styleFrom(
                          backgroundColor: Colors.transparent,
                          foregroundColor: Colors.grey[600],
                          side: BorderSide(
                            color: Colors.grey[300]!,
                            width: 1.5,
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 14),
                          elevation: 0,
                        ),
                        child: Text(
                          "Cancel",
                          style: TextStyle(
                            fontFamily: "Poppins",
                            fontWeight: FontWeight.w600,
                            fontSize: 14,
                            color: Colors.grey[700],
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),

                    // Logout Button
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () => Navigator.pop(context, true),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppColors.buttonColor,
                          foregroundColor: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 14),
                          elevation: 0,
                          shadowColor: Colors.transparent,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              "Logout",
                              style: TextStyle(
                                fontFamily: "Poppins",
                                fontWeight: FontWeight.w600,
                                fontSize: 14,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );

    // Step 2: If user cancelled, just return
    if (confirm != true) return;

    // Step 3: Show loading indicator
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 3, sigmaY: 3),
          child: Dialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            backgroundColor: Colors.white.withOpacity(0.9),
            child: Padding(
              padding: const EdgeInsets.all(24),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  CircularProgressIndicator(
                    color: AppColors.buttonColor,
                    strokeWidth: 3,
                  ),
                  const SizedBox(height: 20),
                  Text(
                    "Logging out...",
                    style: TextStyle(
                      fontFamily: "Poppins",
                      fontWeight: FontWeight.w600,
                      fontSize: 16,
                      color: Colors.grey[800],
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );


    try {
      final success = await provider.logout(
        widget.accId,
        widget.sessionId,
      );

      // Close loading dialog
      if (context.mounted) Navigator.pop(context);

      if (success) {
        // ✅ Success — clear shared prefs
        final prefs = SharedPreferencesService.instance;
        await prefs.clearPreferences();

        if (context.mounted) {
          CustomSnackBar.showSuccess(
              context: context,
              message: "Logged out successfully"
          );

          await Future.delayed(const Duration(milliseconds: 1500));

          Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(builder: (_) => const LoginScreen()),
                (route) => false,
          );
        }
      } else {
        // ❌ Logout failed — show error snackbar
        if (context.mounted) {
          CustomSnackBar.showError(
              context: context,
              message: "Logout failed. Please try again."
          );
        }
      }
    } catch (e) {
      // Handle exceptions
      if (context.mounted) Navigator.pop(context);

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          backgroundColor: Colors.redAccent,
          content: Row(
            children: [
              const Icon(Icons.error_outline, color: Colors.white, size: 20),
              const SizedBox(width: 8),
              Text(
                "Logout failed: ${e.toString()}",
                style: const TextStyle(
                  fontFamily: "Poppins",
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
          duration: const Duration(seconds: 3),
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
        ),
      );
    }

  }


  @override
  Widget build(BuildContext context) {

    final profileProvider = Provider.of<DashboardProvider>(context);
    final authProvider = Provider.of<AuthProvider>(context);

    final isLoading = profileProvider.isLoading;
    final error = profileProvider.errorMessage;
    final data = profileProvider.profileData?.details;

    if (isLoading) {
      return const Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        body: Center(
          child: CircularProgressIndicator(color: AppColors.buttonColor,),
        ),
      );
    }

    if (error != null) {
      return Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        body: Center(
          child: Text(
            error,
            style: const TextStyle(color: Colors.red, fontSize: 16),
          ),
        ),
      );
    }

    if (data == null) {
      return const Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        body: Center(
          child: Text("No data found."),
        ),
      );
    }

    return RefreshIndicator.adaptive(
      color: AppColors.amountText,
      onRefresh: () async {
        await Future.delayed(const Duration(milliseconds: 600));
        Provider.of<DashboardProvider>(context, listen: false);
        profileProvider.fetchDashboard(widget.accId, widget.sessionId);
      },
      child: Scaffold(
        backgroundColor: Color(0xFF4076FF),
        body: CustomScrollView(
          physics:  ClampingScrollPhysics(),
          slivers: <Widget>[
            SliverAppBar(
              leading: Container(),
              stretch: _stretch,
              backgroundColor: Color(0xFF4076FF),
              onStretchTrigger: () async {
                // Refresh data when pulled down
                final profileProvider =
                Provider.of<DashboardProvider>(context, listen: false);
                profileProvider.fetchProfile(widget.accId, widget.sessionId);
              },
              stretchTriggerOffset: 300.0,
              expandedHeight: 245.0,
              flexibleSpace: LayoutBuilder(
                builder: (context, constraints) {
                  final top = constraints.biggest.height;
                  return FlexibleSpaceBar(
                    stretchModes: const [
                      StretchMode.zoomBackground,
                      StretchMode.blurBackground,
                    ],
                    background: GestureDetector(

                      child: Container(
                        width: double.infinity,
                        decoration: const BoxDecoration(gradient: AppColors.backgroundGradient),
                        child: SafeArea(
                          bottom: false,
                          child: Padding(
                            padding: const EdgeInsets.only(top: 20, bottom: 25, left: 20, right: 20),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                // Profile Image
                                Container(
                                  height: 80,
                                  width: 80,
                                  decoration: const BoxDecoration(
                                    color: Color(0xFFE6F6FF),
                                    shape: BoxShape.circle,
                                  ),
                                  clipBehavior: Clip.antiAlias,
                                  child: (data.profileImg?.isNotEmpty == true)
                                      ? Image.network(
                                    data.profileImg.toString(),
                                    fit: BoxFit.cover,
                                    errorBuilder: (context, error, stackTrace) =>
                                        CircleAvatar(
                                          radius: 40,
                                          backgroundColor: const Color(0xFFE0F4FF),
                                          child: SvgPicture.asset(
                                            height: 40,
                                            "assets/svg/person_ic.svg",
                                            fit: BoxFit.contain,
                                          ),
                                        ),
                                  )
                                      : CircleAvatar(
                                    radius: 40,
                                    backgroundColor: const Color(0xFFE0F4FF),
                                    child: SvgPicture.asset(
                                      height: 40,
                                      "assets/svg/person_ic.svg",
                                      fit: BoxFit.contain,
                                    ),
                                  ),
                                ),
                                const SizedBox(height: 16),
                                Flexible(
                                  child: Text(
                                    data.name.toString(),
                                    style: const TextStyle(
                                      color: Colors.white,
                                      fontSize: 20,
                                      fontWeight: FontWeight.w600,
                                    ),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                const SizedBox(height: 8),
                                Text(
                                  '+91 ${data.mobNum}',
                                  style: TextStyle(
                                    color: Colors.white.withOpacity(0.9),
                                    fontSize: 14,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),

                                SizedBox(height: 12,),
                                InkResponse(
                                  onTap: () => onLogout(context),
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
                                    decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.circular(20),
                                    ),
                                    child: const Text(
                                      " Logout ",
                                      style: TextStyle(
                                        color: AppColors.normalText,
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ),
                                ),

                                SizedBox(height: 2,),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),

            // Body content
            SliverToBoxAdapter(
              child: Container(
                padding: const EdgeInsets.only(top: 1, bottom: 0),
                color: Colors.transparent,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 0),
                  decoration: const BoxDecoration(
                    color: AppColors.backgroundRegular,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(30),
                      topRight: Radius.circular(30),
                    ),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const SizedBox(height: 20),

                        // email
                        _buildItemRow(
                          icon: "assets/svg/message_ic.svg",
                          iconBg: Color(0xFFDFF8FF),
                          title: "Email ID",
                          subTitle: data.email.toString()
                        ),
                        const SizedBox(height: 8),
                        // address
                        _buildItemRow(
                            icon: "assets/svg/lolipop_ic.svg",
                            iconBg: Color(0xFFFFE5E5),
                            title: "Address",
                            subTitle: data.address.toString()
                        ),

                        const SizedBox(height: 4),
                        // state
                        _buildItemRow(
                            icon: "assets/svg/pay_card_ic.svg",
                            iconBg: Color(0xFFDFF8FF),
                            title: "State",
                            subTitle: data.state.toString()
                        ),
                        const SizedBox(height: 4),
                        // sub local
                        _buildItemRow(
                            icon: "assets/svg/pay_card_ic.svg",
                            iconBg: Color(0xFFDFF8FF),
                            title: "Sub Locality",
                            subTitle: data.locality.toString()
                        ),
                        const SizedBox(height: 120),

                        Padding(
                          padding: const EdgeInsets.only( bottom: 10, left: 20, right: 20),
                          child: Center(
                            child: Column(
                              children: [
                                SvgPicture.asset(
                                  "assets/svg/genesis_logo_2io.svg",
                                  height: 55,
                                  color: AppColors.buttonColor,
                                ),
                                SizedBox(height: 12,),
                                Text(
                                  'Genesis Poweronics PVT. Ltd.',
                                  style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w400,
                                      color: AppColors.subtitleText),
                                ),
                                Text(
                                  'App Version 1.0',
                                  style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w400,
                                      color: AppColors.subtitleText),
                                ),

                              ],
                            ),
                          ),
                        ),
                        const SizedBox(height: 80),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );


  }




  Widget _buildItemRow({
    required String icon,
    required Color iconBg,
    required String title,
    required String subTitle,
  }) {
    return Container(
      padding: EdgeInsets.all(16),
      child: Row(
        children: [
          if(title != "State" && title != "Sub Locality")
          Container(
            padding: EdgeInsets.all(title =="Address" ? 8 :12),
            decoration: BoxDecoration(
              color: iconBg,
              borderRadius: BorderRadius.circular(18)
            ),
            child: SvgPicture.asset(
              height: title =="Address" ? 34: 26,
              icon,
              fit: BoxFit.contain,
            ),
          ),
          if(title != "Email ID" && title != "Address")
            Expanded(
              flex: 1,
              child: Container(
                padding: EdgeInsets.all(14),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(18)
                ),
                child: SizedBox(
                  width: 24,
                  height: 24,
                ),
              ),
            ),
          SizedBox(width: 14,),
          Expanded(
            flex: 7,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: TextStyle(
                    color: AppColors.normalText,
                    fontWeight: FontWeight.w400,
                    fontSize: 14,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Text(
                  subTitle,
                  maxLines: 4,
                  style: TextStyle(
                    color: AppColors.subtitleText,
                    fontWeight: FontWeight.w400,
                    fontSize: 14,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }





}
