import 'dart:io';
import 'package:excel/excel.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hoshan/core/services/permission/permission_service.dart';
import 'package:hoshan/core/utils/date_time.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class ExcelServices {
  static const MethodChannel _channel = MethodChannel('file_channel');

  static Future<void> copyToDownloads(String filePath, String fileName) async {
    await PermissionService.getPermission(
        permission: Permission.manageExternalStorage);

    try {
      final String result = await _channel.invokeMethod('copyToDownloads', {
        'filePath': filePath,
        'fileName': fileName,
      });
      if (kDebugMode) {
        print("File copied successfully: $result");
      }
    } catch (e) {
      if (kDebugMode) {
        print("Error copying file: $e");
      }
      rethrow;
    }
  }

  static Future<String?> saveDataTableToExcel(
      List<DataColumn> columns, List<DataRow> rows) async {
    try {
      // Create an Excel workbook
      var excel = Excel.createExcel();

      // Create a sheet
      Sheet sheet = excel['Sheet1'];

      // Add column headers
      List<CellValue> headers = columns.map((col) {
        final label = col.label as Text;
        return TextCellValue(label.data ?? '');
      }).toList();
      sheet.appendRow(headers);

      // Add row data
      for (var row in rows) {
        List<CellValue> rowData = row.cells.map((cell) {
          final text = cell.child as Text;
          return TextCellValue(text.data ?? '');
        }).toList();
        sheet.appendRow(rowData);
      }
      String sanitizedFileName = DateTimeUtils.getNow()
          .toIso8601String()
          .replaceAll(RegExp(r'[\/:*?"<>|]'), '_');
      if (kIsWeb) {
        excel.save(fileName: '$sanitizedFileName.xlsx');

        return 'success';
      } else {
        await PermissionService.getPermission(permission: Permission.storage);
        // Save the file
        Directory? directory = await getDownloadsDirectory();
        String filePath = '${directory?.path}/$sanitizedFileName.xlsx';
        File(filePath)
          ..createSync(recursive: true)
          ..writeAsBytesSync(excel.save()!);
        if (kDebugMode) {
          print('Excel file saved at $filePath');
        }
        return filePath;
      }
    } catch (e) {
      if (kDebugMode) {
        print('Excel file saved Error: $e');
      }
      return null;
    }
  }
}
