import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';
import '../../Notifier/HelpAndEnquiryProvider.dart';
import '../../Utility/AppColors.dart';
import '../Notifier/RentalContactProvider .dart';
import '../Utility/SharedpreferencesService.dart';
import 'authScreen/LoginScreen.dart';

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

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

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

class _ProfileScreenState extends State<ProfileScreen> {
  @override
  void initState() {
    super.initState();

    // Fetch profile data when screen loads
    Future.microtask(() async {
      final profileProvider = Provider.of<RentalProvider>(context, listen: false);
      await profileProvider.fetchProfile(context,widget.accId, widget.sessionId);
    });
  }

  Future<void> onLogout(BuildContext context) async {
    final provider = Provider.of<RentalProvider>(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: "Plus Jakarta Sans",
                    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: "Plus Jakarta Sans",
                    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: "Plus Jakarta Sans",
                            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: "Plus Jakarta Sans",
                                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: "Plus Jakarta Sans",
                      fontWeight: FontWeight.w600,
                      fontSize: 16,
                      color: Colors.grey[800],
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );


    try {
      // Step 4: Call provider to logout
      final deviceDetails = {
        "device_name": "Android Device",
        "os_version": "14",
      };

      await provider.logout(
        context,
        widget.accId,
        widget.sessionId,
      );

      // Step 5: Clear SharedPreferences
      final prefs = SharedPreferencesService.instance;
      await prefs.clearPreferences();

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

      // Step 6: Navigate to login screen with success feedback
      if (context.mounted) {
        // Show success message briefly
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            backgroundColor: AppColors.buttonColor,
            content: Row(
              children: [
                Icon(Icons.check_circle, color: Colors.white, size: 20),
                const SizedBox(width: 8),
                Text(
                  "Logged out successfully",
                  style: TextStyle(
                    fontFamily: "Plus Jakarta Sans",
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
            duration: const Duration(seconds: 2),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        );

        // Navigate after brief delay
        await Future.delayed(const Duration(milliseconds: 1500));

        if (context.mounted) {
          Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(builder: (_) => const LoginScreen()),
                (route) => false,
          );
        }
      }
    } catch (e) {
      // Close loading dialog
      if (context.mounted) Navigator.pop(context);

      // Show error message
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            backgroundColor: Colors.redAccent,
            content: Row(
              children: [
                Icon(Icons.error_outline, color: Colors.white, size: 20),
                const SizedBox(width: 8),
                Text(
                  "Logout failed. Please try again.",
                  style: TextStyle(
                    fontFamily: "Plus Jakarta Sans",
                    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<RentalProvider>(context);
    final profile = profileProvider.profileData;

    return SafeArea(
      top: false,
      child: Scaffold(
        body: profileProvider.isLoading
            ? const Center(child: CircularProgressIndicator())
            : Container(
          color: const Color(0xFFF3F3F3),
          height: MediaQuery.of(context).size.height,
          child: SingleChildScrollView(
            child: Column(
              children: [
                Stack(
                  children: [
                    // Background image
                    Container(
                      width: double.infinity,
                      child: Image.asset(
                        'assets/images/sky_blue_bg.jpg',
                        width: double.infinity,
                        height: 400,
                        fit: BoxFit.cover,
                      ),
                    ),

                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          width: double.infinity,
                          height: 400,
                          decoration: const BoxDecoration(
                            gradient: LinearGradient(
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                              colors: [
                                Color(0x22FFFFFF),
                                Color(0x33FFFFFF),
                                Color(0x88FFFFFF),
                                Color(0xFFF3F3F3),
                                Color(0xFFF3F3F3),
                              ],
                            ),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              const SizedBox(height: 0),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  const SizedBox(width: 20),
                                  InkResponse(
                                    onTap: () {
                                      Navigator.pop(context);
                                    },
                                    child: Container(
                                      width: 32,
                                      height: 32,
                                      color: Colors.transparent,
                                      child: SvgPicture.asset(
                                        "assets/svg/continue_left_ic.svg",
                                        fit: BoxFit.contain,
                                      ),
                                    ),
                                  ),
                                  const SizedBox(width: 5),
                                  Text(
                                    "Profile",
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontFamily: "Poppins",
                                      fontWeight: FontWeight.w400,
                                      color: AppColors.normalText,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 86),
                              //  Profile image
                              Container(
                                height: 140,
                                width: 140,
                                decoration: const BoxDecoration(
                                  color: Color(0xFFE6F6FF),
                                  shape: BoxShape.circle,
                                ),
                                clipBehavior: Clip.antiAlias,
                                child: (profile?.profileUrl?.isNotEmpty ?? false)
                                    ? Image.network(
                                  // You can replace mail with image URL field if you have one
                                  profile!.profileUrl!,
                                  fit: BoxFit.cover,
                                  errorBuilder: (context, error, stackTrace) =>
                                  const Icon(Icons.person, color: Color(0xFF2d2d2d), size: 100),
                                )
                                    : CircleAvatar(
                                  radius: 80,
                                  backgroundColor: Color(0xFFE0F4FF),
                                  child: SvgPicture.asset(
                                    height: 80,
                                    "assets/svg/person_ic.svg",
                                    fit: BoxFit.contain,
                                  ),
                                ),
                              ),
                              const SizedBox(height: 10),
                              Text(
                                profile?.name ?? "User Name",
                                style: TextStyle(
                                  fontSize: 18,
                                  fontFamily: "Poppins",
                                  fontWeight: FontWeight.w500,
                                  color: AppColors.normalText,
                                ),
                              ),
                              const SizedBox(height: 30),
                            ],
                          ),
                        ),

                        // Main info section
                        Container(
                          margin: const EdgeInsets.all(14),
                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 5),
                          decoration: BoxDecoration(
                            color: Colors.transparent,
                            borderRadius: BorderRadius.circular(18),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              _infoItem(
                                iconPath: "assets/svg/phone_ic.svg",
                                title: "Phone No.",
                                value: "+91 ${profile?.mobNum ?? "N/A"}",
                                iconBgColor: const Color(0xFFDFF6E3),
                              ),
                              const SizedBox(height: 16),
                              _infoItem(
                                iconPath: "assets/svg/message_ic.svg",
                                title: "Email ID",
                                value: profile?.mail ?? "N/A",
                                iconBgColor: const Color(0xFFDDEEFF),
                              ),
                              const SizedBox(height: 16),
                              _infoItem(
                                iconPath: "assets/svg/lolipop_ic.svg",
                                title: "Address",
                                value: profile?.address ?? "N/A",
                                iconBgColor: const Color(0xFFFFE9E9),
                              ),
                              const SizedBox(height: 20),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                children: [
                                  _twoColumnItem("State", profile?.state ?? "N/A"),
                                  _twoColumnItem("Sub Locality", profile?.subLocality ?? "N/A"),
                                ],
                              ),
                              const SizedBox(height: 30),

                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
        bottomNavigationBar: Padding(
          padding: const EdgeInsets.all(14),
          child: SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () => onLogout(context),
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.amountText,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(50),
                ),
                padding: const EdgeInsets.symmetric(vertical: 14),
              ),
              child: const Text(
                "Logout",
                style: TextStyle(
                  fontSize: 16,
                  fontFamily: "Plus Jakarta Sans",
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _infoItem({
    required String iconPath,
    required String title,
    required String value,
    required Color iconBgColor,
  }) {
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: iconBgColor,
            borderRadius: BorderRadius.circular(14),
          ),
          child: SvgPicture.asset(iconPath, height: 28, width: 28),
        ),
        const SizedBox(height: 6),
        Text(title,
            style: const TextStyle(
                fontSize: 14, fontWeight: FontWeight.w400, fontFamily: "Plus Jakarta Sans", color: Colors.black87)),
        const SizedBox(height: 2),
        Text(value,
            textAlign: TextAlign.center,
            style: const TextStyle(
                fontSize: 14, fontWeight: FontWeight.w400, fontFamily: "Plus Jakarta Sans", color: Colors.black54)),
      ],
    );
  }

  Widget _twoColumnItem(String title, String value) {
    return Column(
      children: [
        Text(title,
            style: const TextStyle(
                fontSize: 14, fontWeight: FontWeight.w400, fontFamily: "Plus Jakarta Sans", color: Colors.black87)),
        const SizedBox(height: 4),
        Text(value,
            style: const TextStyle(
                fontSize: 14, fontWeight: FontWeight.w400, fontFamily: "Plus Jakarta Sans", color: Colors.black54)),
      ],
    );
  }
}
