import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:kmobile/l10n/app_localizations.dart';
import 'package:intl/intl.dart';

class DailyLimitScreen extends StatefulWidget {
  const DailyLimitScreen({super.key});
  @override
  State<DailyLimitScreen> createState() => _DailyLimitScreenState();
}

class _DailyLimitScreenState extends State<DailyLimitScreen> {
  double? _currentLimit;
  final _limitController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // Now just taking null, but for real time limit will be fetched using API call
    _currentLimit = null;
  }

  @override
  void dispose() {
    _limitController.dispose();
    super.dispose();
  }

  Future<void> _showAddOrEditLimitDialog() async {
    _limitController.text = _currentLimit?.toStringAsFixed(0) ?? '';
    final newLimit = await showDialog<double>(
      context: context,
      builder: (context) {
        final localizations = AppLocalizations.of(context);
        return AlertDialog(
          title: Text(
            _currentLimit == null
                ? localizations.addLimit
                : localizations.editLimit,
          ),
          content: TextField(
            controller: _limitController,
            autofocus: true,
            keyboardType: TextInputType.number,
            inputFormatters: [
              FilteringTextInputFormatter.allow(RegExp(r'^\d+')),
            ],
            decoration: InputDecoration(
              labelText: localizations.limitAmount,
              prefixText: '₹',
              border: const OutlineInputBorder(),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text(localizations.cancel),
            ),
            ElevatedButton(
              onPressed: () {
                final value = double.tryParse(_limitController.text);
                if (value != null && value > 0) {
                  Navigator.of(context).pop(value);
                }
              },
              child: Text(localizations.save),
            ),
          ],
        );
      },
    );
    if (newLimit != null) {
      setState(() {
        _currentLimit = newLimit;
      });
    }
  }

  void _removeLimit() {
    setState(() {
      _currentLimit = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);
    final formatCurrency = NumberFormat.currency(locale: 'en_IN', symbol: '₹');
    return Scaffold(
      appBar: AppBar(
        title: Text(localizations.dailylimit),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                localizations.currentDailyLimit,
                style: theme.textTheme.headlineSmall?.copyWith(
                  color: theme.colorScheme.onSurface.withOpacity(0.7),
                ),
              ),
              const SizedBox(height: 16),
              Text(
                _currentLimit == null
                    ? localizations.noLimitSet
                    : formatCurrency.format(_currentLimit),
                style: theme.textTheme.headlineMedium?.copyWith(
                  fontWeight: FontWeight.bold,
                  color: _currentLimit == null
                      ? theme.colorScheme.secondary
                      : theme.colorScheme.primary,
                ),
              ),
              const SizedBox(height: 48),
              if (_currentLimit == null)
                ElevatedButton.icon(
                  onPressed: _showAddOrEditLimitDialog,
                  icon: const Icon(Icons.add_circle_outline),
                  label: Text(localizations.addLimit),
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 24, vertical: 12),
                    textStyle: theme.textTheme.titleMedium,
                  ),
                )
              else
                Column(
                  children: [
                    ElevatedButton.icon(
                      onPressed: _showAddOrEditLimitDialog,
                      icon: const Icon(Icons.edit_outlined),
                      label: Text(localizations.editLimit),
                      style: ElevatedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 24, vertical: 12),
                        textStyle: theme.textTheme.titleMedium,
                      ),
                    ),
                    const SizedBox(height: 16),
                    TextButton.icon(
                      onPressed: _removeLimit,
                      icon: const Icon(Icons.remove_circle_outline),
                      label: Text(localizations.removeLimit),
                      style: TextButton.styleFrom(
                        foregroundColor: theme.colorScheme.error,
                      ),
                    ),
                  ],
                ),
            ],
          ),
        ),
      ),
    );
  }
}
