import 'package:flutter/material.dart';
import 'package:medora/controllers/doctor_controller.dart';
import 'package:medora/route/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 _formKey = GlobalKey<FormState>();
  late DoctorController? _controller;
  late TextEditingController _descriptionController;
  final int _minDescriptionLength = 5;
  final int _maxDescriptionLength = 500;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller ?? DoctorController();
    _descriptionController = TextEditingController(
        text: _controller?.model.profileDescription ?? '');
    _descriptionController.addListener(_onDescriptionChanged);
  }

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

  void _onDescriptionChanged() {
    setState(() {});
  }

  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 (_formKey.currentState!.validate() && _validateDescription()) {
      _controller?.updateProfileDescription(_descriptionController.text.trim());
      return true;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
            onPressed: () {
              if (_validateAndProceed()) {
                Navigator.pushNamed(
                  context,
                  RouteNames.experienceScreen,
                  arguments: _controller,
                );
              }
            },
            icon: const Icon(Icons.arrow_forward),
          ),
        ],
        title: const Text('Profile Description'),
      ),
      body: Form(
        key: _formKey,
        child: 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: 16),
              Container(
                padding: const EdgeInsets.all(16.0),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.5),
                      blurRadius: 10,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    TextFormField(
                      controller: _descriptionController,
                      onChanged: (value) {
                        widget.controller!.updateProfileDescription(value);
                        _onDescriptionChanged();
                      },
                      maxLength: _maxDescriptionLength,
                      maxLines: 8,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Profile description is required';
                        }
                        if (value.length < _minDescriptionLength) {
                          return 'Description must be at least $_minDescriptionLength characters';
                        }
                        if (value.length > _maxDescriptionLength) {
                          return 'Description cannot exceed $_maxDescriptionLength characters';
                        }
                        return null;
                      },
                      decoration: InputDecoration(
                        labelText: 'Profile Description',
                        filled: true,
                        fillColor: Colors.grey[100],
                        alignLabelWithHint: true,
                        // prefixIcon:
                        //     const Icon(Icons.description, color: Colors.blue),
                        contentPadding: const EdgeInsets.symmetric(
                            vertical: 20, horizontal: 12),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide:
                              BorderSide(color: Colors.grey.shade300, width: 1),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide:
                              const BorderSide(color: Colors.blue, width: 1.5),
                        ),
                        errorBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide:
                              const BorderSide(color: Colors.red, width: 1.5),
                        ),
                        focusedErrorBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide:
                              const BorderSide(color: Colors.red, width: 1.5),
                        ),
                        helperText:
                            'Minimum $_minDescriptionLength characters required',
                        counterText:
                            '${_descriptionController.text.length}/$_maxDescriptionLength',
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
