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

class ExperienceScreen extends StatefulWidget {
  final DoctorController controller;

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

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

class ExperienceScreenState extends State<ExperienceScreen> {
  String? _selectedExperience;
  final _licenseController = TextEditingController();
  late final DoctorController _controller;
  bool _isEditing = false;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller;
    _selectedExperience = _controller.model.yearsOfExperience;
    _licenseController.text = _controller.model.licenseNumber ?? '';
    _licenseController.addListener(_onFieldChanged);
  }

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

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

  bool _validateFields() {
    if (_selectedExperience == null) {
      _showError('Please select years of experience');
      return false;
    }

    if (_licenseController.text.trim().isEmpty) {
      _showError('Please enter your license number');
      return false;
    }

    // Add additional license number validation if needed
    if (_licenseController.text.trim().length < 5) {
      _showError('License number must be at least 5 characters long');
      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 (!_validateFields()) {
      return false;
    }

    _controller.updateYearsOfExperience(_selectedExperience!);
    _controller.updateLicenseNumber(_licenseController.text.trim());
    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('Experience Details'),
          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(
                'Professional Experience',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              const Text(
                'Please provide your years of experience and medical license details.',
                style: TextStyle(
                  color: Colors.grey,
                  fontSize: 14,
                ),
              ),
              const SizedBox(height: 24),
              DropdownButtonFormField<String>(
                decoration: const InputDecoration(
                  labelText: 'Years of Experience',
                  border: OutlineInputBorder(),
                ),
                value: _selectedExperience,
                items: List.generate(50, (index) => index + 1)
                    .map((year) => DropdownMenuItem(
                          value: year.toString(),
                          child: Text('$year years'),
                        ))
                    .toList(),
                onChanged: (value) {
                  setState(() {
                    _selectedExperience = value;
                    _isEditing = true;
                  });
                },
              ),
              const SizedBox(height: 16),
              TextField(
                controller: _licenseController,
                decoration: const InputDecoration(
                  labelText: 'License Number',
                  hintText: 'Enter your medical license number',
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          ),
        ),
        bottomNavigationBar: 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 (_validateAndProceed()) {
                    Navigator.pushNamed(
                      context,
                      RouteNames.specialitiesScreeen,
                      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,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
