import 'package:flutter/material.dart';
import 'package:medora/controllers/doctor_controller.dart';
import 'package:medora/route/route_names.dart';

class AchievementsScreen extends StatefulWidget {
  final DoctorController controller;

  const AchievementsScreen({
    super.key,
    required this.controller,
  });

  @override
  State<AchievementsScreen> createState() => _AchievementsScreenState();
}

class _AchievementsScreenState extends State<AchievementsScreen> {
  final _formKey = GlobalKey<FormState>();
  late DoctorController _controller;
  late TextEditingController _achievementController;
  late List<String> achievements;
  bool _isEditing = false;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller;
    _controller.model.achievements ??= [];
    _achievementController = TextEditingController();
    achievements = List<String>.from(_controller.model.achievements ?? []);

    // if (achievements.isNotEmpty) {
    //   _achievementController.text = achievements.join(', ');
    // }
    // _achievementController.addListener(_onFieldChanged);
  }

  void _onFieldChanged() {
    setState(() {
      _isEditing = _achievementController.text.isNotEmpty;
    });
  }

  bool _validateAchievement(String value) {
    if (value.isEmpty) {
      _showError('Please enter an achievement');
      return false;
    }

    if (achievements.any((a) => a.toLowerCase() == value.toLowerCase())) {
      _showError('This achievement has already been added');
      return false;
    }

    if (value.length < 3) {
      _showError('Achievement must be at least 3 characters long');
      return false;
    }

    return true;
  }

  void _addAchievement() {
    if (_formKey.currentState!.validate()) {
      final achievement = _achievementController.text.trim();
      if (_validateAchievement(achievement)) {
        setState(() {
          achievements.add(achievement);
          _isEditing = true;
        });
        _controller.updateAchievements(List<String>.from(achievements));
        _achievementController.clear();
      }
    }
  }

  void _addAchievementBottomSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) => Padding(
        padding: EdgeInsets.only(
          bottom: MediaQuery.of(context).viewInsets.bottom,
        ),
        child: Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text(
                'Add Achievement',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _achievementController,
                decoration: InputDecoration(
                  hintText: 'Enter your achievement',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
              ),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: () {
                  final achievement = _achievementController.text.trim();
                  if (_validateAchievement(achievement)) {
                    setState(() {
                      achievements.add(achievement);
                      _isEditing = true;
                    });
                    _controller
                        .updateAchievements(List<String>.from(achievements));
                    _achievementController.clear();
                    Navigator.pop(context);
                  }
                },
                child: const Text('Add'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _removeAchievement(int index) {
    setState(() {
      achievements.removeAt(index);
      _isEditing = true;
    });
    _controller.updateAchievements(List<String>.from(achievements));
  }

  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  bool _validateBeforeNextPage() {
    if (achievements.isEmpty) {
      _showError('Please add at least one achievement');
      return false;
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_isEditing) {
          final shouldPop = await showDialog<bool>(
            context: context,
            builder: (context) => AlertDialog(
              title: const Text('Discard Changes?'),
              content: const Text(
                  'You have unsaved changes. Are you sure you want to go back?'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: const Text('CANCEL'),
                ),
                TextButton(
                  onPressed: () => Navigator.pop(context, true),
                  child: const Text('DISCARD'),
                ),
              ],
            ),
          );
          return shouldPop ?? false;
        }
        return true;
      },
      child: Scaffold(
        appBar: AppBar(
          actions: [
            IconButton(
              onPressed: () {
                if (_validateBeforeNextPage()) {
                  Navigator.pushNamed(
                      context, RouteNames.digitalSignatureScreeen,
                      arguments: _controller);
                }
              },
              icon: const Icon(Icons.arrow_forward),
            ),
          ],
          title: const Text('Achievements'),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Padding(
              padding: EdgeInsets.all(16.0),
              child: Text(
                'Add Your Achievements',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: achievements.length,
                padding: const EdgeInsets.all(16),
                itemBuilder: (context, index) {
                  return Card(
                    elevation: 2,
                    margin: const EdgeInsets.only(bottom: 8),
                    child: ListTile(
                      leading: CircleAvatar(
                        backgroundColor: const Color(0xFF5BC0DE),
                        child: Text('${index + 1}'),
                      ),
                      title: Text(achievements[index]),
                      trailing: IconButton(
                        icon: const Icon(Icons.delete, color: Colors.red),
                        onPressed: () => _removeAchievement(index),
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _addAchievementBottomSheet,
          backgroundColor: const Color(0xFF4FB6D8),
          child: const Icon(Icons.add),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _achievementController.removeListener(_onFieldChanged);
    _achievementController.dispose();
    super.dispose();
  }
}
