import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:open_file/open_file.dart';
import 'package:provider/provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/export_module/models/asset_column_metadata.dart';
import 'package:test_sa/modules/export_module/models/export_form_model.dart';
import 'package:test_sa/modules/export_module/models/export_module_type.dart';
import 'package:test_sa/modules/export_module/provider/export_provider.dart';
import 'package:test_sa/modules/export_module/provider/export_columns_provider.dart';
import 'package:test_sa/modules/export_module/provider/export_format_provider.dart';
import 'package:test_sa/modules/export_module/widgets/file_success_dialog.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/new_views/common_widgets/multiple_item_drop_down_menu.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'dart:developer';

import 'package:test_sa/views/widgets/item_views/info_header_widget.dart';

class ExportFormView<T> extends StatefulWidget {
  final T searchModel;
  final ExportModuleType moduleType;
  final int pageNo;
  final int pageSize;

  const ExportFormView({
    Key? key,
    required this.searchModel,
    required this.moduleType,
    required this.pageNo,
    required this.pageSize,
  }) : super(key: key);

  @override
  State<ExportFormView<T>> createState() => _ExportFormViewState<T>();
}

class _ExportFormViewState<T> extends State<ExportFormView<T>> {
  List<AssetColumnMetadata> selectedColumns = [];
  Lookup? selectedFormat;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Provider.of<AssetColumnsProvider>(context, listen: false).reset();
  }

  void _updateSelectedColumns(List<AssetColumnMetadata>? value) {
    if (value != null && mounted) {
      setState(() {
        selectedColumns = value;
      });
    }
  }

  void _updateSelectedFormat(Lookup? value) {
    if (value != null && mounted) {
      setState(() {
        selectedFormat = value;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const DefaultAppBar(title: 'Export'),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                spacing: 12,
                children: [
                  MultipleItemDropDownMenu<AssetColumnMetadata, AssetColumnsProvider>(
                    context: context,
                    title: 'Columns',
                    showAsBottomSheet: true,
                    backgroundColor: AppColor.fieldBgColor(context),
                    showShadow: false,
                    height: 56.toScreenHeight,
                    showCancel: true,
                    initialValue: selectedColumns,
                    requestById: widget.moduleType.id,
                    onSelect: _updateSelectedColumns,
                  ),
                  SingleItemDropDownMenu<Lookup, ExportFormatProvider>(
                    context: context,
                    title: 'Format',
                    backgroundColor: AppColor.fieldBgColor(context),
                    height: 56.toScreenHeight,
                    showShadow: false,
                    showAsBottomSheet: false,
                    showAsFullScreenDialog: true,
                    requestById: 1,
                    initialValue: selectedFormat,
                    onSelect: _updateSelectedFormat,
                  ),
                ],
              ).toShadowContainer(context).paddingOnly(top: 20, start: 16, end: 16),
            ),
          ),
          18.height,
          FooterActionButton.footerContainer(
            context: context,
            child: AppFilledButton(
                label: 'Export',
                buttonColor: AppColor.primary10,
                onPressed: () async {
                  if (selectedFormat == null) {
                    'Please select an export format.'.showToast;
                    return;
                  }
                  if (selectedColumns.isEmpty) {
                    'Please select at least one column to export.'.showToast;
                    return;
                  }

                  final exportRequest = ExportRequest<T>(
                    selectedColumns: selectedColumns.map((col) => col.propertyName ?? '').toList(),
                    format: selectedFormat?.name ?? '',
                    searchModel: widget.searchModel,
                    pageNo: widget.pageNo,
                    pageSize: widget.pageSize,
                  );

                  log('📦 ExportRequest created');

                  try {
                    final exportProvider = Provider.of<ExportApiProvider>(context, listen: false);
                    if (!mounted) return;

                    final filePath = await exportProvider.exportData(exportRequest, widget.moduleType, context);
                    if (!mounted) return;

                    if (filePath != null && filePath.isEmpty) {
                      // do nothing, as toast handled in method
                    } else if (filePath != null && filePath.isNotEmpty) {
                      await FileSuccessDialog.show(
                        context: context,
                        filePath: filePath,
                        title: 'Export Successful',
                        message: 'Your file has been exported successfully',
                        logPrefix: 'exported',
                      );
                    } else if (exportProvider.errorMessage != null) {
                      String errorMessage = exportProvider.errorMessage!;
                      if (errorMessage.contains('No app installed') || errorMessage.contains('No app found')) {
                        String fileType = selectedFormat?.name ?? 'this file type';
                        errorMessage = 'No app found to open $fileType files. Please install a compatible app';
                      }
                      errorMessage.showToast;
                    } else {
                      'Export failed. Please try again.'.showToast;
                    }
                  } catch (e, stackTrace) {
                    log('❌ Error in export button: $e');
                    log('Stack trace: $stackTrace');
                    if (mounted) {
                      'Error occurred during export: $e'.showToast;
                    }
                  }
                }),
          ),
        ],
      ),
    );
  }

  //check if we need we can show this as well @waseem

  String _getAppSuggestion(String format) {
    final formatLower = format.toLowerCase();
    switch (formatLower) {
      case 'excel':
        return 'Microsoft Excel, Google Sheets, or WPS Office';
      case 'pdf':
        return 'Adobe Acrobat Reader or any PDF viewer';
      case 'word':
      case 'doc':
        return 'Microsoft Word, Google Docs, or WPS Office';
      case 'text':
      case 'txt':
        return 'any text editor';
      case 'csv':
        return 'Microsoft Excel, Google Sheets, or any spreadsheet app';
      default:
        return 'a compatible viewer app';
    }
  }
}
