import 'dart:io';

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/utils/currency_format.dart';
import 'package:niogu_app/core/utils/extension_format.dart';
import 'package:niogu_app/core/enums/item_type.dart';
import 'package:niogu_app/features/stock_in/presentation/widgets/counter_button.dart';
import 'package:niogu_app/features/stock_in/domain/entities/stock_in.dart';
import 'package:sizer/sizer.dart';

class PurchaseItemCard extends StatelessWidget {
  final SelectedItem item;
  final TextEditingController purchasePriceController;
  final void Function(String)? onChanged;
  final VoidCallback? onDecrementTap;
  final VoidCallback? onIncrementTap;
  final VoidCallback onEditPressed;
  final VoidCallback onDeletePressed;
  const PurchaseItemCard({
    super.key,
    required this.item,
    required this.purchasePriceController,
    required this.onChanged,
    required this.onDecrementTap,
    required this.onIncrementTap,
    required this.onEditPressed,
    required this.onDeletePressed,
  });

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

    final double sellingPrice = item.sellingPrice;

    final double purchasePrice =
        double.tryParse(purchasePriceController.text.trim()) ?? 0.0;

    final validatePurchasePrice = switch (item.itemType) {
      ItemType.product_variant =>
        double.tryParse(purchasePriceController.text.trim()) != null &&
            purchasePrice > 0 &&
            sellingPrice > purchasePrice,
      ItemType.raw_material =>
        double.tryParse(purchasePriceController.text.trim()) != null &&
            purchasePrice > 0,
    };

    final String path =
        item.localImagePath != null && item.localImagePath!.isNotEmpty
        ? item.localImagePath!
        : 'image not found';

    final File imageFile = File(path);

    final bool imageFileExists = imageFile.existsSync();

    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(2.5.w),
        border: Border.all(color: Colors.grey.shade200),
        boxShadow: [
          BoxShadow(color: Colors.black.withOpacity(0.02), blurRadius: 5),
        ],
      ),
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.all(3.w),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 18.w,
                  height: 18.w,
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey.shade200, width: 1.5),
                    borderRadius: BorderRadius.circular(2.5.w),
                  ),
                  child: imageFileExists
                      ? ClipRRect(
                          borderRadius: BorderRadius.circular(2.5.w),
                          child: 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(
                          item.itemType == ItemType.product_variant
                              ? Icons.image_outlined
                              : Icons.inventory_2_rounded,
                          size: 8.w,
                          color: item.itemType == ItemType.product_variant
                              ? Colors.grey
                              : Colors.grey[400],
                        ),
                ),
                SizedBox(width: 3.w),
                Expanded(
                  flex: 3,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        item.name,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: isTablet
                              ? (AppFontSize.medium - 1.25).sp
                              : (AppFontSize.small - 1.25).sp,
                        ),
                      ),
                      if (item.variantName != null &&
                          item.variantName!.isNotEmpty) ...[
                        SizedBox(height: 0.5.h),
                        Text(
                          "(${item.variantName})",
                          style: TextStyle(
                            color: Colors.grey[600],
                            fontWeight: FontWeight.bold,
                            fontSize: isTablet
                                ? (AppFontSize.medium - 1.25).sp
                                : (AppFontSize.small - 1.25).sp,
                          ),
                        ),
                      ],
                      SizedBox(height: 0.5.h),
                      Text(
                        "Sisa Stok: ${item.remainingStock.toStringWithoutTrailingZero()} ${item.unit}",
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: isTablet
                              ? (AppFontSize.medium - 1.25).sp
                              : (AppFontSize.small - 1.25).sp,
                        ),
                      ),

                      if (item.itemType == ItemType.product_variant) ...[
                        SizedBox(height: 0.5.h),
                        Text(
                          "Harga Jual: ${CurrencyFormat.formatToIdr(item.sellingPrice, 0)}",
                          style: TextStyle(
                            color: Colors.grey[600],
                            fontSize: isTablet
                                ? (AppFontSize.medium - 1.25).sp
                                : (AppFontSize.small - 1.25).sp,
                          ),
                        ),
                      ],
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 0.5.h),
                  child: IconButton(
                    onPressed: onEditPressed,
                    icon: Icon(
                      Icons.edit_note_rounded,
                      color: Colors.grey,
                      size: 5.w,
                    ),
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                    style: IconButton.styleFrom(
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                  ),
                ),

                SizedBox(width: 2.w),

                Container(
                  margin: EdgeInsets.only(top: 0.5.h),
                  child: IconButton(
                    onPressed: onDeletePressed,
                    icon: Icon(
                      Icons.delete_outline,
                      color: Colors.red,
                      size: 5.w,
                    ),
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                    style: IconButton.styleFrom(
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Divider(height: 1, color: Colors.grey[100]),
          Padding(
            padding: EdgeInsets.all(3.w),
            child: Row(
              children: [
                Expanded(
                  flex: 3,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "Jumlah Pembelian",
                        style: TextStyle(
                          fontSize: isTablet
                              ? (AppFontSize.medium - 1.25).sp
                              : (AppFontSize.small - 1.25).sp,
                          color: Colors.grey,
                        ),
                      ),
                      SizedBox(height: 0.5.h),
                      Container(
                        height: 5.h,
                        decoration: BoxDecoration(
                          color: Colors.grey[50],
                          borderRadius: BorderRadius.circular(2.w),
                          border: Border.all(color: Colors.grey.shade300),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            CounterButton(
                              icon: Icons.remove,
                              onTap: item.quantity > 1 ? onDecrementTap : null,
                            ),
                            Row(
                              children: [
                                Text(
                                  item.quantity.toStringWithoutTrailingZero(),
                                  style: TextStyle(
                                    fontSize: isTablet
                                        ? (AppFontSize.medium - 1.25).sp
                                        : (AppFontSize.small - 1.25).sp,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                SizedBox(width: 1.w),
                                Text(
                                  item.unit,
                                  style: TextStyle(
                                    fontSize: isTablet
                                        ? (AppFontSize.medium - 1.25).sp
                                        : (AppFontSize.small - 1.25).sp,
                                    color: Colors.grey,
                                  ),
                                ),
                              ],
                            ),
                            CounterButton(
                              icon: Icons.add,
                              onTap: onIncrementTap,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),

                SizedBox(width: 3.w),

                Expanded(
                  flex: 3,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "Harga Beli / Satuan",
                        style: TextStyle(
                          fontSize: isTablet
                              ? (AppFontSize.medium - 1.25).sp
                              : (AppFontSize.small - 1.25).sp,
                          color: Colors.grey,
                        ),
                      ),
                      SizedBox(height: 0.5.h),

                      SizedBox(
                        height: 5.h,
                        child: TextFormField(
                          keyboardType: TextInputType.number,
                          controller: purchasePriceController,
                          onChanged: onChanged,
                          style: TextStyle(
                            fontSize: isTablet
                                ? (AppFontSize.medium - 1.25).sp
                                : (AppFontSize.small - 1.25).sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.black87,
                          ),
                          decoration: InputDecoration(
                            prefixText: "Rp ",
                            prefixStyle: TextStyle(
                              color: Colors.grey[600],
                              fontSize: isTablet
                                  ? (AppFontSize.medium - 1.25).sp
                                  : (AppFontSize.small - 1.25).sp,
                            ),
                            contentPadding: EdgeInsets.symmetric(
                              horizontal: 3.w,
                              vertical: 0,
                            ),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(2.w),
                              borderSide: BorderSide(
                                color: Colors.grey.shade300,
                              ),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(2.w),
                              borderSide: BorderSide(
                                color: validatePurchasePrice
                                    ? Colors.grey.shade300
                                    : Colors.red,
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(2.w),
                              borderSide: BorderSide(
                                color: validatePurchasePrice
                                    ? AppColor.primaryColor
                                    : Colors.red,
                              ),
                            ),
                            filled: true,
                            fillColor: Colors.white,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 3.w, vertical: 1.h),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              borderRadius: BorderRadius.vertical(
                bottom: Radius.circular(2.5.w),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  "Subtotal",
                  style: TextStyle(
                    fontSize: isTablet
                        ? (AppFontSize.medium - 1.25).sp
                        : (AppFontSize.small - 1.25).sp,
                    color: Colors.grey[700],
                  ),
                ),
                Text(
                  CurrencyFormat.formatToIdr(purchasePrice * item.quantity, 0),
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: isTablet
                        ? (AppFontSize.medium - 1.25).sp
                        : (AppFontSize.small - 1.25).sp,
                    color: AppColor.primaryColor,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
