import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/utils/extension_format.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/system/system_setting.dart';
import 'package:niogu_app/core/widgets/custom_snackbar.dart';
import 'package:niogu_app/features/goods/products/domain/entities/product.dart';
import 'package:niogu_app/features/goods/products/presentation/providers/product_provider.dart';
import 'package:sizer/sizer.dart';

class DeleteProductScreen extends ConsumerStatefulWidget {
  final DeleteProductSnapshot productSnapshot;
  const DeleteProductScreen({super.key, required this.productSnapshot});

  @override
  ConsumerState<DeleteProductScreen> createState() =>
      _DeleteProductScreenState();
}

class _DeleteProductScreenState extends ConsumerState<DeleteProductScreen> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  Future<void> _onDeleteCurrentProduct() async {
    final outletId = await SystemSetting.getCurrentOutletId();

    try {
      await ref
          .read(productControllerProvider.notifier)
          .deleteProduct(
            widget.productSnapshot.productId,
            outletId: outletId!,
            canDeleteAll: false,
          );

      if (!mounted) return;

      CustomSnackbar.showSuccess(context, 'Produk berhasil dihapus');
      context.pop();
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, "Ups, terjadi kesalahan");
      context.pop();
    }
  }

  Future<void> _onDeleteAllProduct() async {
    try {
      await ref
          .read(productControllerProvider.notifier)
          .deleteProduct(widget.productSnapshot.productId, canDeleteAll: true);

      if (!mounted) return;

      CustomSnackbar.showSuccess(context, 'Produk berhasil dihapus');
      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) {
    final bool isTablet = 100.w >= 600;
    final double maxWidth = 100.w >= 1280
        ? 1200
        : isTablet
        ? 800
        : 400;

    final bool isMainOutlet = widget.productSnapshot.isMainOutlet;

    final int totalOutletCount = widget.productSnapshot.totalOutletCount;

    final bool isMultiLocation = isMainOutlet && totalOutletCount > 1;

    final bool imagePathAvailable =
        widget.productSnapshot.imagePath != null &&
        widget.productSnapshot.imagePath!.isNotEmpty;

    final File imageFile = File(
      imagePathAvailable
          ? widget.productSnapshot.imagePath!
          : "image not found",
    );

    final bool imageFileExists = imageFile.existsSync();

    final productControllerState = ref.watch(productControllerProvider);

    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4.w)),
      elevation: 0,
      backgroundColor: Colors.transparent,
      child: Container(
        padding: EdgeInsets.all(5.w),
        width: double.infinity,
        constraints: BoxConstraints(maxWidth: maxWidth),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(4.w),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              padding: EdgeInsets.all(3.w),
              decoration: BoxDecoration(
                color: Colors.red[50],
                shape: BoxShape.circle,
              ),
              child: Icon(Icons.delete_outline, color: Colors.red, size: 8.w),
            ),
            SizedBox(height: 2.h),
            Text(
              "Hapus Produk?",
              style: TextStyle(
                fontSize: AppFontSize.medium.sp,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
            SizedBox(height: 1.h),
            Text(
              "Tindakan ini tidak dapat dibatalkan.",
              style: TextStyle(
                fontSize: isTablet
                    ? AppFontSize.medium.sp
                    : AppFontSize.small.sp,
                color: Colors.grey[800],
              ),
            ),
            SizedBox(height: 3.h),

            Container(
              padding: EdgeInsets.symmetric(vertical: 3.w),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(2.5.w),
              ),
              child: Row(
                children: [
                  Container(
                    height: 15.w,
                    width: 15.w,
                    decoration: BoxDecoration(
                      color: Colors.grey[200],
                      border: imageFileExists
                          ? Border.all(color: Colors.grey)
                          : null,
                      borderRadius: BorderRadius.circular(2.5.w),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(2.5.w),
                      child: imageFileExists
                          ? Image.file(
                              imageFile,
                              fit: BoxFit.cover,
                              width: double.infinity,
                              height: double.infinity,
                              errorBuilder: (context, error, stackTrace) {
                                return const Icon(
                                  Icons.error,
                                  color: Colors.grey,
                                );
                              },
                            )
                          : Icon(Icons.image, color: Colors.grey, size: 8.w),
                    ),
                  ),

                  SizedBox(width: 3.w),

                  // Detail Text
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          widget.productSnapshot.name,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: isTablet
                                ? AppFontSize.medium.sp
                                : AppFontSize.small.sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.black87,
                          ),
                        ),
                        SizedBox(height: 0.5.h),
                        // Badge Terjual
                        Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: 2.w,
                            vertical: 0.5.h,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.green[50],
                            borderRadius: BorderRadius.circular(1.w),
                          ),
                          child: Text(
                            "${widget.productSnapshot.totalSold.toCompact} Terjual",
                            style: TextStyle(
                              fontSize: isTablet
                                  ? (AppFontSize.medium - 2).sp
                                  : (AppFontSize.small - 2).sp,
                              color: Colors.green[700],
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                        SizedBox(height: 0.5.h),

                        Row(
                          children: [
                            Icon(Icons.store, size: 4.w, color: Colors.grey),
                            SizedBox(width: 1.w),
                            Expanded(
                              child: Text(
                                isMultiLocation
                                    ? "${widget.productSnapshot.currentOutletName} (+${widget.productSnapshot.totalOutletCount - 1} lainnya)"
                                    : widget.productSnapshot.currentOutletName,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  fontSize: isTablet
                                      ? (AppFontSize.medium - 1).sp
                                      : (AppFontSize.small - 1).sp,
                                  color: Colors.grey[600],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),

            SizedBox(height: 3.h),

            if (isMultiLocation) ...[
              _buildButton(
                context,
                label: "Hapus di Outlet Ini Saja",
                color: const Color.fromARGB(255, 156, 10, 0),
                onPressed: productControllerState.isLoading
                    ? null
                    : _onDeleteCurrentProduct,
              ),
              SizedBox(height: 1.5.h),
              _buildButton(
                context,
                label: "Hapus di SEMUA Outlet",
                color: Colors.red,
                onPressed: productControllerState.isLoading
                    ? null
                    : _onDeleteAllProduct,
              ),
            ] else ...[
              _buildButton(
                context,
                label: "Ya, Hapus",
                color: Colors.red,
                onPressed: productControllerState.isLoading
                    ? null
                    : isMainOutlet && totalOutletCount == 1
                    ? _onDeleteAllProduct
                    : _onDeleteCurrentProduct,
              ),
            ],

            SizedBox(height: 1.5.h),

            TextButton(
              onPressed: productControllerState.isLoading
                  ? null
                  : () => context.pop(),
              child: Text(
                "Batal",
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: AppFontSize.medium.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildButton(
    BuildContext context, {
    required String label,
    required Color color,
    required VoidCallback? onPressed,
  }) {
    return SizedBox(
      width: double.infinity,
      height: 6.h,
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: color,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(2.5.w),
          ),
          disabledBackgroundColor: Colors.grey.shade300,
        ),
        child: Text(
          label,
          style: TextStyle(
            color: Colors.white,
            fontSize: AppFontSize.medium.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}
