import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.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: Padding(
            padding: const EdgeInsets.all(24.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Error Icon
                Container(
                  width: 120,
                  height: 120,
                  decoration: BoxDecoration(
                    color: Colors.red.withOpacity(0.1),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    Icons.error_outline_rounded,
                    size: 60,
                    color: Colors.red,
                  ),
                ),

                const SizedBox(height: 24),

                // Error Title
                const Text(
                  "Oops! Something went wrong",
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                    fontFamily: "Poppins",
                  ),
                ),

                const SizedBox(height: 12),

                // Error Message
                Text(
                  error,
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                    fontSize: 14,
                    color: Colors.grey,
                    fontFamily: "Poppins",
                    height: 1.4,
                  ),
                ),

                const SizedBox(height: 32),

                // Retry Button
                ElevatedButton.icon(
                  onPressed: () async {
                    // Show loading state
                    setState(() {});

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

                    // Retry fetching data
                    final dashboardProvider =
                    await Future.delayed(const Duration(milliseconds: 600));
                    Provider.of<DashboardProvider>(context, listen: false);
                    profileProvider.fetchDashboard(widget.accId, widget.sessionId);
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.buttonColor,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(
                      horizontal: 24,
                      vertical: 12,
                    ),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(25),
                    ),
                    elevation: 2,
                  ),
                  icon: const Icon(Icons.refresh_rounded, size: 20),
                  label: const Text(
                    "Try Again",
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                      fontFamily: "Poppins",
                    ),
                  ),
                ),

                const SizedBox(height: 16),

                // Alternative Action
                TextButton(
                  onPressed: () {
                    // Go back or navigate to home
                    Navigator.maybePop(context);
                  },
                  child: const Text(
                    "Go Back",
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey,
                      fontFamily: "Poppins",
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }

    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: 340.0,
              expandedHeight: 300.0,
              flexibleSpace: LayoutBuilder(
                builder: (context, constraints) {
                  final top = constraints.biggest.height;
                  return FlexibleSpaceBar(
                    stretchModes: const [
                      StretchMode.zoomBackground,
                      StretchMode.blurBackground,
                    ],
                    background: 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: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  InkResponse(
                                    onTap: () {
                                      HapticFeedback.selectionClick();
                                      Navigator.pop(context, true);
                                    },
                                    child: SvgPicture.asset(
                                      "assets/svg/appbar_back.svg",
                                      height: 25,
                                    ),
                                  ),
                                  SizedBox(width: 10),
                                  Expanded(
                                    flex: 4,
                                    child: InkResponse(
                                      onTap: () {
                                        HapticFeedback.selectionClick();

                                        Navigator.pop(context, true);
                                      },
                                      child: Text(
                                        "Profile",
                                        overflow: TextOverflow.ellipsis,
                                        maxLines: 1,
                                        style: TextStyle(
                                          fontSize: 16,
                                          color: Colors.white,
                                          height: 1.1,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              // 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),
                              Text(
                                data.name.toString(),
                                style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: 22,
                                  fontWeight: FontWeight.w400,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              const SizedBox(height: 8),
                              Text(
                                '+91 ${data.mobNum}',
                                style: TextStyle(
                                  fontWeight: FontWeight.w400,
                                  color: Colors.white.withOpacity(0.9),
                                  fontSize: 16,
                                ),
                                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.w600,
                                      fontSize: 14,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                ),
                              ),

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

            // Body content
            SliverFillRemaining(
              hasScrollBody: false,
              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
                        if (data.email != "" && data.email != null)
                        _buildItemRow(
                            icon: "assets/svg/message_ic.svg",
                            iconBg: Color(0xFFDFF8FF),
                            title: "Email ID",
                            subTitle: data.email.toString()
                        ),
                        // address
                        _buildItemRow(
                            icon: "assets/svg/lolipop_ic.svg",
                            iconBg: Color(0xFFFFE5E5),
                            title: "Address",
                            subTitle: data.address.toString()
                        ),
                        // state
                        _buildItemRow(
                            icon: "assets/svg/pay_card_ic.svg",
                            iconBg: Color(0xFFDFF8FF),
                            title: "State",
                            subTitle: data.state.toString()
                        ),
                        // sub local
                        _buildItemRow(
                            icon: "assets/svg/pay_card_ic.svg",
                            iconBg: Color(0xFFDFF8FF),
                            title: "Sub Locality",
                            subTitle: data.locality.toString()
                        ),

                        Spacer(),
                        Align(
                          alignment: Alignment.bottomCenter,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              SvgPicture.asset(
                                "assets/svg/gensis_latest_logo.svg",
                                height: 58,
                                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),
                              ),

                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );


  }




  Widget _buildItemRow({
    required String icon,
    required Color iconBg,
    required String title,
    required String subTitle,
  }) {
    final isShow = title != "Sub Locality" && title != "State";
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16,vertical: 8),
      child: Row(
        children: [

          Container(
            padding: EdgeInsets.all(title =="Address" ? 8 :12),
            decoration: BoxDecoration(
                color: isShow ?  iconBg : Colors.transparent,
                borderRadius: BorderRadius.circular(18)
            ),
            child: SvgPicture.asset(
              height: title =="Address" ? 34: 26,
              icon,
              fit: BoxFit.contain,
            ),
          ),

          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,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }





}
