import 'dart:math';

import 'package:flutter/material.dart';

import '../../../shared/widgets/inputs/modern_text_field.dart';
import 'base_field.dart';

/// Generic Captcha field: shows generated code and asks user to type it
class CaptchaField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final int length;

  CaptchaField({
    required this.fieldKey,
    required this.label,
    this.hint = 'Enter CAPTCHA',
    this.isRequired = true,
    this.length = 6,
  });

  @override
  String? Function(String?)? get validator => (value) {
        if (isRequired && (value == null || value.isEmpty)) {
          return '$label is required';
        }
        return null;
      };

  @override
  Widget buildField({
    required TextEditingController controller,
    required ColorScheme colorScheme,
    VoidCallback? onChanged,
  }) {
    return _CaptchaFieldWidget(
      key: ValueKey(fieldKey),
      label: label,
      hint: hint,
      length: length,
      colorScheme: colorScheme,
      controller: controller,
      baseValidator: validator,
      onChanged: onChanged,
    );
  }

  String _generateCaptcha(int length) {
    final random = Random();
    const chars =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    return String.fromCharCodes(Iterable.generate(
      length,
      (_) => chars.codeUnitAt(random.nextInt(chars.length)),
    ));
  }
}

class _CaptchaFieldWidget extends StatefulWidget {
  final String label;
  final String hint;
  final int length;
  final ColorScheme colorScheme;
  final TextEditingController controller;
  final String? Function(String?)? baseValidator;
  final VoidCallback? onChanged;

  const _CaptchaFieldWidget({
    super.key,
    required this.label,
    required this.hint,
    required this.length,
    required this.colorScheme,
    required this.controller,
    required this.baseValidator,
    required this.onChanged,
  });

  @override
  State<_CaptchaFieldWidget> createState() => _CaptchaFieldWidgetState();
}

class _CaptchaFieldWidgetState extends State<_CaptchaFieldWidget> {
  late String _captcha;

  @override
  void initState() {
    super.initState();
    _captcha = _generateCaptcha(widget.length);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
          decoration: BoxDecoration(
            color: widget.colorScheme.primaryContainer.withOpacity(0.2),
            borderRadius: BorderRadius.circular(12),
            border:
                Border.all(color: widget.colorScheme.primary.withOpacity(0.2)),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                _captcha,
                style: TextStyle(
                  color: widget.colorScheme.primary,
                  fontSize: 20,
                  fontWeight: FontWeight.w700,
                  letterSpacing: 3,
                ),
              ),
              IconButton(
                tooltip: 'Refresh',
                onPressed: () {
                  setState(() {
                    _captcha = _generateCaptcha(widget.length);
                  });
                  if (widget.onChanged != null) widget.onChanged!();
                },
                icon: Icon(Icons.refresh_rounded,
                    color: widget.colorScheme.primary),
              ),
            ],
          ),
        ),
        const SizedBox(height: 12),
        ModernTextField(
          controller: widget.controller,
          hint: widget.hint,
          validator: (value) {
            final base = widget.baseValidator;
            final err = base != null ? base(value) : null;
            if (err != null) return err;
            if ((value ?? '').trim() != _captcha) {
              return 'CAPTCHA does not match';
            }
            return null;
          },
          onChanged:
              widget.onChanged != null ? (_) => widget.onChanged!() : null,
        ),
      ],
    );
  }

  String _generateCaptcha(int length) {
    final random = Random();
    const chars =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    return String.fromCharCodes(Iterable.generate(
      length,
      (_) => chars.codeUnitAt(random.nextInt(chars.length)),
    ));
  }
}
