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';

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

  @override
  Widget build(BuildContext context) {
    final isEditable = widget.reason == null;
    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
              const SectionHeading(title: 'Create New Ticket'),
              const SizedBox(height: 12),

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

              /// Reason Dropdown
              Container(
                width: double.infinity,
                padding:
                const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                decoration: BoxDecoration(
                  color: Color(0xffE0E0E0),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: isEditable
                    ? DropdownButtonFormField<String>(
                  value: _selectedReason,
                  items: [
                    'Payment Issue',
                    'Bill Related Issues',
                    'Other Issues',
                  ].map((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(
                        value,
                        style: const TextStyle(
                          fontSize: 14,
                          fontFamily: "Plus Jakarta Sans",
                          fontWeight: FontWeight.w500,
                          color: Colors.black87,
                        ),
                      ),
                    );
                  }).toList(),
                  onChanged: (newValue) {
                    setState(() {
                      _selectedReason = newValue!;
                    });
                  },
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.zero,
                  ),
                )
                    : Text(
                  _selectedReason,
                  style: const TextStyle(
                    fontSize: 14,
                    fontFamily: "Plus Jakarta Sans",
                    fontWeight: FontWeight.w500,
                    color: Colors.black87,
                  ),
                ),
              ),
              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: 12,
        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();
  }
}
