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/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/raw_materials/domain/entities/raw_material.dart';
import 'package:niogu_app/features/goods/raw_materials/presentation/providers/raw_material_provider.dart';
import 'package:sizer/sizer.dart';

class DeleteRawMaterialScreen extends ConsumerStatefulWidget {
  final DeleteRawMaterialSnapshot rawMaterialSnapshot;
  const DeleteRawMaterialScreen({super.key, required this.rawMaterialSnapshot});

  @override
  ConsumerState<DeleteRawMaterialScreen> createState() =>
      _DeleteRawMaterialScreenState();
}

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

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

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

    try {
      await ref
          .read(rawMaterialControllerProvider.notifier)
          .deleteRawMaterial(
            widget.rawMaterialSnapshot.rawMaterialId,
            outletId: outletId!,
            canDeleteAll: false,
          );

      if (!mounted) return;

      CustomSnackbar.showSuccess(context, 'Bahan baku 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> _onDeleteAllRawMaterial() async {
    try {
      await ref
          .read(rawMaterialControllerProvider.notifier)
          .deleteRawMaterial(
            widget.rawMaterialSnapshot.rawMaterialId,
            canDeleteAll: true,
          );

      if (!mounted) return;

      CustomSnackbar.showSuccess(context, 'Bahan baku 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.rawMaterialSnapshot.isMainOutlet;

    final int totalOutletCount = widget.rawMaterialSnapshot.totalOutletCount;

    final bool isMultiLocation = isMainOutlet && totalOutletCount > 1;

    final rawMaterialControllerState = ref.watch(rawMaterialControllerProvider);

    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      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 Bahan Baku?",
              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: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          widget.rawMaterialSnapshot.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.rawMaterialSnapshot.totalProductUsage} Produk menggunakan bahan baku ini",
                            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.rawMaterialSnapshot.currentOutletName} (+${widget.rawMaterialSnapshot.totalOutletCount - 1} lainnya)"
                                    : widget
                                          .rawMaterialSnapshot
                                          .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: rawMaterialControllerState.isLoading
                    ? null
                    : _onDeleteCurrentRawMaterial,
              ),
              SizedBox(height: 1.5.h),
              _buildButton(
                context,
                label: "Hapus di SEMUA Outlet",
                color: Colors.red,
                onPressed: rawMaterialControllerState.isLoading
                    ? null
                    : _onDeleteAllRawMaterial,
              ),
            ] else ...[
              _buildButton(
                context,
                label: "Hapus Bahan Baku",
                color: Colors.red,
                onPressed: rawMaterialControllerState.isLoading
                    ? null
                    : isMainOutlet && totalOutletCount == 1
                    ? _onDeleteAllRawMaterial
                    : _onDeleteCurrentRawMaterial,
              ),
            ],

            SizedBox(height: 1.5.h),

            TextButton(
              onPressed: () => 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,
          ),
        ),
      ),
    );
  }
}
