import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:gen_rentals/Screens/HelpScreens/OrderHelpScreen.dart';
import 'package:gen_rentals/Screens/HelpScreens/TicketChatScreen.dart';
import 'package:gen_rentals/Utility/Reusablewidgets.dart';
import '../../Notifier/HelpAndEnquiryProvider.dart';
import '../../Utility/AppColors.dart';
import 'package:provider/provider.dart';

import '../Notifier/RentalContactProvider .dart';
import '../Utility/SharedpreferencesService.dart';
import 'authScreen/LoginScreen.dart';


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

  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 ticket list on screen load
    Future.microtask(() async {
      final provider = Provider.of<HelpAndEnquiryProvider>(context, listen: false);
      await provider.fetchTicketList(
        sessionId: widget.sessionId,
        accId: widget.accId,
      );
    });
  }

  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) => Center(
        child: Container(
          padding: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 10,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(
                color: AppColors.buttonColor,
                strokeWidth: 3,
              ),
              const SizedBox(height: 16),
              Text(
                "Logging out...",
                style: TextStyle(
                  fontFamily: "Plus Jakarta Sans",
                  fontWeight: FontWeight.w500,
                  color: Colors.grey[700],
                ),
              ),
            ],
          ),
        ),
      ),
    );

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

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

      // 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) {
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;
    double bottomPadding = MediaQuery.of(context).padding.bottom;
    return SafeArea(
      top: false,
      child: Scaffold(
        body: Container(
          color: const Color(0xFFF3F3F3),
          height: screenHeight,
          child: SingleChildScrollView(
            child: Column(
              children: [
                // Top background image section
                Stack(
                  children: [
                    // Background image
                    Container(
                      width: double.infinity,
                      decoration: BoxDecoration(
                        gradient: const LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [
                            Colors.white54,
                            Color(0xFFF3F3F3),
                          ],
                        ),
                      ),
                      child: Image.asset(
                        'assets/images/sky_blue_bg.jpg',
                        width: double.infinity,
                        height: 400,
                        fit: BoxFit.cover,
                      ),
                    ),

                    // Content overlay
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Header with profile
                        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),
                                  // Profile icon
                                  InkResponse(
                                    onTap: () {
                                      Navigator.pop(context);
                                    },
                                    child: Container(
                                      width: 32,
                                      height: 32,
                                      decoration: BoxDecoration(
                                        color: Colors.transparent,
                                      ),
                                      child: SvgPicture.asset(
                                        "assets/svg/continue_left_ic.svg",
                                        fit: BoxFit.contain,
                                      ),
                                    ),
                                  ),
                                  SizedBox(width: 5,),
                                  Text(
                                    "Profile",
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontFamily: "Poppins",
                                      fontWeight: FontWeight.w400,
                                      color: AppColors.normalText,
                                    ),
                                  ),

                                ],
                              ),
                              SizedBox(height: 120,),
                              Container(
                                height: 140,
                                width: 140,
                                decoration: const BoxDecoration(
                                  color: Color(0xFFE6F6FF),
                                  shape: BoxShape.circle,
                                ),
                                clipBehavior: Clip.antiAlias,
                                child: (widget.accId.isNotEmpty)
                                    ? Image.network(
                                  widget.accId,
                                  fit: BoxFit.cover,
                                  errorBuilder: (context, error, stackTrace) {
                                    return const Icon(Icons.person, color: Color(0xFF2d2d2d), size: 100,);
                                  },
                                  loadingBuilder: (context, child, loadingProgress) {
                                    if (loadingProgress == null) return child;
                                    return const Center(
                                        child: CircularProgressIndicator(strokeWidth: 2));
                                  },
                                )
                                    : CircleAvatar(
                                  radius: 80,
                                  backgroundColor: Colors.blue.shade100,
                                  child: SvgPicture.asset(
                                    "assets/svg/person_ic.svg",
                                    fit: BoxFit.contain,
                                  ),
                                ),
                              ),
                              const SizedBox(height: 10),
                              Text(
                                "Blink Commerce PVT. LTD - TN",
                                style: TextStyle(
                                  fontSize: 16,
                                  fontFamily: "Poppins",
                                  fontWeight: FontWeight.w400,
                                  color: AppColors.normalText,
                                ),
                              ),

                              const SizedBox(height: 10),
                            ],
                          ),
                        ),

                        // Main content section
                        Container(
                          margin: const EdgeInsets.all(14),
                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
                          decoration: BoxDecoration(
                            color: Colors.transparent,
                            borderRadius: BorderRadius.circular(18),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              // 📞 Phone
                              _infoItem(
                                iconPath: "assets/svg/phone_ic.svg",
                                title: "Phone No.",
                                value: "+91 9639919XX",
                                iconBgColor: const Color(0xFFDFF6E3),
                              ),

                              const SizedBox(height: 16),

                              // 📧 Email
                              _infoItem(
                                iconPath: "assets/svg/email_ic.svg",
                                title: "Email ID",
                                value: "xyz@gmail.com",
                                iconBgColor: const Color(0xFFDDEEFF),
                              ),

                              const SizedBox(height: 16),
                              // 📍 Address
                              _infoItem(
                                iconPath: "assets/svg/location_ic.svg", title: "Address",
                                value: "No.1/398 O.M. Road, Navallur, Chennai - 600130",
                                iconBgColor: const Color(0xFFFFE9E9),
                              ),

                              const SizedBox(height: 20),

                              // 🌏 State / Sub locality
                              Center(
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                  children: [
                                    _twoColumnItem("State", "Tamil Nadu"),
                                    _twoColumnItem("Sub Locality", "Chennai"),
                                  ],
                                ),
                              ),

                              const SizedBox(height: 30),

                              // 🚪 Logout Button
                              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: 13,
            fontWeight: FontWeight.w600,
            fontFamily: "Plus Jakarta Sans",
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 2),
        Text(
          value,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 13,
            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: 13,
            fontWeight: FontWeight.w600,
            fontFamily: "Plus Jakarta Sans",
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            fontSize: 13,
            fontWeight: FontWeight.w400,
            fontFamily: "Plus Jakarta Sans",
            color: Colors.black54,
          ),
        ),
      ],
    );
  }


}





