import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../../Utility/AppColors.dart';
import '../../Utility/Reusablewidgets.dart';

class HelpTicketScreen extends StatefulWidget {
  final String? reason;
  const HelpTicketScreen({super.key, this.reason});

  @override
  State<HelpTicketScreen> createState() => _HelpTicketScreenState();
}

class _HelpTicketScreenState extends State<HelpTicketScreen> {
  final TextEditingController _issueController = TextEditingController();
  final TextEditingController _otherReasonController = TextEditingController();
  List<String> _selectedImages = [];
  String _selectedReason = 'Payment Issue';

  // Dummy data for help - with proper null safety
  final List<Map<String, dynamic>> createNewTickets = [
    {
      'title': 'Payment Issues',
      'description': 'Get help with payment related problems',
      'icon': "assets/svg/rupee_coin_ic.svg",
      'color': Color(0xFFFFEFBE),
    },
    {
      'title': 'Bill Related Issues',
      'description': 'Resolve bill and invoice matters',
      'icon': "assets/svg/know_pay.svg",
      'color': Color(0xFFCEF9FF),
    },
    {
      'title': 'Other Issues',
      'description': 'Any other support you need',
      'icon': 'assets/svg/help_ic.svg',
      'color': Color(0xFFE4E5FF),
    },
  ];

  @override
  void initState() {
    super.initState();
    if (widget.reason != null) {
      _selectedReason = widget.reason!;
    }
  }

  @override
  Widget build(BuildContext context) {
    final showOtherReasonField = _selectedReason == 'Other Issues';

    return SafeArea(
      top: false,
      child: Scaffold(
        backgroundColor: AppColors.backgroundRegular,
        appBar: AppBar(
          automaticallyImplyLeading: false,
          backgroundColor: Colors.white,
          elevation: 0,
          title: Row(
            children: [
              InkResponse(
                onTap: () => Navigator.pop(context, true),
                child: SvgPicture.asset(
                  "assets/svg/continue_left_ic.svg",
                  height: 25,
                ),
              ),
              const SizedBox(width: 10),
              const Text(
                "Help?",
                style: TextStyle(
                  fontSize: 16,
                  fontFamily: "Plus Jakarta Sans",
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
        ),
        body: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              /// Section Title
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SectionHeading(title: 'Create New Ticket'),
                  Container(
                    padding:
                    const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
                    decoration: BoxDecoration(
                      color: Colors.blue.shade50,
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Text(
                      "order #1235",
                      style: TextStyle(
                        fontSize: 14,
                        fontFamily: "Plus Jakarta Sans",
                        fontWeight: FontWeight.w500,
                        color: Colors.black87,
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),

              /// Reason Label
              _fieldLabel("Reason"),
              const SizedBox(height: 6),

              /// Reason Selection Button - Opens Bottom Sheet
              GestureDetector(
                onTap: _showReasonBottomSheet,
                child: Container(
                  width: 200,
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  decoration: BoxDecoration(
                    color: Color(0xffFFF3D1),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        _selectedReason,
                        style: const TextStyle(
                          fontSize: 14,
                          fontFamily: "Plus Jakarta Sans",
                          fontWeight: FontWeight.w500,
                          color: Colors.black87,
                        ),
                      ),
                      SvgPicture.asset(
                        "assets/svg/edit_ic.svg",
                        height: 25,
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 16),

              /// Other Reason Field
              if (showOtherReasonField) ...[
                _fieldLabel("Enter Reason"),
                const SizedBox(height: 6),
                _textField(
                  controller: _otherReasonController,
                  hint: "Write your reason",
                ),
                const SizedBox(height: 16),
              ],

              /// Issue Description
              _fieldLabel("Tell us your issue?"),
              const SizedBox(height: 6),
              _textField(
                controller: _issueController,
                hint: "Write your issue",
                maxLines: 5,
              ),
              const SizedBox(height: 16),

              /// Attachments
              _fieldLabel("Add Screenshot (optional)"),
              const SizedBox(height: 6),
              Container(
                width: double.infinity,
                padding:
                const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Add Image Button
                    Container(
                      width: 60,
                      height: 60,
                      decoration: BoxDecoration(
                        color: Colors.grey.shade100,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: IconButton(
                        onPressed: _addImage,
                        icon: Icon(
                          Icons.add,
                          size: 24,
                          color: Colors.grey[600],
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),

                    // Selected Images Grid
                    if (_selectedImages.isNotEmpty)
                      GridView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 4,
                          crossAxisSpacing: 8,
                          mainAxisSpacing: 8,
                        ),
                        itemCount: _selectedImages.length,
                        itemBuilder: (context, index) {
                          return Stack(
                            children: [
                              ClipRRect(
                                borderRadius: BorderRadius.circular(8),
                                child: Image.network(
                                  _selectedImages[index],
                                  fit: BoxFit.cover,
                                  width: double.infinity,
                                  height: double.infinity,
                                ),
                              ),
                              Positioned(
                                top: 4,
                                right: 4,
                                child: GestureDetector(
                                  onTap: () => _removeImage(index),
                                  child: Container(
                                    padding: const EdgeInsets.all(2),
                                    decoration: const BoxDecoration(
                                      color: Colors.black54,
                                      shape: BoxShape.circle,
                                    ),
                                    child: const Icon(
                                      Icons.close,
                                      size: 14,
                                      color: Colors.white,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          );
                        },
                      ),
                  ],
                ),
              ),
              const SizedBox(height: 24),

              /// Submit Button
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _submitTicket,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.buttonColor,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(28),
                    ),
                    elevation: 0,
                  ),
                  child: const Text(
                    'Submit',
                    style: TextStyle(
                      fontSize: 16,
                      fontFamily: "Plus Jakarta Sans",
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// Custom label widget (no shadow, minimal)
  Widget _fieldLabel(String text) {
    return Text(
      text,
      style: TextStyle(
        fontSize: 14,
        fontFamily: "Plus Jakarta Sans",
        fontWeight: FontWeight.w500,
        color: Colors.grey[700],
      ),
    );
  }

  /// Clean text field (no border or shadow)
  Widget _textField({
    required TextEditingController controller,
    required String hint,
    int maxLines = 1,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: TextFormField(
        controller: controller,
        maxLines: maxLines,
        style: const TextStyle(
          fontSize: 14,
          fontFamily: "Plus Jakarta Sans",
          fontWeight: FontWeight.w400,
          color: Colors.black87,
        ),
        decoration: InputDecoration(
          hintText: hint,
          hintStyle: TextStyle(
            fontSize: 14,
            fontFamily: "Plus Jakarta Sans",
            fontWeight: FontWeight.w400,
            color: Colors.grey[400],
          ),
          border: InputBorder.none,
          contentPadding:
          const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        ),
      ),
    );
  }

  /// Add image (demo)
  void _addImage() {
    setState(() {
      _selectedImages.add('https://via.placeholder.com/100');
    });
  }

  void _removeImage(int index) {
    setState(() {
      _selectedImages.removeAt(index);
    });
  }

  void _submitTicket() {
    final issue = _issueController.text.trim();
    final otherReason = _otherReasonController.text.trim();

    if (issue.isEmpty) return;
    if (_selectedReason == 'Other Issues' && otherReason.isEmpty) return;

    print('Submitting ticket with reason: $_selectedReason');
    print('Issue: $issue');
  }

  @override
  void dispose() {
    _issueController.dispose();
    _otherReasonController.dispose();
    super.dispose();
  }

  void _showReasonBottomSheet() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      builder: (context) {
        return Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                "Select Your Reason",
                style: TextStyle(
                  fontSize: 18,
                  fontFamily: "Plus Jakarta Sans",
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
              const SizedBox(height: 16),

              GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 12,
                  mainAxisSpacing: 12,
                  childAspectRatio: 0.99,
                ),
                itemCount: createNewTickets.length,
                itemBuilder: (context, index) {
                  final ticket = createNewTickets[index];
                  final String title = ticket['title'] ?? 'Unknown';
                  final String icon = ticket['icon'] ?? 'assets/svg/help_ic.svg';
                  final Color color = ticket['color'] ?? Colors.grey;

                  return _buildReasonCard(
                    title: title,
                    icon: icon,
                    color: color,
                  );
                },
              ),
              const SizedBox(height: 24),
            ],
          ),
        );
      },
    );
  }

  Widget _buildReasonCard({
    required String title,
    required String icon,
    required Color color,
  }) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedReason = title;
        });
        Navigator.pop(context); // Close the bottom sheet
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 2, vertical: 1),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // Icon container
            Container(
              width: 88,
              height: 88,
              decoration: BoxDecoration(
                color: color.withOpacity(0.12), // Fixed opacity
                borderRadius: BorderRadius.circular(12),
              ),
              child: Center(
                child: SizedBox(
                  height: 40,
                  width: 40,
                  child: SvgPicture.asset(
                    icon,
                    fit: BoxFit.fitWidth,
                  ),
                ),
              ),
            ),
            const SizedBox(height: 8),
            // Title
            SizedBox(
              child: Text(
                title,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: AppColors.nearDarkText,
                  fontSize: 14,
                  fontWeight: FontWeight.w400,
                  fontFamily: "Plus Jakarta Sans",
                ),
              ),
            ),
            const SizedBox(height: 4),
          ],
        ),
      ),
    );
  }
}