import 'package:flutter/material.dart';
import '../../controllers/doctor_controller.dart';
import '../../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 TextEditingController _achievementController = TextEditingController();
  late final DoctorController _controller;
  late List<String> achievements;
  bool _isEditing = false;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller;
    _achievementController.addListener(_onFieldChanged);
    // Create a new modifiable list from the controller's achievements
    achievements = List<String>.from(_controller.model.achievements);
  }

  void _addAchievement() {
    final achievement = _achievementController.text.trim();
    if (achievement.isNotEmpty) {
      setState(() {
        achievements.add(achievement);
        _isEditing = true;
      });
      _controller.updateAchievements(List<String>.from(achievements));
      _achievementController.clear();
    } else {
      _showError('Please enter an achievement');
    }
  }

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

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

  void _onFieldChanged() {
    setState(() {
      _isEditing = true;
    });
  }

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

  bool _validateAchievements() {
    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(
          title: const Text('Achievements'),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              if (_isEditing) {
                showDialog(
                  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),
                        child: const Text('CANCEL'),
                      ),
                      TextButton(
                        onPressed: () {
                          Navigator.pop(context);
                          Navigator.pop(context);
                        },
                        child: const Text('DISCARD'),
                      ),
                    ],
                  ),
                );
              } else {
                Navigator.pop(context);
              }
            },
          ),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Padding(
              padding: EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Add Your Achievements',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 8),
                  Text(
                    'List your professional accomplishments, certifications, and awards',
                    style: TextStyle(
                      color: Colors.grey,
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: TextField(
                controller: _achievementController,
                decoration: InputDecoration(
                  hintText: 'Enter your achievement',
                  suffixIcon: IconButton(
                    icon: const Icon(Icons.add),
                    onPressed: _addAchievement,
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                onSubmitted: (_) => _addAchievement(),
              ),
            ),
            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),
                      ),
                    ),
                  );
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  TextButton(
                    onPressed: () {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('Draft saved')),
                      );
                    },
                    child: const Text('SAVE DRAFT'),
                  ),
                  ElevatedButton(
                    onPressed: () {
                      if (_validateAchievements()) {
                        Navigator.pushNamed(
                          context,
                          RouteNames.digitalSignatureScreeen,
                          arguments: _controller,
                        );
                      }
                    },
                    style: ElevatedButton.styleFrom(
                      shape: const CircleBorder(),
                      padding: const EdgeInsets.all(24),
                      backgroundColor: const Color(0xFF5BC0DE),
                    ),
                    child: const Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
