import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:gen_service/Notifiers/AuthProvider.dart';
import 'package:provider/provider.dart';

import '../Utility/AppColors.dart';
import '../Utility/CustomSnackbar.dart';
import '../Utility/SharedpreferencesService.dart';
import 'AuthScreen/LoginScreen.dart';

class DeleteAccountScreen extends StatefulWidget {
  final accId;
  final sessionId;
  const DeleteAccountScreen({super.key,required this.accId,required this.sessionId});

  @override
  State<DeleteAccountScreen> createState() => _DeleteAccountScreenState();
}

class _DeleteAccountScreenState extends State<DeleteAccountScreen> {
  bool _stretch = true;
  late List<String> reasons = [
    "Don’t plan to use My Gen anymore",
    "Already have another account",
    "Concerned about my privacy",
    "The app isn’t working as expected",
    "I want to Opt-out.",
  ];
  var selectedDeleteValue;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      maintainBottomViewPadding: true,
      top: false,
      bottom: Platform.isAndroid,
      child: Scaffold(
        backgroundColor: Color(0xFF4076FF),

        body: CustomScrollView(
          physics: ClampingScrollPhysics(),
          slivers: <Widget>[
            SliverAppBar(
              leading: Container(),
              stretch: _stretch,
              backgroundColor: Color(0xFF4076FF),
              onStretchTrigger: () async {},
              stretchTriggerOffset: 100.0,
              expandedHeight: 70.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: 20,
                            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(
                                        "Delete Account",
                                        overflow: TextOverflow.ellipsis,
                                        maxLines: 1,
                                        style: TextStyle(
                                          fontSize: 16,
                                          color: Colors.white,
                                          height: 1.1,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),

                              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
                        Text(
                          "Do you want to Delete Your Account",
                          style: TextStyle(fontSize: 16),
                        ),
                        const SizedBox(height: 5),

                        Text(
                          "select your reason to delete your account",
                          style: TextStyle(
                            fontSize: 12,
                            color: AppColors.subtitleText,
                          ),
                        ),
                        const SizedBox(height: 15),
                        ...List.generate(reasons.length, (index) {
                          return InkWell(
                            onTap: () {
                              setState(() {
                                selectedDeleteValue = reasons[index];
                              });

                              _showDeleteConfirmationBottomSheet(context);
                            },
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                SizedBox(height: 5),
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: [
                                    (selectedDeleteValue == reasons[index])
                                        ? SvgPicture.asset(
                                          "assets/svg/checkbox-checked.svg",
                                          height: 17,
                                        )
                                        : SvgPicture.asset(
                                          "assets/svg/checkbox.svg",
                                          height: 17,
                                        ),
                                    SizedBox(width: 10),
                                    SizedBox(
                                      child: Text(
                                        reasons[index]!,
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          color: AppColors.nearDarkText,
                                          fontWeight: FontWeight.w500,
                                          fontSize: 12,
                                        ),
                                      ),
                                    ),
                                    // Spacer(),
                                    // SvgPicture.asset(
                                    //   "assets/images/next_button.svg",
                                    //   height: 13,
                                    // ),
                                  ],
                                ),
                                SizedBox(height: 5),
                              ],
                            ),
                          );
                        }),
                        Spacer(),
                        Align(
                          alignment: Alignment.bottomCenter,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              SvgPicture.asset(
                                "assets/svg/genservice_full.svg",
                                height: 50,
                              ),
                              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,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _showDeleteConfirmationBottomSheet(context) async {
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;

    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(15.0)),
      ),
      isScrollControlled: true,
      builder: (BuildContext context) {
        return SafeArea(
          child: StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return Padding(
                padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context).viewInsets.bottom,
                  top: 16,
                  left: 16,
                  right: 16,
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Center(
                      child: Container(
                        width: 40,
                        height: 4,
                        decoration: BoxDecoration(
                          color: Colors.grey[300],
                          borderRadius: BorderRadius.circular(4),
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                    SizedBox(height: 10),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 10),
                      width: MediaQuery.of(context).size.width * 0.8,
                      child: Text(
                        "Uh-oh! Are you sure you want to delete your account?",
                        maxLines: 2,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 14,
                          color: AppColors.nearDarkText,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ),
                    SizedBox(height: 10),
                    Text(
                      "All your data will be permanently deleted",
                      style: TextStyle(
                        color: AppColors.subtitleText,
                        fontSize: 12,
                      ),
                    ),
                    SizedBox(height: 20),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Container(
                          width: 170,
                          height: 38,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border.all(
                              color: AppColors.subtitleText,
                              width: 0.3,
                            ),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: TextButton(
                            style: ButtonStyle(
                              overlayColor: MaterialStatePropertyAll(
                                Colors.transparent,
                              ),
                            ),
                            onPressed: () {
                              Navigator.pop(context);
                              showDialog(
                                context: context,
                                builder:
                                    (_) => AlertDialog.adaptive(
                                      title: Text("Request Received"),
                                      content: Text(
                                        "Your account deletion request has been recorded. "
                                        "We will process it within 24–48 hours.",
                                      ),
                                      actions: [
                                        TextButton(
                                          onPressed: () async {
                                            // Navigator.pop(context);
                                            final provider = Provider.of<AuthProvider>(
                                              context,
                                              listen: false,
                                            );
                                            try {
                                              final success = await provider
                                                  .logout(
                                                    widget.accId,
                                                    widget.sessionId,
                                                  );

                                              if (context.mounted) {
                                                Navigator.pop(context);
                                              }

                                              if (success) {
                                                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 {

                                                if (context.mounted) {
                                                  CustomSnackBar.showError(
                                                    context: context,
                                                    message:
                                                        "Logout failed. Please try again.",
                                                  );
                                                }
                                              }
                                            } catch (e) {
                                              if (context.mounted) {
                                                CustomSnackBar.showError(
                                                  context: context,
                                                  message:
                                                      "An error occurred. Please try again.",
                                                );
                                              }
                                            }
                                          },
                                          child: Text("OK"),
                                        ),
                                      ],
                                    ),
                              );
                            },

                            child: Text(
                              "Yep, delete me!",
                              style: TextStyle(
                                fontSize: 12,
                                color: AppColors.nearDarkText,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ),
                        Container(
                          width: 170,
                          height: 38,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: AppColors.buttonColor,
                          ),
                          child: TextButton(
                            style: ButtonStyle(
                              overlayColor: MaterialStatePropertyAll(
                                Colors.transparent,
                              ),
                            ),
                            onPressed: () {
                              Navigator.pop(context);
                            },
                            child: const Text(
                              "Nope, take me back!",
                              style: TextStyle(
                                fontSize: 13,
                                fontFamily: "MontserratSemiBold",
                                color: Colors.white,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 10),
                  ],
                ),
              );
            },
          ),
        );
      },
    );
  }
}
