import 'package:flutter/material.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/enums/user_role.dart';
import 'package:niogu_app/core/widgets/custom_text_form_field.dart';
import 'package:niogu_app/features/goods/products/presentation/widgets/product_variant_model.dart';
import 'package:niogu_app/features/goods/products/presentation/widgets/image_uploader_product_variant.dart';
import 'package:niogu_app/features/goods/raw_materials/presentation/widgets/checkbox_product_card.dart';
import 'package:sizer/sizer.dart';

class VariantProductCard extends StatelessWidget {
  final UserRole userRole;
  final bool isMainOutlet;
  final bool isEditing;
  final bool isSelected;
  final GlobalKey<FormState> formKey;
  final int length;
  final ProductVariantModel variant;
  final int index;
  final bool isStockFixed;
  final TextEditingController nameController;
  final TextEditingController stockController;
  final TextEditingController costPriceController;
  final TextEditingController sellingPriceController;
  final VoidCallback? onTapSelected;
  final VoidCallback onTapRemoveVarian;
  final VoidCallback onTapVariantImageAdd;
  final VoidCallback onTapVariantImageRemove;

  const VariantProductCard({
    super.key,
    required this.userRole,
    required this.isMainOutlet,
    required this.isEditing,
    this.isSelected = false,
    required this.formKey,
    required this.length,
    required this.variant,
    required this.index,
    required this.isStockFixed,
    required this.nameController,
    required this.stockController,
    required this.costPriceController,
    required this.sellingPriceController,
    this.onTapSelected,
    required this.onTapRemoveVarian,
    required this.onTapVariantImageAdd,
    required this.onTapVariantImageRemove,
  });

  @override
  Widget build(BuildContext context) {
    final double costPrice =
        double.tryParse(costPriceController.text.trim()) ?? 0.0;

    final double sellingPrice =
        double.tryParse(sellingPriceController.text.trim()) ?? 0.0;

    final bool validatePrice =
        double.tryParse(costPriceController.text.trim()) != null &&
        double.tryParse(sellingPriceController.text.trim()) != null &&
        costPrice > 0 &&
        sellingPrice > 0 &&
        costPrice >= sellingPrice;

    final enabledBorderColor = validatePrice
        ? Colors.red
        : Colors.grey.shade300;

    final focusedBorderColor = validatePrice
        ? Colors.red
        : AppColor.primaryColor;

    final bool readOnly =
        isEditing &&
        variant.productVariantId != null &&
        variant.outletInventoryId != null;

    final String? message = readOnly ? "Tambah stok di menu stok masuk" : null;

    String title = "Variant #${index + 1}";

    final isNewVariant =
        ((userRole == UserRole.owner && !isMainOutlet) ||
            userRole == UserRole.admin) &&
        variant.outletInventoryId == null;

    if (isNewVariant) title = "Varian Baru";

    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4.w),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.fromLTRB(4.w, 2.h, 4.w, 0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 3.w,
                    vertical: 0.5.h,
                  ),
                  decoration: BoxDecoration(
                    color: AppColor.primaryColor.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(4.05.w),
                  ),
                  child: Text(
                    title,
                    style: TextStyle(
                      color: AppColor.primaryColor,
                      fontWeight: FontWeight.bold,
                      fontSize: AppFontSize.small.sp,
                    ),
                  ),
                ),

                if (length > 1 && userRole == UserRole.owner && isMainOutlet)
                  InkWell(
                    onTap: onTapRemoveVarian,
                    borderRadius: BorderRadius.circular(4.w),
                    child: Container(
                      padding: EdgeInsets.all(2.w),
                      decoration: BoxDecoration(
                        color: Colors.red[50],
                        borderRadius: BorderRadius.circular(4.w),
                      ),
                      child: Icon(
                        Icons.delete_outline_rounded,
                        color: Colors.red,
                        size: 5.w,
                      ),
                    ),
                  )
                else if (isNewVariant)
                  GestureDetector(
                    onTap: onTapSelected,
                    child: CheckboxProductCard(isSelected: isSelected),
                  ),
              ],
            ),
          ),

          Divider(color: Colors.grey[100], height: 3.h),

          Form(
            key: formKey,
            child: Padding(
              padding: EdgeInsets.fromLTRB(4.w, 0, 4.w, 3.h),
              child: Column(
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      ImageUploaderProductVariant(
                        userRole: userRole,
                        isMainOutlet: isMainOutlet,
                        variant: variant,
                        onTapVariantImageAdd: onTapVariantImageAdd,
                        onTapVariantImageRemove: onTapVariantImageRemove,
                      ),

                      SizedBox(width: 3.w),

                      Expanded(
                        child: CustomTextFormField(
                          label: "Nama Varian",
                          controller: nameController,
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return "Nama varian belum diisi";
                            }

                            return null;
                          },
                          readOnly:
                              (userRole == UserRole.owner && !isMainOutlet) ||
                              userRole == UserRole.admin,
                        ),
                      ),
                    ],
                  ),

                  SizedBox(height: 2.5.h),

                  CustomTextFormField(
                    label: "Harga Modal",
                    hint: "0",
                    keyboardType: TextInputType.number,
                    controller: costPriceController,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return "Harga modal belum diisi";
                      }

                      try {
                        if (double.parse(value) <= 0) {
                          return "Harga modal harus lebih dari 0";
                        }
                      } catch (e) {
                        return "Harga modal tidak valid";
                      }

                      return null;
                    },
                    enabledBorderColor: enabledBorderColor,
                    focusedBorderColor: focusedBorderColor,
                  ),

                  SizedBox(height: 2.5.h),

                  CustomTextFormField(
                    label: "Harga Jual",
                    hint: "0",
                    keyboardType: TextInputType.number,
                    controller: sellingPriceController,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return "Harga jual belum diisi";
                      }

                      try {
                        if (double.parse(value) <= 0) {
                          return "Harga jual harus lebih dari 0";
                        }
                      } catch (e) {
                        return "Harga jual tidak valid";
                      }

                      return null;
                    },
                    enabledBorderColor: enabledBorderColor,
                    focusedBorderColor: focusedBorderColor,
                  ),

                  SizedBox(height: 2.5.h),

                  if (isStockFixed)
                    Row(
                      children: [
                        Expanded(
                          child: CustomTextFormField(
                            label: "Stok",
                            hint: "0",
                            keyboardType: TextInputType.number,
                            controller: stockController,
                            validator: isStockFixed
                                ? (value) {
                                    if (value == null || value.isEmpty) {
                                      return "Stok belum diisi";
                                    }

                                    try {
                                      if (!readOnly &&
                                          double.parse(value) <= 0) {
                                        if (isStockFixed) {
                                          return "Stok harus lebih dari 0";
                                        }
                                      }
                                    } catch (e) {
                                      return "Stok tidak valid";
                                    }

                                    return null;
                                  }
                                : null,
                            readOnly: readOnly,
                            onTapReadOnlyMessage: message,
                          ),
                        ),
                      ],
                    ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
