import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:intl/intl.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_date_picker_popup.dart';

class KwDateSelector extends StatefulWidget {
  const KwDateSelector({
    required this.onSelect,
    super.key,
    this.title,
    this.hintText,
    this.helperText,
    this.minHeight = standardHeight,
    this.suffixIcon,
    this.showError = false,
    this.enabled = true,
    this.readOnly = false,
    this.focusNode,
    this.textStyle,
    this.radius = 12,
    this.borderColor,
    this.dateFormat,
    this.initialValue,
    this.firstDate,
    this.lastDate,
    this.initialDate,
  });

  static const standardHeight = 48.0;

  final void Function(DateTime) onSelect;
  final String? title;
  final String? hintText;
  final String? helperText;
  final bool enabled;
  final bool readOnly;
  final bool showError;
  final FocusNode? focusNode;
  final double minHeight;
  final TextStyle? textStyle;
  final Widget? suffixIcon;
  final double radius;
  final Color? borderColor;
  final DateFormat? dateFormat;
  final DateTime? initialValue;
  final DateTime? firstDate;
  final DateTime? lastDate;
  final DateTime? initialDate;

  @override
  State<KwDateSelector> createState() => _KwDateSelectorState();
}

class _KwDateSelectorState extends State<KwDateSelector> {
  final _controller = TextEditingController();
  late FocusNode _focusNode;
  late DateFormat _dateFormat;

  @override
  initState() {
    _focusNode = widget.focusNode ?? FocusNode();
    _dateFormat = widget.dateFormat ?? DateFormat('M/d/y');

    super.initState();

    _focusNode.addListener(() => setState(() {}));
    if (widget.initialValue != null) {
      _controller.text = _dateFormat.format(widget.initialValue!);
    }
  }

  Color _helperTextColor() {
    if (widget.showError) return AppColors.statusError;

    if (!widget.enabled) return AppColors.grayDisable;

    return AppColors.bgColorDark;
  }

  Color _borderColor() {
    if (!widget.enabled) return AppColors.grayDisable;

    if (widget.showError) return AppColors.statusError;

    if (_focusNode.hasFocus) return AppColors.bgColorDark;

    return widget.borderColor ?? AppColors.grayStroke;
  }

  Future<void> _handleOnTap() async {
    final today = DateTime.now();

    final date = await KwDatePickerPopup.show(
      context: context,
      firstDate:
          widget.firstDate ?? today.subtract(const Duration(days: 3650)),
      lastDate: widget.lastDate ?? today.add(const Duration(days: 10)),
      initDate: widget.initialDate,
      currentDate: today,
    );

    if (date == null) return;

    _controller.text = _dateFormat.format(date);
    widget.onSelect(date);
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (widget.title != null)
            Padding(
              padding: const EdgeInsets.only(left: 16),
              child: Text(
                widget.title!,
                style: AppTextStyles.bodyTinyReg.copyWith(
                  color: widget.enabled
                      ? AppColors.blackGray
                      : AppColors.grayDisable,
                ),
              ),
            ),
          if (widget.title != null) const SizedBox(height: 4),
          Stack(
            children: [
              Container(
                alignment: Alignment.topCenter,
                constraints: BoxConstraints(
                  minHeight: widget.minHeight,
                ),
                decoration: BoxDecoration(
                  color: Colors.transparent,
                  borderRadius: BorderRadius.all(
                    Radius.circular(
                      widget.minHeight > KwDateSelector.standardHeight
                          ? widget.radius
                          : widget.minHeight / 2,
                    ),
                  ),
                  border: Border.all(
                    color: _borderColor(),
                  ),
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: TextFormField(
                        controller: _controller,
                        focusNode: _focusNode,
                        enabled: widget.enabled && !widget.readOnly,
                        onTap: _handleOnTap,
                        onTapOutside: (_) => _focusNode.unfocus(),
                        style: widget.textStyle ??
                            AppTextStyles.bodyMediumReg.copyWith(
                              color: !widget.enabled
                                  ? AppColors.grayDisable
                                  : null,
                            ),
                        cursorColor: Colors.transparent,
                        decoration: InputDecoration(
                          fillColor: Colors.transparent,
                          contentPadding: const EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 8,
                          ),
                          hintText: widget.hintText,
                          hintStyle: widget.textStyle ??
                              AppTextStyles.bodyMediumReg.copyWith(
                                color: widget.enabled
                                    ? AppColors.blackGray
                                    : AppColors.grayDisable,
                              ),
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                    if (widget.suffixIcon != null)
                      SizedBox(child: widget.suffixIcon!),
                  ],
                ),
              ),
              if (widget.minHeight > KwDateSelector.standardHeight)
                Positioned(
                  bottom: 12,
                  right: 12,
                  child: Assets.images.icons.textFieldNotches.svg(
                    height: 12,
                    width: 12,
                  ),
                ),
            ],
          ),
          if (widget.helperText != null &&
              (widget.helperText?.isNotEmpty ?? false)) ...[
            const SizedBox(height: 4),
            Row(
              children: [
                const Gap(16),
                Text(
                  widget.helperText!,
                  style: AppTextStyles.bodyTinyReg.copyWith(
                    height: 1,
                    color: _helperTextColor(),
                  ),
                ),
              ],
            )
          ]
        ],
      ),
    );
  }
}
