import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:nearle/controllers/support_ticket.dart';
import 'package:nearle/views/helpers/constants/Colorconstants.dart';
import 'package:nearle/views/helpers/constants/Font_constant.dart';

class SupportTicket extends StatefulWidget {
  const SupportTicket({super.key});

  @override
  State<SupportTicket> createState() => _SupportTicketState();
}

class _SupportTicketState extends State<SupportTicket>
    with SingleTickerProviderStateMixin {
  late final TabController _tabController;

  // Form
  final _formKey = GlobalKey<FormState>();
  final _subjectCtrl = TextEditingController();
  final _messageCtrl = TextEditingController();
  String _category = 'Account';
  String _priority = 'Medium';
  int _attachmentCount = 0;

  // Image
  final ImagePicker _picker = ImagePicker();
  final List<XFile> _attachments = [];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() => setState(() {}));
    Get.put(SupportTicketController());
  }

  @override
  void dispose() {
    _subjectCtrl.dispose();
    _messageCtrl.dispose();
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: ColorConstants.primaryColor,
          centerTitle: true,
          toolbarHeight: 70,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
            onPressed: () => Navigator.pop(context),
          ),
          title: Text(
            'Support Ticket',
            style: TextStyle(
              fontSize: 26,
              color: Colors.white,
              fontWeight: FontWeight.bold,
              letterSpacing: 1.2,
              fontFamily: FontConstants.fontFamily,
            ),
          ),
          elevation: 4,
        ),
        body: Column(
          children: [
            Container(
              color: Colors.white,
              child: TabBar(
                controller: _tabController,
                indicatorColor: ColorConstants.primaryColor,
                labelColor: ColorConstants.primaryColor,
                unselectedLabelColor: Colors.grey,
                labelStyle: TextStyle(
                  fontFamily: FontConstants.fontFamily,
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
                tabs: [
                  Tab(
                    child: Text(
                      'Create Tickets',
                      style: TextStyle(fontFamily: FontConstants.fontFamily, fontSize: 20),
                    ),
                  ),
                  Tab(
                    child: Text(
                      'My Tickets',
                      style: TextStyle(fontFamily: FontConstants.fontFamily, fontSize: 20),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: TabBarView(
                controller: _tabController,
                children: [_buildCreateForm(), _buildTicketsList()],
              ),
            ),
          ],
        ),
        bottomNavigationBar: _tabController.index == 0
            ? Padding(
                padding: const EdgeInsets.all(16),
                child: SizedBox(
                  height: 55,
                  width: double.infinity,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: ColorConstants.primaryColor,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(vertical: 14),
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                    ),
                    onPressed: _submitTicket,
                    child: Text(
                      'Submit Ticket',
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        fontFamily: FontConstants.fontFamily,
                      ),
                    ),
                  ),
                ),
              )
            : null,
      ),
    );
  }

  // ===============================================
  // CREATE FORM
  // ===============================================
  Widget _buildCreateForm() {
    final controller = Get.find<SupportTicketController>();

    return SingleChildScrollView(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
      child: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Create a new support ticket',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, fontFamily: FontConstants.fontFamily),
            ),
            const SizedBox(height: 8),
            Text(
              'Tell us what went wrong. We\'ll get back to you as soon as possible.',
              style: TextStyle(fontSize: 18, color: Colors.grey.shade700, height: 1.4, fontFamily: FontConstants.fontFamily),
            ),
            const SizedBox(height: 20),

            // Category
            Text('Category', style: _labelStyle()),
            const SizedBox(height: 8),
            DropdownButtonFormField<String>(
              // ignore: deprecated_member_use
              value: _category,
              items: ['Account', 'Orders', 'Payments', 'App issue', 'Other']
                  .map((e) => DropdownMenuItem(value: e, child: Text(e, style: TextStyle(fontFamily: FontConstants.fontFamily))))
                  .toList(),
              onChanged: (v) => setState(() => _category = v ?? _category),
              decoration: _inputDecoration(),
            ),

            const SizedBox(height: 16),

            // Priority
            Text('Priority', style: _labelStyle()),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              children: ['Low', 'Medium', 'High'].map((p) {
                final selected = _priority == p;
                return ChoiceChip(
                  label: Text(p, style: TextStyle(fontFamily: FontConstants.fontFamily, fontWeight: FontWeight.w600, fontSize: 16)),
                  selected: selected,
                  selectedColor: ColorConstants.primaryColor.withOpacity(0.15),
                  labelStyle: TextStyle(
                    color: selected ? ColorConstants.primaryColor : Colors.black87,
                    fontWeight: FontWeight.w600,
                    fontFamily: FontConstants.fontFamily,
                  ),
                  onSelected: (_) => setState(() => _priority = p),
                );
              }).toList(),
            ),

            const SizedBox(height: 16),

            // Subject
            Text('Subject', style: _labelStyle()),
            const SizedBox(height: 8),
            TextFormField(
              controller: _subjectCtrl,
              decoration: _inputDecoration(hint: 'Type Something'),
              style: TextStyle(fontFamily: FontConstants.fontFamily),
              validator: (v) => (v == null || v.trim().isEmpty) ? 'Please enter a subject' : null,
            ),

            const SizedBox(height: 16),

            // Message
            Text('Describe the issue', style: _labelStyle()),
            const SizedBox(height: 8),
            TextFormField(
              controller: _messageCtrl,
              minLines: 5,
              maxLines: 8,
              decoration: _inputDecoration(hint: 'Type Something'),
              style: TextStyle(fontFamily: FontConstants.fontFamily),
              validator: (v) => (v == null || v.trim().isEmpty) ? 'Please enter your message' : null,
            ),

            const SizedBox(height: 16),

            // Attachments
            Row(
              children: [
                OutlinedButton.icon(
                  onPressed: _addAttachment,
                  icon: const Icon(Icons.attach_file),
                  label: Text('Add screenshot', style: TextStyle(fontFamily: FontConstants.fontFamily)),
                ),
                const SizedBox(width: 12),
                if (_attachmentCount > 0)
                  Text('$_attachmentCount attached', style: TextStyle(fontWeight: FontWeight.w600, fontFamily: FontConstants.fontFamily)),
              ],
            ),
            const SizedBox(height: 8),
            if (_attachments.isNotEmpty)
              Wrap(
                spacing: 8,
                runSpacing: 8,
                children: _attachments.asMap().entries.map((entry) {
                  final idx = entry.key;
                  final file = entry.value;
                  return Stack(
                    clipBehavior: Clip.none,
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: Image.file(File(file.path), width: 80, height: 80, fit: BoxFit.cover),
                      ),
                      Positioned(
                        top: -8,
                        right: -8,
                        child: InkWell(
                          onTap: () => setState(() {
                            _attachments.removeAt(idx);
                            _attachmentCount = _attachments.length;
                          }),
                          child: Container(
                            width: 22,
                            height: 22,
                            decoration: BoxDecoration(color: Colors.black.withOpacity(0.6), shape: BoxShape.circle),
                            child: const Icon(Icons.close, size: 16, color: Colors.white),
                          ),
                        ),
                      ),
                    ],
                  );
                }).toList(),
              ),

            // Submit loading
            Obx(() => controller.isSubmitting.value
                ? const Padding(
                    padding: EdgeInsets.symmetric(vertical: 16),
                    child: Center(child: CircularProgressIndicator()),
                  )
                : const SizedBox.shrink()),
          ],
        ),
      ),
    );
  }

  // ===============================================
  // MY TICKETS LIST
  // ===============================================
  Widget _buildTicketsList() {
    final controller = Get.find<SupportTicketController>();

    return Obx(() {
      if (controller.isLoading.value) {
        return const Center(child: CircularProgressIndicator());
      }

      if (controller.errorMessage.value.isNotEmpty) {
        return Center(
          child: Padding(
            padding: const EdgeInsets.all(24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Icon(Icons.error_outline, size: 48, color: Colors.red),
                const SizedBox(height: 12),
                Text('Failed to load tickets', style: TextStyle(fontFamily: FontConstants.fontFamily, fontWeight: FontWeight.w600)),
                const SizedBox(height: 8),
                Text(controller.errorMessage.value, textAlign: TextAlign.center, style: TextStyle(color: Colors.grey.shade600, fontFamily: FontConstants.fontFamily)),
                const SizedBox(height: 16),
                ElevatedButton(onPressed: controller.fetchTickets, child: const Text('Retry')),
              ],
            ),
          ),
        );
      }

      if (controller.tickets.isEmpty) {
        return _buildEmptyState();
      }

      return ListView.separated(
        padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
        itemCount: controller.tickets.length,
        separatorBuilder: (_, __) => const SizedBox(height: 10),
        itemBuilder: (context, i) {
          final t = controller.tickets[i];
          final statusColor = _getPriorityColor(t.priority);

          return Card(
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
            elevation: 2,
            child: ListTile(
              contentPadding: const EdgeInsets.all(12),
              title: Text(t.subject, style: TextStyle(fontWeight: FontWeight.w700, fontFamily: FontConstants.fontFamily)),
              subtitle: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(height: 4),
                  Text('Category: ${t.category} • Priority: ${t.priority}', style: TextStyle(fontFamily: FontConstants.fontFamily)),
                  const SizedBox(height: 4),
                  Text('Created: ${_formatDate(t.created)}', style: TextStyle(fontFamily: FontConstants.fontFamily)),
                ],
              ),
              trailing: Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                decoration: BoxDecoration(color: statusColor.withOpacity(0.15), borderRadius: BorderRadius.circular(20)),
                child: Text(t.priority, style: TextStyle(color: statusColor, fontWeight: FontWeight.bold, fontFamily: FontConstants.fontFamily)),
              ),
            ),
          );
        },
      );
    });
  }

  Widget _buildEmptyState() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.support_agent, size: 48, color: Colors.grey),
            const SizedBox(height: 12),
            Text('No tickets yet', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, fontFamily: FontConstants.fontFamily)),
            const SizedBox(height: 8),
            Text('Create your first ticket from the Create tab.', style: TextStyle(color: Colors.grey.shade700, fontFamily: FontConstants.fontFamily)),
          ],
        ),
      ),
    );
  }

  // ===============================================
  // HELPERS
  // ===============================================
  TextStyle _labelStyle() => TextStyle(fontSize: 20, fontWeight: FontWeight.bold, fontFamily: FontConstants.fontFamily);

  InputDecoration _inputDecoration({String? hint}) {
    return InputDecoration(
      hintText: hint,
      filled: true,
      fillColor: Colors.white,
      contentPadding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12),
      border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide(color: Colors.grey.shade300)),
      enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide(color: Colors.grey.shade300)),
      focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide(color: ColorConstants.primaryColor, width: 1.5)),
      hintStyle: TextStyle(fontFamily: FontConstants.fontFamily),
    );
  }

  Color _getPriorityColor(String priority) {
    return switch (priority.toLowerCase()) {
      'high' => Colors.red,
      'medium' => Colors.orange,
      'low' => Colors.green,
      _ => Colors.grey,
    };
  }

  String _formatDate(DateTime date) {
    return '${date.day}/${date.month}/${date.year} ${date.hour}:${date.minute.toString().padLeft(2, '0')}';
  }

  // ===============================================
  // IMAGE PICKER
  // ===============================================
  Future<void> _addAttachment() async {
    final source = await showModalBottomSheet<ImageSource>(
      context: context,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))),
      builder: (ctx) => SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.photo_library),
              title: Text('Gallery', style: TextStyle(fontFamily: FontConstants.fontFamily)),
              onTap: () => Navigator.pop(ctx, ImageSource.gallery),
            ),
            ListTile(
              leading: const Icon(Icons.camera_alt),
              title: Text('Camera', style: TextStyle(fontFamily: FontConstants.fontFamily)),
              onTap: () => Navigator.pop(ctx, ImageSource.camera),
            ),
          ],
        ),
      ),
    );

    if (source == null) return;

    try {
      if (source == ImageSource.gallery) {
        final multi = await _picker.pickMultiImage(imageQuality: 85);
        if (multi.isNotEmpty) {
          setState(() => _attachments.addAll(multi));
        } else {
          final one = await _picker.pickImage(source: ImageSource.gallery, imageQuality: 85);
          if (one != null) setState(() => _attachments.add(one));
        }
      } else {
        final captured = await _picker.pickImage(source: ImageSource.camera, imageQuality: 85);
        if (captured != null) setState(() => _attachments.add(captured));
      }
    } catch (_) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to pick image', style: TextStyle(fontFamily: FontConstants.fontFamily))),
      );
    }

    setState(() => _attachmentCount = _attachments.length);
  }

  // ===============================================
  // SUBMIT TICKET
  // ===============================================
  Future<void> _submitTicket() async {
    if (!(_formKey.currentState?.validate() ?? false)) return;

    final controller = Get.find<SupportTicketController>();
    final success = await controller.createTicket(
      userid: 1242,
      category: _category,
      priority: _priority,
      subject: _subjectCtrl.text.trim(),
      issue: _messageCtrl.text.trim(),
      attachments: _attachments.isEmpty ? null : _attachments,
    );

    if (success) {
      _subjectCtrl.clear();
      _messageCtrl.clear();
      _attachments.clear();
      _attachmentCount = 0;
      setState(() {});

      _tabController.animateTo(1);

      showDialog(
        context: context,
        builder: (_) => AlertDialog(
          title: const Text('Ticket Submitted!'),
          content: const Text('Your ticket has been created and saved. Our team will get back to you soon.'),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK')),
          ],
        ),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Failed to submit ticket: ${controller.errorMessage.value}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
    }