import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/enums/stock_type.dart';
import 'package:niogu_app/core/widgets/custom_button.dart';
import 'package:niogu_app/core/widgets/custom_text_form_field.dart';
import 'package:sizer/sizer.dart';

class DecimalQuantity extends StatefulWidget {
  final String name;
  final String variantName;
  final StockType stockType;
  final String remainingStock;
  final String unit;
  final String initialQuantity;
  final String sellingPrice;
  final Function(String) onPressed;

  const DecimalQuantity({
    super.key,
    required this.name,
    required this.variantName,
    required this.stockType,
    required this.remainingStock,
    required this.unit,
    required this.initialQuantity,
    required this.sellingPrice,
    required this.onPressed,
  });

  @override
  State<DecimalQuantity> createState() => _DecimalQuantityState();
}

class _DecimalQuantityState extends State<DecimalQuantity> {
  late GlobalKey<FormState> _formKey;
  late TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _formKey = GlobalKey<FormState>();
    _controller = TextEditingController(text: widget.initialQuantity);
  }

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

  @override
  Widget build(BuildContext context) {
    final bool isTablet = 100.w >= 600;

    final double maxWidth = 100.w >= 1280
        ? 1200
        : isTablet
        ? 800
        : 400;

    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4.w)),
      backgroundColor: Colors.white,
      child: Container(
        padding: EdgeInsets.all(5.w),
        constraints: BoxConstraints(maxHeight: 85.h, maxWidth: maxWidth),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                "Masukkan Kuantitas",
                style: TextStyle(
                  fontSize: isTablet
                      ? AppFontSize.medium.sp
                      : AppFontSize.small.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
              ),
              SizedBox(height: 2.h),

              Flexible(
                child: SingleChildScrollView(
                  physics: const ClampingScrollPhysics(),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      CustomTextFormField(
                        label: "Nama Produk",
                        controller: TextEditingController(text: widget.name),
                        readOnly: true,
                      ),

                      SizedBox(height: 1.5.h),

                      CustomTextFormField(
                        label: "Varian Produk",
                        controller: TextEditingController(
                          text: widget.variantName,
                        ),
                        readOnly: true,
                      ),

                      SizedBox(height: 1.5.h),

                      Row(
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                CustomTextFormField(
                                  label: "Sisa Stok",
                                  controller: TextEditingController(
                                    text: widget.stockType == StockType.fixed
                                        ? "${widget.remainingStock} ${widget.unit}"
                                        : "Selalu ada",
                                  ),
                                  readOnly: true,
                                ),
                              ],
                            ),
                          ),
                          SizedBox(width: 3.w),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                CustomTextFormField(
                                  label: "Harga Jual",
                                  controller: TextEditingController(
                                    text: widget.sellingPrice,
                                  ),
                                  readOnly: true,
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),

                      SizedBox(height: 2.h),

                      CustomTextFormField(
                        label: "Kuantitas Desimal",
                        hint: "Gunakan titik (.), misal 0.5",
                        keyboardType: const TextInputType.numberWithOptions(
                          decimal: true,
                        ),
                        autoFocus: true,
                        controller: _controller,
                        validator: (value) {
                          if (value == null || value.isEmpty)
                            return "Kuantitas belum diisi";
                          if (double.tryParse(value) == null)
                            return "Kuantitas tidak valid";
                          if (double.parse(value) <= 0)
                            return "Kuantitas harus lebih dari 0";

                          final double stock = double.parse(
                            widget.remainingStock,
                          );

                          final double quantity = double.parse(value.trim());

                          if (widget.stockType == StockType.fixed &&
                              quantity > stock)
                            return "Stok tidak cukup";
                          return null;
                        },
                      ),

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

              SizedBox(height: 2.h),

              CustomButton(
                title: "Ubah",
                onPressed: () {
                  if (!_formKey.currentState!.validate()) return;

                  widget.onPressed(_controller.text.trim());

                  context.pop();
                },
              ),
              SizedBox(height: 1.h),
            ],
          ),
        ),
      ),
    );
  }
}
