import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:gen_service/Notifiers/HelpAndComplaintProvider.dart';
import 'package:gen_service/Utility/CustomSnackbar.dart';
import 'package:provider/provider.dart';
import '../../Utility/AppColors.dart';
import 'package:dropdown_button2/dropdown_button2.dart';

class AddComplaintScreen extends StatefulWidget {
  final String accId;
  final String sessionId;
  final String product;
  final String hashId;


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

  @override
  State<AddComplaintScreen> createState() => _AddComplaintScreenState();
}

class _AddComplaintScreenState extends State<AddComplaintScreen> {
  bool _stretch = true;

  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      final provider =
      Provider.of<HelpAndComplaintProvider>(context, listen: false);
      provider.fetchComplaintDropdowns(
        accId: widget.accId,
        sessionId: widget.sessionId,
        genId: widget.hashId
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<HelpAndComplaintProvider>(context);
    final isLoading = provider.isLoading;
    final error = provider.errorMessage;

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

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

    return Scaffold(
      backgroundColor: Colors.white,
      body: CustomScrollView(
        physics: const ClampingScrollPhysics(),
        slivers: <Widget>[
          /// App bar section
          SliverAppBar(
            leading: Container(),
            stretch: _stretch,
            backgroundColor: const Color(0xFF4076FF),
            onStretchTrigger: () async {},
            stretchTriggerOffset: 300.0,
            flexibleSpace: FlexibleSpaceBar(
              stretchModes: const [
                StretchMode.zoomBackground,
                StretchMode.blurBackground,
              ],
              background: Container(
                decoration: const BoxDecoration(gradient: AppColors.commonAppBarGradient),
                child: Padding(
                  padding:
                  const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      InkResponse(
                        onTap: () => Navigator.pop(context, true),
                        child: SvgPicture.asset(
                          "assets/svg/continue_left_ic.svg",
                          height: 30,
                          color: Colors.white,
                        ),
                      ),
                      const SizedBox(width: 10),
                      const Text(
                        "Help?",
                        style: TextStyle(
                          fontSize: 16,
                          fontFamily: "Poppins",
                          fontWeight: FontWeight.w400,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),

          /// Main content
          SliverToBoxAdapter(
            child: Container(
              color: AppColors.backgroundBottom,
              child: Container(
                padding:
                const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(30),
                    topRight: Radius.circular(30),
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Padding(
                      padding: EdgeInsets.all(10.0),
                      child: Text(
                        "Raise Complaint",
                        style: TextStyle(
                          fontSize: 16,
                          fontFamily: "PoppinsMedium",
                          fontWeight: FontWeight.w500,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                    const SizedBox(height: 2),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(
                                flex: 6,
                                child: Text(
                                  widget.product,
                                  maxLines: 2,
                                  style: TextStyle(
                                    fontSize: 14,
                                    fontWeight: FontWeight.w400,
                                    color: AppColors.amountText,
                                  ),
                                ),
                              ),
                              const SizedBox(width: 2),
                              Container(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 18, vertical: 8),
                                decoration: BoxDecoration(
                                  color: AppColors.stripSky,
                                  borderRadius: BorderRadius.circular(12),
                                ),
                                child: Text(
                                  "#${widget.hashId} | ${provider.dropDownsListResponse?.genDetails?.modelName}",
                                  style: const TextStyle(
                                    fontSize: 13,
                                    fontWeight: FontWeight.w400,
                                    color: Colors.black87,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const Divider()
                        ],
                      ),
                    ),
                    const SizedBox(height: 10),
                    _ComplaintForm(
                      accId: widget.accId,
                      sessionId: widget.sessionId,
                      genId: widget.hashId,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _ComplaintForm extends StatefulWidget {
  final String accId;
  final String sessionId;
  final String genId;

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

  @override
  State<_ComplaintForm> createState() => _ComplaintFormState();
}

class _ComplaintFormState extends State<_ComplaintForm> {
  String? _selectedCategory;
  String? _selectedDescription;
  final TextEditingController _noteController = TextEditingController();

  String? _categoryError;
  String? _descriptionError;
  String? _noteError;

  @override
  void initState() {
    super.initState();
    _noteController.addListener(() {
      if (_noteController.text.isNotEmpty && _noteError != null) {
        setState(() => _noteError = null);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<HelpAndComplaintProvider>(context);
    final dropdownData = provider.dropDownsListResponse;

    final categories = dropdownData?.categories ?? [];
    final descriptions = dropdownData?.descriptions ?? [];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          "Category",
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w400,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 6),
        Container(
          decoration: BoxDecoration(
            color: AppColors.fieldsGrey,
            borderRadius: BorderRadius.circular(8),
          ),
          child: DropdownButtonHideUnderline(
            child: DropdownButton2<String>(
              isExpanded: true,
              value: _selectedCategory,
              hint: const Padding(
                padding: EdgeInsets.symmetric(horizontal: 12),
                child: Text(
                  "Select Complaint Category",
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey,
                  ),
                ),
              ),
              items: categories
                  .map((cat) => DropdownMenuItem<String>(
                value: cat.id,
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  child: Text(
                    cat.name ?? "",
                    style: TextStyle(fontSize: 14, color: AppColors.normalText,),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ))
                  .toList(),
              onChanged: (value) {
                setState(() {
                  _selectedCategory = value;
                  _categoryError = null;
                });
              },
              buttonStyleData: ButtonStyleData(
                height: 48,
                width: double.infinity,
                padding: const EdgeInsets.symmetric(horizontal: 12),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: AppColors.fieldsGrey,
                ),
              ),
              dropdownStyleData: DropdownStyleData(
                maxHeight: 200,
                width: MediaQuery.of(context).size.width - 40, // Match field width
                padding: const EdgeInsets.symmetric(vertical: 8),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 8,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                elevation: 8,
                offset: const Offset(0, -8),
              ),
              menuItemStyleData: const MenuItemStyleData(
                height: 40,
                padding: EdgeInsets.symmetric(horizontal: 12),
              ),
              iconStyleData: const IconStyleData(
                icon: Icon(Icons.arrow_drop_down),
                iconSize: 24,
              ),
            ),
          ),
        ),
        if (_categoryError != null) ...[
          const SizedBox(height: 4),
          Text(
            _categoryError!,
            style: const TextStyle(
              color: Colors.red,
              fontSize: 12,
            ),
          ),
        ],

        const SizedBox(height: 16),

        const Text(
          "Description",
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w400,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 6),
        Container(
          decoration: BoxDecoration(
            color: AppColors.fieldsGrey,
            borderRadius: BorderRadius.circular(8),
          ),
          child: DropdownButtonHideUnderline(
            child: DropdownButton2<String>(
              isExpanded: true,
              value: _selectedDescription,
              hint: const Padding(
                padding: EdgeInsets.symmetric(horizontal: 12),
                child: Text(
                  "Select Complaint Description",
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey,
                  ),
                ),
              ),
              items: descriptions
                  .map((desc) => DropdownMenuItem<String>(
                value: desc.id,
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  child: Text(
                    desc.name ?? "",
                    style: TextStyle(fontSize: 14, color: AppColors.normalText,),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ))
                  .toList(),
              onChanged: (value) {
                setState(() {
                  _selectedDescription = value;
                  _descriptionError = null;
                });
              },
              buttonStyleData: ButtonStyleData(
                height: 48,
                width: double.infinity,
                padding: const EdgeInsets.symmetric(horizontal: 12),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: AppColors.fieldsGrey,
                ),
              ),
              dropdownStyleData: DropdownStyleData(
                maxHeight: 200,
                width: MediaQuery.of(context).size.width - 40, // Match field width
                padding: const EdgeInsets.symmetric(vertical: 8),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 8,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                elevation: 8,
                offset: const Offset(0, -8),
              ),
              menuItemStyleData: const MenuItemStyleData(
                height: 40,
                padding: EdgeInsets.symmetric(horizontal: 12),
              ),
              iconStyleData: const IconStyleData(
                icon: Icon(Icons.arrow_drop_down),
                iconSize: 24,
              ),
            ),
          ),
        ),
        if (_descriptionError != null) ...[
          const SizedBox(height: 4),
          Text(
            _descriptionError!,
            style: const TextStyle(
              color: Colors.red,
              fontSize: 12,
            ),
          ),
        ],

        const SizedBox(height: 16),

        const Text(
          "Note",
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w400,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 6),
        TextFormField(
          controller: _noteController,
          maxLines: 5,
          style: TextStyle(fontSize: 14, color: AppColors.normalText,),
          decoration: InputDecoration(
            hintText: "Write a note...",
            filled: true,
            fillColor: AppColors.fieldsGrey,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: BorderSide.none,
            ),
            errorText: _noteError,
            errorStyle: TextStyle( color: Colors.red,),
            hintStyle: TextStyle(fontSize: 14, color: Colors.grey,),
            contentPadding:
            const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
          ),
        ),

        const SizedBox(height: 30),

        SizedBox(
          width: double.infinity,
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.buttonColor,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(30),
              ),
              padding: const EdgeInsets.symmetric(vertical: 14),
            ),
            onPressed: () async {
              _validateAndSubmit(context);
            },
            child: const Text(
              "Raise Complaint",
              style: TextStyle(
                fontFamily: "PoppinsMedium",
                color: Colors.white,
                fontSize: 14,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Future<void> _validateAndSubmit(BuildContext context) async {
    setState(() {
      _categoryError = _selectedCategory == null ? "Please select a category" : null;
      _descriptionError = _selectedDescription == null ? "Please select a description" : null;
      _noteError = _noteController.text.trim().isEmpty ? "Please enter a note" : null;
    });

    if (_categoryError != null || _descriptionError != null || _noteError != null) {
      return;
    }

    try {
      final provider = Provider.of<HelpAndComplaintProvider>(context, listen: false);
      final res = await provider.addComplaint(
        accId: widget.accId,
        sessionId: widget.sessionId,
        genId: widget.genId,
        categoryId: _selectedCategory!,
        descriptionId: _selectedDescription!,
        note: _noteController.text.trim(),
        typeId: provider.dropDownsListResponse?.typeId ?? "2",
      );

      if (!mounted) return;

      // Fixed comparison to handle both String and int
      if (res != null && (res.error == "0" || res.error == 0)) {
        _showSuccessDialog(context);
      } else {
        CustomSnackBar.showError(
          context: context,
          message: res?.message ?? "Failed to raise complaint",
        );
      }
    } catch (e) {
      debugPrint("❌ Exception during complaint submission: $e");
      if (mounted) {
        CustomSnackBar.showError(
          context: context,
          message: "An error occurred while submitting complaint",
        );
      }
    }
  }

//   success_gif.gif
  void _showSuccessDialog(BuildContext context) {
    // Check if context is still valid and mounted
    if (!mounted) return;

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (ctx) => Dialog(
        backgroundColor: Colors.transparent,
        child: Container(
          width: MediaQuery.of(context).size.width * 0.8,
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: double.infinity,
                height: 140,
                color: Colors.white,
                child: Image.asset(
                  'assets/images/success_gif.gif',
                  height: 80,
                  width: 80,
                ),
              ),
              const Text(
                "Submitted",
                style: TextStyle(
                  fontSize: 18,
                  fontFamily: "Poppins",
                  fontWeight: FontWeight.w600,
                  color: Colors.black,
                ),
              ),
              const SizedBox(height: 16),
              Text(
                "Thanks for reaching out!",
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 12,
                  fontFamily: "Poppins",
                  fontWeight: FontWeight.w400,
                  color: AppColors.subtitleText,
                ),
              ),
              const Text(
                "Our team will reach out to you shortly.",
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 14,
                  fontFamily: "Poppins",
                  fontWeight: FontWeight.w400,
                  color: Colors.black87,
                ),
              ),
              const SizedBox(height: 24),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () {
                    Navigator.pop(ctx); // Close dialog
                    if (mounted) {
                      Navigator.pop(context, true); // Close form screen
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.buttonColor,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 12),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(28),
                    ),
                  ),
                  child: const Text(
                    "Close",
                    style: TextStyle(
                      fontFamily: "Poppins",
                      fontSize: 15,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}