import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:hello_doctor_admin_dashboard/app/models/help_model.dart';
import 'package:hello_doctor_admin_dashboard/app/models/help_table_source.dart';
import 'package:hello_doctor_admin_dashboard/app/services/help_service.dart';
import 'package:hello_doctor_admin_dashboard/app/utils/timeformat.dart';
import 'package:url_launcher/url_launcher.dart' as launcher;

class HelpCenterController extends GetxController
    with StateMixin<List<HelpModel>> {
  List<HelpModel>? listHelp;
  late HelpDataSource helpData;

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

  Future<void> initHelpCenterTab() async {
    try {
      if (listHelp == null) {
        listHelp = await HelpService().getAllHelpRequests();
        helpData = HelpDataSource(listHelp!);
        change(listHelp, status: RxStatus.success());
      }
    } catch (e) {
      Fluttertoast.showToast(msg: e.toString(), toastLength: Toast.LENGTH_LONG);
    }
  }

  void showDetailsDialog(HelpModel help) {
    Get.defaultDialog(
      title: 'Help Request Details',
      content: Container(
        width: 500,
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            _detailRow('Name', help.name),
            _detailRow('Email', help.email),
            _detailRow('Problem', help.problem),
            if (help.attachmentUrl != null)
              _detailRow(
                  'Attachment',
                  TextButton(
                    onPressed: () => launchUrl(help.attachmentUrl!),
                    child: Text('View Attachment'),
                  )),
            _detailRow('Created At', TimeFormat().formatDate(help.createdAt)),
            _detailRow(
                'Status',
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: _getStatusColor(help.status),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    help.status,
                    style: TextStyle(color: Colors.white),
                  ),
                )),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Get.back(),
          child: Text('Close'),
        ),
      ],
    );
  }

  void showEditStatusDialog(HelpModel help) {
    String selectedStatus = help.status;
    final List<String> statusOptions = ['pending', 'in_progress', 'resolved'];

    Get.defaultDialog(
      title: 'Update Status',
      content: Container(
        width: 300,
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Current Status: ${help.status}'),
            SizedBox(height: 16),
            DropdownButtonFormField<String>(
              value: selectedStatus,
              items: statusOptions.map((String status) {
                return DropdownMenuItem<String>(
                  value: status,
                  child: Text(status.replaceAll('_', ' ').capitalize ?? status),
                );
              }).toList(),
              onChanged: (String? newValue) {
                if (newValue != null) {
                  selectedStatus = newValue;
                }
              },
              decoration: InputDecoration(
                labelText: 'New Status',
                border: OutlineInputBorder(),
              ),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Get.back(),
          child: Text('Cancel'),
        ),
        ElevatedButton(
          onPressed: () async {
            await updateStatus(help.id, selectedStatus);
            Get.back();
          },
          child: Text('Update'),
        ),
      ],
    );
  }

  Future<void> updateStatus(String helpId, String newStatus) async {
    try {
      // Update in server
      await HelpService().updateHelpStatus(helpId, newStatus);

      // Update locally
      if (listHelp != null) {
        final index = listHelp!.indexWhere((help) => help.id == helpId);
        if (index != -1) {
          // Create new help model with updated status
          final updatedHelp = listHelp![index].copyWith(status: newStatus);
          listHelp![index] = updatedHelp;

          // Update data source
          helpData = HelpDataSource(listHelp!);
          // Trigger UI refresh
          change(listHelp, status: RxStatus.success());
        }
      }

      Fluttertoast.showToast(msg: 'Status updated successfully');
    } catch (e) {
      Fluttertoast.showToast(msg: 'Failed to update status: ${e.toString()}');
    }
  }

  Widget _detailRow(String label, dynamic value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: Text(
              '$label:',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
          Expanded(
            child: value is Widget ? value : Text(value.toString()),
          ),
        ],
      ),
    );
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'pending':
        return Colors.orange;
      case 'in_progress':
        return Colors.blue;
      case 'resolved':
        return Colors.green;
      default:
        return Colors.grey;
    }
  }

  Future<void> launchUrl(String url) async {
    try {
      final Uri uri = Uri.parse(url);
      if (await launcher.canLaunchUrl(uri)) {
        await launcher.launchUrl(uri,
            mode: launcher.LaunchMode.externalApplication);
      } else {
        Fluttertoast.showToast(msg: 'Could not open attachment URL');
      }
    } catch (e) {
      Fluttertoast.showToast(msg: 'Error opening attachment: ${e.toString()}');
    }
  }
}
