import 'package:flutter/material.dart';

typedef VRadioCellChangeCallback<T> = void Function(T? value, bool isChecked);

class VRadioCell<T> extends StatefulWidget {
  final String label;
  final T? value;
  final bool isChecked;
  final bool isDisabled;
  final VRadioCellChangeCallback<T>? onChanged;

  const VRadioCell({
    super.key,
    required this.label,
    required this.value,
    required this.isChecked,
    required this.isDisabled,
    this.onChanged,
  });

  @override
  State<StatefulWidget> createState() => _VRadioCellState<T>();
}

class _VRadioCellState<T> extends State<VRadioCell<T>> {
  static const _horizontalPadding = 24.0;
  late bool _isChecked;

  static const _height = 56.0;

  @override
  void initState() {
    _isChecked = widget.isChecked;
    super.initState();
  }

  @override
  void didUpdateWidget(covariant VRadioCell<T> oldWidget) {
    super.didUpdateWidget(oldWidget);
    setState(() {
      _isChecked = widget.isChecked;
    });
  }

  @override
  Widget build(BuildContext context) {
    final iconWidget = _CheckStatusIcon(
      isChecked: _isChecked,
      isDisabled: widget.isDisabled,
    );
    final labelWidget = Text(
      widget.label,
      style: TextStyle(
        color: _isChecked ? Theme.of(context).primaryColor : Colors.black87,
        fontSize: 20,
      ),
    );
    return Material(
      child: Ink(
        child: InkWell(
          onTap: widget.isDisabled ? null : _onClick,
          child: Container(
            height: _height,
            padding: const EdgeInsets.symmetric(horizontal: _horizontalPadding),
            color: _isChecked ? Theme.of(context).secondaryHeaderColor : null,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                labelWidget,
                iconWidget,
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _onClick() {
    setState(() {
      _isChecked = !_isChecked;
      widget.onChanged?.call(widget.value, _isChecked);
    });
  }
}

class _CheckStatusIcon extends StatelessWidget {
  final bool isChecked;
  final bool isDisabled;

  const _CheckStatusIcon({
    required this.isChecked,
    required this.isDisabled,
  });

  @override
  Widget build(BuildContext context) {
    if (isChecked) {
      return Icon(
        Icons.check_outlined,
        color: Theme.of(context).primaryColor,
        size: 24,
      );
    } else {
      return const Icon(
        Icons.radio_button_off_rounded,
        color: Colors.grey,
        size: 24,
      );
    }
  }
}
