import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../services/app_provider.dart';
import '../../services/api_service.dart';
import '../../widgets/glass_card.dart';

class ChangePasswordScreen extends StatefulWidget {
  const ChangePasswordScreen({super.key});

  @override
  State<ChangePasswordScreen> createState() => _ChangePasswordScreenState();
}

class _ChangePasswordScreenState extends State<ChangePasswordScreen> {
  final _currentCtrl = TextEditingController();
  final _newCtrl = TextEditingController();
  final _confirmCtrl = TextEditingController();
  bool _saving = false;
  String? _message;
  bool _isError = false;
  bool _obscureCurrent = true;
  bool _obscureNew = true;

  Future<void> _change() async {
    if (_newCtrl.text != _confirmCtrl.text) {
      setState(() { _message = 'Passwords do not match'; _isError = true; });
      return;
    }
    if (_newCtrl.text.length < 8) {
      setState(() { _message = 'Password must be at least 8 characters'; _isError = true; });
      return;
    }
    setState(() { _saving = true; _message = null; });
    try {
      await context.read<AppProvider>().api.changePassword(
        currentPassword: _currentCtrl.text,
        newPassword: _newCtrl.text,
      );
      setState(() { _message = 'Password updated'; _isError = false; });
      _currentCtrl.clear();
      _newCtrl.clear();
      _confirmCtrl.clear();
    } on ApiException catch (e) {
      setState(() { _message = e.message; _isError = true; });
    } catch (_) {
      setState(() { _message = 'Failed to change password'; _isError = true; });
    }
    setState(() => _saving = false);
  }

  @override
  void dispose() {
    _currentCtrl.dispose();
    _newCtrl.dispose();
    _confirmCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.navy,
      appBar: AppBar(
        title: Text('Change Password', style: AppTypography.headingLg.copyWith(color: Colors.white)),
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.fromLTRB(16, 16, 16, 40),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _field('Current Password', _currentCtrl, obscure: _obscureCurrent,
                onToggle: () => setState(() => _obscureCurrent = !_obscureCurrent)),
            const SizedBox(height: 16),
            _field('New Password', _newCtrl, obscure: _obscureNew,
                onToggle: () => setState(() => _obscureNew = !_obscureNew)),
            const SizedBox(height: 16),
            _field('Confirm New Password', _confirmCtrl, obscure: _obscureNew),
            const SizedBox(height: 24),

            if (_message != null)
              Padding(
                padding: const EdgeInsets.only(bottom: 16),
                child: Text(_message!,
                    style: AppTypography.bodyMd.copyWith(color: _isError ? AppColors.error : AppColors.success)),
              ),

            GestureDetector(
              onTap: _saving ? null : _change,
              child: Container(
                width: double.infinity,
                height: 52,
                decoration: BoxDecoration(
                  gradient: AppColors.blueGradient,
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Center(
                  child: _saving
                      ? const SizedBox(width: 22, height: 22, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                      : Text('Update Password', style: AppTypography.button.copyWith(color: Colors.white)),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _field(String label, TextEditingController ctrl, {bool obscure = false, VoidCallback? onToggle}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
        const SizedBox(height: 8),
        GlassCard(
          padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),
          child: TextField(
            controller: ctrl,
            obscureText: obscure,
            style: AppTypography.bodyMd.copyWith(color: Colors.white),
            decoration: InputDecoration(
              border: InputBorder.none,
              suffixIcon: onToggle != null
                  ? IconButton(
                      icon: Icon(obscure ? Icons.visibility_off_rounded : Icons.visibility_rounded,
                          color: AppColors.textMuted, size: 20),
                      onPressed: onToggle,
                    )
                  : null,
            ),
          ),
        ),
      ],
    );
  }
}
