import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'base_field.dart';

class CurrencyField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final String currencySymbol;
  final int decimalDigits;
  final List<Map<String, String>>
      currencyOptions; // [{code: 'INR', symbol: 'â¹', name: 'India (INR)'}]

  CurrencyField({
    required this.fieldKey,
    required this.label,
    this.hint = '',
    this.isRequired = false,
    this.currencySymbol = 'â¹',
    this.decimalDigits = 2,
    List<Map<String, String>>? currencyOptions,
  }) : currencyOptions = currencyOptions ??
            const [
              {'code': 'INR', 'symbol': 'â¹', 'name': 'India (INR)'},
              {'code': 'USD', 'symbol': '\$', 'name': 'USA (USD)'},
              {'code': 'EUR', 'symbol': '€', 'name': 'Euro (EUR)'},
              {'code': 'GBP', 'symbol': '£', 'name': 'UK (GBP)'},
              {'code': 'AUD', 'symbol': 'A\$', 'name': 'Australia (AUD)'},
              {'code': 'CAD', 'symbol': 'C\$', 'name': 'Canada (CAD)'},
              {'code': 'CHF', 'symbol': 'CHF', 'name': 'Switzerland (CHF)'},
              {'code': 'CNY', 'symbol': 'Â¥', 'name': 'China (CNY)'},
              {'code': 'HKD', 'symbol': 'HK\$', 'name': 'Hong Kong (HKD)'},
              {'code': 'NZD', 'symbol': 'NZ\$', 'name': 'New Zealand (NZD)'},
              {'code': 'SGD', 'symbol': 'S\$', 'name': 'Singapore (SGD)'},
              {'code': 'ZAR', 'symbol': 'R', 'name': 'South Africa (ZAR)'},
              {'code': 'SEK', 'symbol': 'kr', 'name': 'Sweden (SEK)'},
              {'code': 'NOK', 'symbol': 'kr', 'name': 'Norway (NOK)'},
              {'code': 'MXN', 'symbol': '\$', 'name': 'Mexico (MXN)'},
              {'code': 'BRL', 'symbol': 'R\$', 'name': 'Brazil (BRL)'},
              {'code': 'RUB', 'symbol': '₽', 'name': 'Russia (RUB)'},
              {'code': 'KRW', 'symbol': '₩', 'name': 'South Korea (KRW)'},
              {'code': 'TRY', 'symbol': '₺', 'name': 'Turkey (TRY)'},
              {'code': 'JPY', 'symbol': '¥', 'name': 'Japan (JPY)'},
            ];

  @override
  String? Function(String?)? get validator => (value) {
        final v = value?.trim() ?? '';
        if (isRequired && v.isEmpty) return 'Required';
        if (v.isNotEmpty && double.tryParse(v.replaceAll(',', '')) == null) {
          return 'Invalid amount';
        }
        return null;
      };

  @override
  Widget buildField({
    required TextEditingController controller,
    required ColorScheme colorScheme,
    VoidCallback? onChanged,
  }) {
    return _CurrencyFieldWidget(
      controller: controller,
      colorScheme: colorScheme,
      label: label,
      hint: hint.isEmpty ? '0.${'0' * decimalDigits}' : hint,
      isRequired: isRequired,
      decimalDigits: decimalDigits,
      defaultSymbol: currencySymbol,
      options: currencyOptions,
      onChanged: onChanged,
      validator: validator,
    );
  }
}

class _CurrencyFieldWidget extends StatefulWidget {
  final TextEditingController controller;
  final ColorScheme colorScheme;
  final String label;
  final String hint;
  final bool isRequired;
  final int decimalDigits;
  final String defaultSymbol;
  final List<Map<String, String>> options;
  final VoidCallback? onChanged;
  final String? Function(String?)? validator;

  const _CurrencyFieldWidget({
    required this.controller,
    required this.colorScheme,
    required this.label,
    required this.hint,
    required this.isRequired,
    required this.decimalDigits,
    required this.defaultSymbol,
    required this.options,
    this.onChanged,
    this.validator,
  });

  @override
  State<_CurrencyFieldWidget> createState() => _CurrencyFieldWidgetState();
}

class _CurrencyFieldWidgetState extends State<_CurrencyFieldWidget> {
  late String _selectedSymbol;

  @override
  void initState() {
    super.initState();
    _selectedSymbol = widget.defaultSymbol;
  }

  @override
  Widget build(BuildContext context) {
    final cs = widget.colorScheme;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(widget.label,
            style: TextStyle(color: cs.onSurface, fontWeight: FontWeight.w600)),
        const SizedBox(height: 8),
        Row(
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8),
              decoration: BoxDecoration(
                color: cs.surface,
                borderRadius: BorderRadius.circular(10),
                border: Border.all(color: cs.outlineVariant.withOpacity(0.4)),
              ),
              child: DropdownButtonHideUnderline(
                child: DropdownButton<String>(
                  value: _selectedSymbol,
                  items: widget.options
                      .map((o) => DropdownMenuItem<String>(
                            value: o['symbol'],
                            child: Row(
                              children: [
                                Text(o['symbol'] ?? ''),
                                const SizedBox(width: 8),
                                Text(
                                  o['code'] ?? '',
                                  style: TextStyle(
                                      color: cs.onSurface.withOpacity(0.7),
                                      fontSize: 12),
                                ),
                              ],
                            ),
                          ))
                      .toList(),
                  onChanged: (val) {
                    if (val == null) return;
                    setState(() => _selectedSymbol = val);
                    widget.onChanged?.call();
                  },
                ),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: TextFormField(
                controller: widget.controller,
                keyboardType:
                    const TextInputType.numberWithOptions(decimal: true),
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'[0-9.,]')),
                ],
                decoration: InputDecoration(
                  hintText: widget.hint,
                  prefixText: '$_selectedSymbol ',
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12)),
                  filled: true,
                ),
                validator: widget.validator,
                onChanged: (_) => widget.onChanged?.call(),
              ),
            ),
          ],
        ),
      ],
    );
  }
}
