import 'package:calendar_date_picker2/calendar_date_picker2.dart';
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_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/providers/app_provider.dart';
import 'package:niogu_app/core/utils/extension_format.dart';
import 'package:niogu_app/core/enums/item_type.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/enums/stock_card_type.dart';
import 'package:niogu_app/core/widgets/custom_snackbar.dart';
import 'package:niogu_app/features/stock_in/presentation/widgets/body_form.dart';
import 'package:niogu_app/features/stock_in/presentation/widgets/body_section.dart';
import 'package:niogu_app/features/stock_in/presentation/widgets/empty_item.dart';
import 'package:niogu_app/features/stock_in/presentation/widgets/item_quantity_amount.dart';
import 'package:niogu_app/features/stock_in/presentation/widgets/note_section.dart';
import 'package:niogu_app/features/stock_in/domain/entities/stock_in.dart';
import 'package:niogu_app/features/stock_in/presentation/provider/stock_in_provider.dart';
import 'package:niogu_app/features/stock_in/presentation/widgets/header_stock_in_production_section.dart';
import 'package:sizer/sizer.dart';

class StockInProductionScreen extends ConsumerStatefulWidget {
  const StockInProductionScreen({super.key});

  @override
  ConsumerState<StockInProductionScreen> createState() =>
      StockInProductionScreenState();
}

class StockInProductionScreenState
    extends ConsumerState<StockInProductionScreen>
    with AutomaticKeepAliveClientMixin {
  DateTime _selectedDate = DateTime.now();

  TextEditingController _noteController = TextEditingController();

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

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

  @override
  void dispose() {
    _noteController.dispose();
    super.dispose();
  }

  Future<void> _showProductionDatePicker(BuildContext context) async {
    final bool isTablet = 100.w >= 600;

    List<DateTime?> tempPickedDate = [_selectedDate];

    final List<DateTime?>? results = await showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      constraints: const BoxConstraints(maxWidth: double.infinity),
      builder: (context) {
        return Container(
          height: 80.h,
          width: double.infinity,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(4.5.w)),
          ),
          constraints: BoxConstraints(
            maxHeight: 80.h,
            maxWidth: double.infinity,
          ),
          child: Column(
            children: [
              SizedBox(height: 1.5.h),
              Container(
                width: 12.w,
                height: 0.6.h,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(2.5.w),
                ),
              ),
              Padding(
                padding: EdgeInsets.symmetric(vertical: 2.h),
                child: Text(
                  "Pilih Tanggal Produksi",
                  style: TextStyle(
                    fontSize: isTablet
                        ? AppFontSize.medium.sp
                        : AppFontSize.small.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
              ),
              Divider(height: 1, color: Colors.grey[200]),

              Expanded(
                child: CalendarDatePicker2(
                  config: CalendarDatePicker2Config(
                    calendarType: CalendarDatePicker2Type.single,
                    selectedDayHighlightColor: AppColor.primaryColor,
                    weekdayLabels: [
                      'Min',
                      'Sen',
                      'Sel',
                      'Rab',
                      'Kam',
                      'Jum',
                      'Sab',
                    ],
                    weekdayLabelTextStyle: TextStyle(
                      color: Colors.grey[600],
                      fontWeight: FontWeight.bold,
                    ),
                    controlsTextStyle: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                      fontSize: isTablet
                          ? AppFontSize.medium.sp
                          : AppFontSize.small.sp,
                    ),
                    dayTextStyle: TextStyle(
                      color: Colors.black87,
                      fontWeight: FontWeight.w500,
                    ),

                    centerAlignModePicker: true,
                    firstDayOfWeek: 1, // Senin
                  ),
                  value: tempPickedDate,
                  onValueChanged: (dates) {
                    tempPickedDate = dates;
                  },
                ),
              ),

              Container(
                padding: EdgeInsets.all(5.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(
                        onPressed: () => context.pop(),
                        style: OutlinedButton.styleFrom(
                          padding: EdgeInsets.symmetric(vertical: 1.5.h),
                          side: BorderSide(color: AppColor.primaryColor),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(2.5.w),
                          ),
                        ),
                        child: Text(
                          "Batal",
                          style: TextStyle(
                            color: AppColor.primaryColor,
                            fontWeight: FontWeight.bold,
                            fontSize: AppFontSize.medium.sp,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 3.w),

                    Expanded(
                      child: ElevatedButton(
                        onPressed: () {
                          context.pop(tempPickedDate);
                        },
                        style: ElevatedButton.styleFrom(
                          padding: EdgeInsets.symmetric(vertical: 1.5.h),
                          backgroundColor: AppColor.primaryColor,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(2.5.w),
                          ),
                        ),
                        child: Text(
                          "Pilih",
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: AppFontSize.medium.sp,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );

    if (results != null && results.isNotEmpty && results[0] != null) {
      setState(() {
        _selectedDate = results[0]!;
      });
    }
  }

  Future<void> updateStockItem() async {
    final selectedItemState = ref.read(
      selectedItemProvider(SelectedItemType.production),
    );

    final selectedItems = selectedItemState.values.where((item) {
      return item.type == SelectedItemType.production;
    }).toList();

    if (selectedItems.isEmpty) {
      CustomSnackbar.showWarning(context, "Tambah minimal 1 barang");
      return;
    }

    final items = selectedItems.map((item) {
      return UpdateStockItem(
        outletInventoryId: item.id,
        stockCardType: StockCardType.production,
        remainingStock: item.remainingStock,
        qtyChange: item.quantity,
        updateStock: item.remainingStock + item.quantity,
        currentStock: item.remainingStock + item.quantity,
        costPrice: item.costPrice,
        purchasePrice: item.purchasePrice,
        notes: _noteController.text.trim(),
      );
    }).toList();

    try {
      await ref
          .read(stockInControllerProvider.notifier)
          .updateStockItem(items: items);

      if (!mounted) return;

      CustomSnackbar.showSuccess(context, "Stok barang berhasil diperbarui");

      setState(() {
        _selectedDate = DateTime.now();
      });

      ref.invalidate(selectedItemProvider);

      _noteController.clear();
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, "Ups, terjadi kesalahan");
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    final bool isTablet = 100.w >= 600;

    final currentUserName = ref.watch(currentUserNameProvider);

    final selectedItemState = ref.watch(
      selectedItemProvider(SelectedItemType.production),
    );

    final selectedItems = selectedItemState.values.where((item) {
      return item.type == SelectedItemType.production;
    }).toList();

    return Column(
      children: [
        Expanded(
          child: SingleChildScrollView(
            padding: EdgeInsets.all(5.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                HeaderStockInProductionSection(
                  selectedDate: _selectedDate,
                  currentUserName: currentUserName!,
                  onTap: () => _showProductionDatePicker(context),
                ),

                SizedBox(height: 3.h),

                BodySection(
                  label: "Hasil Produksi (${selectedItems.length})",
                  type: SelectedItemType.production,
                ),

                SizedBox(height: 1.5.h),

                if (selectedItems.isEmpty)
                  const EmptyItem(
                    icon: Icons.post_add_rounded,
                    title: "Belum ada barang produksi",
                    subtitle: "Tekan 'Tambah Barang' untuk memulai",
                  )
                else
                  BodyForm(
                    selectedItems: selectedItems,
                    label: "Jumlah Produksi:",
                    onDecrementTap: (item) {
                      ref
                          .read(
                            selectedItemProvider(
                              SelectedItemType.production,
                            ).notifier,
                          )
                          .decrement(item.id);
                    },
                    onIncrementTap: (item) {
                      ref
                          .read(
                            selectedItemProvider(
                              SelectedItemType.production,
                            ).notifier,
                          )
                          .increment(item.id);
                    },
                    onEditPressed: (item) {
                      showDialog(
                        context: context,
                        builder: (_) {
                          final ItemType itemType = item.itemType;

                          final String name = item.name;

                          final String? variantName = item.variantName;

                          final String remainingStock = item.remainingStock
                              .toStringWithoutTrailingZero();

                          final String unit = item.unit;

                          final String initialQuantity = item.quantity
                              .toStringWithoutTrailingZero();

                          return ItemQuantityAmount(
                            itemType: itemType,
                            variantName: variantName,
                            name: name,
                            remainingStock: remainingStock,
                            unit: unit,
                            initialQuantity: initialQuantity,
                            label: "Jumlah Produksi",
                            onPressed: (value) {
                              try {
                                final double quantity = double.parse(value);

                                ref
                                    .read(
                                      selectedItemProvider(
                                        SelectedItemType.production,
                                      ).notifier,
                                    )
                                    .customQuantity(item.id, quantity);
                              } catch (e) {
                                CustomSnackbar.showError(
                                  context,
                                  "Stok tidak valid",
                                );
                              }
                            },
                          );
                        },
                      );
                    },
                    onDeletePressed: (item) {
                      ref
                          .read(
                            selectedItemProvider(
                              SelectedItemType.production,
                            ).notifier,
                          )
                          .delete(item.id);
                    },
                  ),

                SizedBox(height: 3.h),

                Text(
                  "Catatan (Opsional)",
                  style: TextStyle(
                    fontSize: (AppFontSize.medium - 1.25).sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: 1.h),
                NoteSection(
                  isTablet: isTablet,
                  controller: _noteController,
                  hint: "Contoh: Batch Produksi Pagi #001",
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
