import 'dart:io';

import 'package:excel/excel.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:intl/intl.dart';
import 'package:mobile_pos/Screens/Expense/Model/expense_modle.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';

import '../../model/business_info_model.dart';
import '../ledger_report/generate_pdf_date_range.dart';

Future<void> generateExpenseReportExcel(
  BuildContext context,
  List<Expense>? data,
  BusinessInformationModel? business,
  DateTime? fromDate,
  DateTime? toDate,
  String selectedTime,
) async {
  EasyLoading.show(status: 'Generating Excel');

  try {
    final excel = Excel.createExcel();
    final sheet = excel['Expense Report'];
    final pdfRange = getPdfDateRangeForSelectedTime(
      selectedTime,
      fromDate: fromDate,
      toDate: toDate,
    );

    final fromStr = pdfRange['from']!;
    final toStr = pdfRange['to']!;

    double totalAmount = data?.fold(0, (sum, item) => sum! + (item.amount ?? 0)) ?? 0;

    // // Styles
    // final businessStyle = CellStyle(bold: true, fontSize: 12);
    // final titleStyle = CellStyle(bold: true, fontSize: 12);
    // final headerStyle = CellStyle(bold: true, fontSize: 12);
    // final footerStyle = CellStyle(bold: true, fontSize: 12);

    // Row 1: Company Name
    sheet.appendRow([TextCellValue(business?.data?.companyName ?? '')]);
    sheet.cell(CellIndex.indexByString("A1")).cellStyle;

    // Row 2: Report Title
    sheet.appendRow([TextCellValue('Expense Report')]);
    sheet.cell(CellIndex.indexByString("A2")).cellStyle;

    // Row 3: Duration
    sheet.appendRow([
      TextCellValue('Duration: $fromStr to $toStr'),
    ]);

    // Row 4: Empty for spacing
    sheet.appendRow([]);

    // Row 5: Header
    final headerRowIndex = sheet.maxRows;
    sheet.appendRow([
      TextCellValue('SL'),
      TextCellValue('Date'),
      TextCellValue('Expense For'),
      TextCellValue('Category'),
      TextCellValue('Amount'),
    ]);

    sheet.appendRow([]);

    // Apply bold style to each header cell only
    for (var i = 0; i < 5; i++) {
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: i, rowIndex: headerRowIndex)).cellStyle;
    }

    if (data != null) {
      for (int i = 0; i < data.length; i++) {
        sheet.appendRow([
          TextCellValue('${i + 1}'),
          TextCellValue(DateFormat('dd-MM-yyyy').format(DateTime.parse(data[i].expenseDate.toString()))),
          TextCellValue(data[i].expanseFor ?? 'n/a'),
          TextCellValue(data[i].category?.categoryName ?? 'n/a'),
          TextCellValue(data[i].amount?.toStringAsFixed(2) ?? '0.00'),
        ]);
      }
    }

    final totalRowIndex = sheet.maxRows;
    sheet.appendRow([
      TextCellValue('Total'),
      TextCellValue(''),
      TextCellValue(''),
      TextCellValue(''),
      TextCellValue(totalAmount.toStringAsFixed(2)),
    ]);

    for (var i = 0; i < 5; i++) {
      sheet.cell(CellIndex.indexByColumnRow(columnIndex: i, rowIndex: totalRowIndex)).cellStyle;
    }

    final dir = await getApplicationDocumentsDirectory();
    final filePath = '${dir.path}/${business?.data?.companyName ?? "Company"}_Expense_Report.xlsx';
    final file = File(filePath);
    await file.writeAsBytes(excel.encode()!);

    EasyLoading.showSuccess('Report Generated');
    await OpenFile.open(filePath);
  } catch (e) {
    EasyLoading.showError('Error: $e');
    debugPrint('Error during Excel generation: $e');
  }
}
