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

class ProfileDescriptionScreen extends StatefulWidget {
  final DoctorController controller;

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

  @override
  ProfileDescriptionScreenState createState() =>
      ProfileDescriptionScreenState();
}

class ProfileDescriptionScreenState extends State<ProfileDescriptionScreen> {
  final _descriptionController = TextEditingController();
  late final DoctorController _controller;
  bool _isEditing = false;
  final int _minDescriptionLength = 50; // Minimum description length
  final int _maxDescriptionLength = 500; // Maximum description length

  @override
  void initState() {
    super.initState();
    _controller = widget.controller;
    // Initialize with existing description if any
    _descriptionController.text =
        _controller.profileController.model.profileDescription ?? '';
    // Add listener to track editing state
    _descriptionController.addListener(_onDescriptionChanged);
  }

  @override
  void dispose() {
    _descriptionController.removeListener(_onDescriptionChanged);
    _descriptionController.dispose();
    super.dispose();
  }

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

  bool _validateDescription() {
    final description = _descriptionController.text.trim();

    if (description.isEmpty) {
      _showError('Please enter a profile description');
      return false;
    }

    if (description.length < _minDescriptionLength) {
      _showError(
          'Description must be at least $_minDescriptionLength characters long');
      return false;
    }

    if (description.length > _maxDescriptionLength) {
      _showError('Description cannot exceed $_maxDescriptionLength characters');
      return false;
    }

    return true;
  }

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

  bool validateAndProceed() {
    if (!_validateDescription()) {
      return false;
    }

    // Update the profile description in the controller
    _controller.updateProfileDescription(_descriptionController.text.trim());
    return true;
  }

  String _getCharacterCount() {
    return '${_descriptionController.text.length}/$_maxDescriptionLength';
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_isEditing) {
          // Show confirmation dialog if there are unsaved changes
          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('Profile Description'),
          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: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                'Tell us about yourself',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              const Text(
                'Write a brief description about your professional background, expertise, and approach to patient care.',
                style: TextStyle(
                  color: Colors.grey,
                  fontSize: 14,
                ),
              ),
              const SizedBox(height: 16),
              TextField(
                controller: _descriptionController,
                maxLines: 8,
                maxLength: _maxDescriptionLength,
                decoration: InputDecoration(
                  labelText: 'Profile Description',
                  hintText:
                      'Enter your professional background and expertise...',
                  border: const OutlineInputBorder(),
                  alignLabelWithHint: true,
                  counterText: _getCharacterCount(),
                ),
                textInputAction: TextInputAction.newline,
                // keyboardType: TextInputAction.multiline,
              ),
              const SizedBox(height: 8),
              Text(
                'Minimum $_minDescriptionLength characters required',
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 12,
                ),
              ),
            ],
          ),
        ),
        bottomNavigationBar: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TextButton(
                onPressed: () {
                  // Save draft functionality can be added here
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('Draft saved')),
                  );
                },
                child: const Text('SAVE DRAFT'),
              ),
              ElevatedButton(
                onPressed: () {
                  {
                    Navigator.pushNamed(
                      context,
                      RouteNames.experienceScreen,
                      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,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
