import 'package:flutter/material.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/modules/cleaner_module/models/task_type.dart';
import 'package:test_sa/modules/cleaner_module/models/qr_scan_location_data.dart';
import 'package:test_sa/modules/cleaner_module/models/one_time_task_data.dart';
import 'package:test_sa/modules/cleaner_module/provider/cleaner_provider.dart';
import 'package:test_sa/modules/cleaner_module/provider/task_type_provider.dart';
import 'package:test_sa/modules/cleaner_module/pages/one_time_task_view.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/views/widgets/dialogs/confirm_dialog.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';
import 'package:test_sa/views/widgets/qr/scan_qr.dart';

class CleanerSearchFormView extends StatefulWidget {
  static const String routeName = '/cleaner_search';

  const CleanerSearchFormView({Key? key}) : super(key: key);

  @override
  State<CleanerSearchFormView> createState() => _CleanerSearchFormViewState();
}

class _CleanerSearchFormViewState extends State<CleanerSearchFormView> {
  TaskType? selectedTaskType;
  List<TaskType> _taskTypeOptions = [];
  bool _isLoadingTaskTypes = false;
  bool _isScanning = false;
  bool _isProceeding = false;
  QrScanLocationData? _scannedLocationData;

  @override
  void initState() {
    super.initState();
    _loadTaskTypes();
  }

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

  Future<void> _loadTaskTypes() async {
    setState(() {
      _isLoadingTaskTypes = true;
    });

    try {
      final taskTypes = await TaskTypeProvider().getTaskTypesList();
      setState(() {
        _taskTypeOptions = taskTypes;
        _isLoadingTaskTypes = false;
      });
    } catch (e) {
      setState(() {
        _isLoadingTaskTypes = false;
        _taskTypeOptions = [];
      });
      _showErrorDialog(context, 'Failed to load task types. Please try again.');
    }
  }

  Future<void> _onScanQRCode() async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const ScanQr()),
    );

    if (result != null && result is String && result.isNotEmpty) {
      setState(() {
        _isScanning = true;
      });

      try {
        final qrResult = await CleanerProvider().scanQRCode(qrCode: result);

        final isSuccess = qrResult["success"] ?? false;
        final backendMessage = qrResult["message"] ?? "Unknown error occurred";

        if (isSuccess && qrResult["data"] != null) {
          // Store the scanned location data
          setState(() {
            _scannedLocationData = QrScanLocationData.fromJson(qrResult["data"]);
            _isScanning = false;
          });
        } else {
          setState(() {
            _isScanning = false;
          });
          if (mounted) {
            _showErrorDialog(context, backendMessage);
          }
        }
      } catch (e) {
        setState(() {
          _isScanning = false;
        });
        if (mounted) {
          _showErrorDialog(context, 'Failed to scan QR code. Please try again.');
        }
      }
    }
  }

  Future<void> _onProceed() async {
    // Validate that task type and location data are available
    if (selectedTaskType == null) {
      _showErrorDialog(context, 'Please select a task type');
      return;
    }

    if (_scannedLocationData == null) {
      _showErrorDialog(context, 'Please scan a QR code first');
      return;
    }

    setState(() {
      _isProceeding = true;
    });

    try {
      final result = await CleanerProvider().proceedOneTimeTask(
        oneTimeSettingId: selectedTaskType!.id ?? 0,
        siteId: _scannedLocationData!.siteId ?? 0,
        buildingId: _scannedLocationData!.buildingId ?? 0,
        floorId: _scannedLocationData!.floorId ?? 0,
        departmentId: _scannedLocationData!.departmentId ?? 0,
        roomId: _scannedLocationData!.roomId ?? 0,
      );

      final isSuccess = result["success"] ?? false;
      final data = result["data"];
      final message = result["message"] ?? "Unknown error occurred";

      if (isSuccess && data != null) {
        // Get the task ID from the response
        final taskId = data['id'];

        if (mounted && taskId != null) {
          // Convert the data to OneTimeTaskData and navigate with the data
          final taskData = OneTimeTaskData.fromJson(data);

          // Navigate to OneTimeTaskView with the data
          Navigator.of(context).pushReplacement(
            MaterialPageRoute(
              builder: (context) => OneTimeTaskView(
                taskId: taskId,
                initialData: taskData,
              ),
            ),
          );
        }
      } else {
        if (mounted) {
          _showErrorDialog(context, message);
        }
      }
    } catch (e) {
      if (mounted) {
        _showErrorDialog(context, 'Failed to proceed. Please try again.');
      }
    } finally {
      setState(() {
        _isProceeding = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const DefaultAppBar(title: 'Search Request'),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                spacing: 12,
                children: [
                  // Task Type Dropdown
                  SingleItemDropDownMenu<TaskType, NullableLoadingProvider>(
                    context: context,
                    title: 'Task Type',
                    initialValue: selectedTaskType,
                    showShadow: false,
                    showAsBottomSheet: true,
                    backgroundColor: AppColor.fieldBgColor(context),
                    enabled: _taskTypeOptions.isNotEmpty,
                    loading: _isLoadingTaskTypes,
                    staticData: _taskTypeOptions,
                    onSelect: (value) {
                      setState(() {
                        selectedTaskType = value;
                      });
                    },
                  ),

                  // Scan QR Code Button
                  GestureDetector(
                    onTap: selectedTaskType != null ? _onScanQRCode : null,
                    child: Container(
                      height: 50,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: selectedTaskType != null ? AppColor.background(context) : Colors.grey[300],
                        borderRadius: BorderRadius.circular(16),
                        border: Border.all(
                          color: selectedTaskType != null ? AppColor.borderColor(context) : Colors.grey,
                          width: 1,
                        ),
                      ),
                      padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 8.toScreenHeight),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          "scan_asset".toSvgAsset(
                            height: 22,
                            fit: BoxFit.fitHeight,
                            color: selectedTaskType != null ? AppColor.icon2Color(context) : Colors.grey,
                          ),
                          8.width,
                          //we can change the implementation when merge with uiux branch
                          _scannedLocationData == null
                              ? "Scan QR Code".bodyText(context).custom(
                                    color: selectedTaskType != null ? AppColor.icon2Color(context) : Colors.grey,
                                  )
                              : 'Re Scan QR Code'.bodyText(context).custom(
                                    color: selectedTaskType != null ? AppColor.icon2Color(context) : Colors.grey,
                                  ),
                        ],
                      ),
                    ),
                  ),

                  // Loading Indicator
                  if (_isScanning)
                    const Center(
                      child: Padding(
                        padding: EdgeInsets.all(16.0),
                        child: CircularProgressIndicator(),
                      ),
                    ),

                  // Scanned Location Data Card
                  if (_scannedLocationData != null && !_isScanning) _buildLocationDataCard(context),
                ],
              ).toShadowContainer(context).paddingOnly(top: 20, start: 16, end: 16),
            ),
          ),

          // Footer Action Button
          FooterActionButton.footerContainer(
            context: context,
            child: AppFilledButton(
              buttonColor: _scannedLocationData != null && !_isProceeding ? AppColor.primary10 : Colors.grey,
              label: 'Proceed',
              maxWidth: true,
              onPressed: (_scannedLocationData != null && !_isProceeding) ? _onProceed : null,
              loading: _isProceeding,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLocationDataCard(BuildContext context) {
    final locationData = _scannedLocationData;

    if (locationData == null) {
      return const SizedBox();
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (locationData.siteName != null && locationData.siteName!.isNotEmpty)
              InfoTextWidget(
                label: 'Site', value: locationData.siteName,
                // style: AppTextStyles.bodyText.copyWith(
                //   color: context.isDark ? AppColor.neutral10 : AppColor.neutral120,
                // ),
              ),
            if (locationData.buildingName != null && locationData.buildingName!.isNotEmpty)
              InfoTextWidget(
                label: 'Building',
                value: locationData.buildingName,
              ),
            if (locationData.floorName != null && locationData.floorName!.isNotEmpty)
              InfoTextWidget(
                label: 'Floor',
                value: locationData.floorName,
              ),
            if (locationData.departmentName != null && locationData.departmentName!.isNotEmpty)
              InfoTextWidget(
                label: 'Department',
                value: locationData.departmentName,
              ),
            if (locationData.roomName != null && locationData.roomName!.isNotEmpty)
              InfoTextWidget(
                label: 'Room',
                value: locationData.roomName,
              ),
            if (locationData.locationDescription != null && locationData.locationDescription!.isNotEmpty)
              InfoTextWidget(
                label: 'Location Description',
                value: locationData.locationDescription,
              ),
            // Text(
            //   'Location Description: ${locationData.locationDescription}',
            //   style: AppTextStyles.bodyText.copyWith(
            //     color: context.isDark ? AppColor.neutral10 : AppColor.neutral120,
            //   ),
            //   softWrap: true,
            //   maxLines: null,
            // ),
          ],
        ).paddingOnly(start: 16, end: 16, top: 16, bottom: 16),
      ],
    ).toShadowContainer(context, padding: 0);
  }

  void _showErrorDialog(BuildContext context, String message) {
    showDialog(
      context: context,
      builder: (context) => ConfirmDialog(
        message: message,
        title: 'Error',
        onTap: () => Navigator.pop(context),
      ),
    );
  }
}
