import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:gal/gal.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/components/top_back_bar_app.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/enums/purchase_status.dart';
import 'package:niogu_app/core/widgets/custom_confirmation.dart';
import 'package:niogu_app/core/widgets/custom_snackbar.dart';
import 'package:niogu_app/features/report/transaction/domain/entities/transaction_report.dart';
import 'package:niogu_app/features/report/transaction/presentation/providers/transaction_report_provider.dart';
import 'package:niogu_app/features/report/transaction/presentation/widgets/brand_purchase_header.dart';
import 'package:niogu_app/features/report/transaction/presentation/widgets/dashed_divider.dart';
import 'package:niogu_app/features/report/transaction/presentation/widgets/footer_purchase_info.dart';
import 'package:niogu_app/features/report/transaction/presentation/widgets/general_purchase_info.dart';
import 'package:niogu_app/features/report/transaction/presentation/widgets/payment_proof.dart';
import 'package:niogu_app/features/report/transaction/presentation/widgets/payment_purchase_summary.dart';
import 'package:niogu_app/features/report/transaction/presentation/widgets/purchase_item_list.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:screenshot/screenshot.dart';
import 'package:share_plus/share_plus.dart';
import 'package:sizer/sizer.dart';

class TransactionReportPurchaseDetailScreen extends ConsumerWidget {
  final PurchaseDetail purchaseDetail;

  TransactionReportPurchaseDetailScreen({
    super.key,
    required this.purchaseDetail,
  });

  final ScreenshotController screenshotController = ScreenshotController();

  Future<void> _handleShareAction(BuildContext context) async {
    final bool isTablet = 100.w >= 600;
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(2.5.w)),
      ),
      constraints: const BoxConstraints(maxWidth: double.infinity),
      builder: (BuildContext context) {
        return SafeArea(
          child: Container(
            width: 100.w,
            padding: EdgeInsets.symmetric(vertical: 2.h, horizontal: 5.w),
            clipBehavior: Clip.hardEdge,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.vertical(top: Radius.circular(6.w)),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                ListTile(
                  leading: Icon(Icons.download_rounded, size: 6.w),
                  title: Text(
                    'Unduh',
                    style: TextStyle(
                      fontSize: isTablet
                          ? AppFontSize.medium.sp
                          : AppFontSize.small.sp,
                    ),
                  ),
                  onTap: () async {
                    await _processImage(context, isDownload: true);
                    context.pop();
                  },
                ),

                SizedBox(height: 2.h),

                ListTile(
                  leading: Icon(Icons.share_rounded, size: 6.w),
                  title: Text(
                    'Bagikan',
                    style: TextStyle(
                      fontSize: isTablet
                          ? AppFontSize.medium.sp
                          : AppFontSize.small.sp,
                    ),
                  ),
                  onTap: () async {
                    await _processImage(context, isDownload: false);
                    context.pop();
                  },
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<void> _processImage(
    BuildContext context, {
    required bool isDownload,
  }) async {
    try {
      final image = await screenshotController.capture();
      if (image == null) return;

      if (isDownload) {
        if (Platform.isAndroid) {
          final request = await Permission.storage.request();

          if (request.isDenied) {
            CustomSnackbar.showWarning(context, "Akses Ditolak");
            return;
          }
        }

        await Gal.putImageBytes(image);

        if (!context.mounted) return;
        CustomSnackbar.showSuccess(
          context,
          "Gambar berhasil disimpan ke galeri",
        );
      } else {
        final directory = await getTemporaryDirectory();

        final imagePath = await File(
          '${directory.path}/transaction.png',
        ).create();

        await imagePath.writeAsBytes(image);

        await Share.shareXFiles([XFile(imagePath.path)]);
      }
    } catch (e, st) {
      if (!context.mounted) return;
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, "Ups, terjadi kesalahan");
    }
  }

  Future<void> _cancelPurchase(
    BuildContext context,
    WidgetRef ref,
    String purchaseId,
  ) async {
    try {
      await ref
          .read(transactionReportControllerProvider.notifier)
          .cancelPurchase(purchaseId);

      if (!context.mounted) return;

      CustomSnackbar.showSuccess(context, "Transaksi berhasil dibatalkan");

      context.pop();
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);

      CustomSnackbar.showError(context, "Ups, terjadi kesalahan");

      context.pop();
    }
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final bool isTablet = 100.w >= 600;

        final transactionReportControllerState = ref.watch(
          transactionReportControllerProvider,
        );

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child:               Scaffold(
                backgroundColor: const Color(0xFFF5F5F5),
                appBar: TopBackBarApp(
                  title: "Detail Transaksi",
                  onTap: () => context.pop(),
                ),
                body: SingleChildScrollView(
                  padding: EdgeInsets.fromLTRB(4.w, 2.h, 4.w, 12.h),
                  child: Column(
                    children: [
                      Screenshot(
                        controller: screenshotController,
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(4.w),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withOpacity(0.05),
                                blurRadius: 15,
                                offset: const Offset(0, 5),
                              ),
                            ],
                          ),
                          child: Column(
                            children: [
                              BrandPurchaseHeader(
                                purchaseDetail: purchaseDetail,
                              ),

                              const DashedDivider(),

                              GeneralPurchaseInfo(
                                purchaseDetail: purchaseDetail,
                              ),

                              const DashedDivider(),

                              PurchaseItemList(purchaseDetail: purchaseDetail),

                              const DashedDivider(),

                              PaymentPurchaseSummary(
                                purchaseDetail: purchaseDetail,
                              ),

                              if (purchaseDetail.paymentProofPath != null &&
                                  purchaseDetail
                                      .paymentProofPath!
                                      .isNotEmpty) ...[
                                const DashedDivider(),

                                PaymentProof(
                                  imagePath: purchaseDetail.paymentProofPath!,
                                ),
                              ],

                              if (purchaseDetail.note != null ||
                                  purchaseDetail.supplierName != null) ...[
                                const DashedDivider(),
                                FooterPurchaseInfo(
                                  purchaseDetail: purchaseDetail,
                                ),
                              ],

                              SizedBox(height: 3.h),
                            ],
                          ),
                        ),
                      ),

                      SizedBox(height: 2.h),

                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 5.w),
                        child:
                            purchaseDetail.purchaseStatus ==
                                PurchaseStatus.completed
                            ? TextButton.icon(
                                onPressed: () {
                                  showDialog(
                                    context: context,
                                    builder: (context) {
                                      final purchaseId =
                                          purchaseDetail.purchaseId;
                                      return CustomConfirmation(
                                        title: "Batalkan Transaksi",
                                        body:
                                            "Batalkan transaksi ${purchaseDetail.purchaseNumber}",
                                        color: Color(0xFFFFA000),
                                        icon: Icons.warning_amber_rounded,
                                        onConfirm:
                                            transactionReportControllerState
                                                .isLoading
                                            ? null
                                            : () async => await _cancelPurchase(
                                                context,
                                                ref,
                                                purchaseId,
                                              ),
                                      );
                                    },
                                  );
                                },
                                style: TextButton.styleFrom(
                                  foregroundColor: Colors.red[700],
                                  padding: EdgeInsets.symmetric(
                                    vertical: 1.5.h,
                                    horizontal: 4.w,
                                  ),
                                ),
                                icon: Icon(Icons.close_rounded, size: 5.w),
                                label: Text(
                                  "Batalkan Transaksi Ini",
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: isTablet
                                        ? AppFontSize.medium.sp
                                        : AppFontSize.small.sp,
                                  ),
                                ),
                              )
                            : Text(
                                "Transaksi Dibatalkan",
                                style: TextStyle(
                                  color: Colors.red.shade700,
                                  fontSize: isTablet
                                      ? AppFontSize.medium.sp
                                      : AppFontSize.small.sp,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                      ),
                    ],
                  ),
                ),

                bottomNavigationBar: Container(
                  padding: EdgeInsets.all(4.w),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.05),
                        blurRadius: 10,
                        offset: const Offset(0, -5),
                      ),
                    ],
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: OutlinedButton.icon(
                          onPressed: () => _handleShareAction(context),
                          style: OutlinedButton.styleFrom(
                            padding: EdgeInsets.symmetric(vertical: 1.8.h),
                            side: BorderSide(color: AppColor.primaryColor),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(2.5.w),
                            ),
                          ),
                          icon: Icon(
                            Icons.share_outlined,
                            color: AppColor.primaryColor,
                            size: 5.w,
                          ),
                          label: Text(
                            "Bagikan",
                            style: TextStyle(
                              color: AppColor.primaryColor,
                              fontWeight: FontWeight.bold,
                              fontSize: AppFontSize.medium.sp,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 3.w),
                      Expanded(
                        child: ElevatedButton.icon(
                          onPressed: () {},
                          style: ElevatedButton.styleFrom(
                            padding: EdgeInsets.symmetric(vertical: 1.8.h),
                            backgroundColor: AppColor.primaryColor,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(2.5.w),
                            ),
                            elevation: 0,
                          ),
                          icon: Icon(
                            Icons.print_outlined,
                            color: Colors.white,
                            size: 5.w,
                          ),
                          label: Text(
                            "Cetak Struk",
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: AppFontSize.medium.sp,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
        );
      },
    );
  }
}
