import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:medora/controllers/doctor_controller.dart';
import 'package:medora/data/services/doctor_profile_service.dart';
import 'package:medora/route/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> {
  final _formKey = GlobalKey<FormState>();
  late final DoctorController _controller;
  late TextEditingController _selectedExperience;
  late TextEditingController _licenseController;

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

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

  void _onFieldChanged() {
    setState(() {});
  }

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

  Future<bool> _validateAndProceed() async {
    if (_formKey.currentState!.validate()) {
      // Check for duplicate license number
      bool isDuplicate = await DoctorProfileService.isLicenseNumberDuplicate(
          _licenseController.text.trim());

      if (isDuplicate) {
        _showError('This license number is already registered');
        return false;
      }

      _controller.updateYearsOfExperience(_selectedExperience.text);
      _controller.updateLicenseNumber(_licenseController.text.trim());
      return true;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
            onPressed: () async {
              if (await _validateAndProceed()) {
                Navigator.pushNamed(
                  context,
                  RouteNames.specialitiesScreeen,
                  arguments: _controller,
                );
              }
            },
            icon: const Icon(
              Icons.arrow_forward,
              // color: _formKey.currentState?.validate() == true
              //     ? Colors.blue
              //     : Colors.red,
            ),
          ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: 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: 24),
              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(
                  children: [
                    TextFormField(
                      controller: _selectedExperience,
                      keyboardType: TextInputType.number,
                      inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter years of experience';
                        }
                        int? years = int.tryParse(value);
                        if (years == null || years <= 0) {
                          return 'Please enter valid years of experience';
                        }
                        if (years > 50) {
                          return 'Years of experience cannot exceed 50';
                        }
                        return null;
                      },
                      decoration: InputDecoration(
                        labelText: 'Years of Experience',
                        prefixIcon: const Icon(Icons.work, color: Colors.blue),
                        filled: true,
                        fillColor: Colors.grey[100],
                        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),
                        ),
                      ),
                      onChanged: (value) {
                        _onFieldChanged();
                        widget.controller.updateYearsOfExperience(value);
                      },
                    ),
                    const SizedBox(height: 24),
                    TextFormField(
                      controller: _licenseController,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter license number';
                        }
                        if (value.length < 5) {
                          return 'License number must be at least 5 digits';
                        }
                        if (!RegExp(r'^[a-zA-Z0-9]+$').hasMatch(value)) {
                          return 'Please enter numbers only';
                        }
                        return null;
                      },
                      decoration: InputDecoration(
                        labelText: 'License Number',
                        prefixIcon: const Icon(Icons.badge, color: Colors.blue),
                        filled: true,
                        fillColor: Colors.grey[100],
                        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),
                        ),
                      ),
                      onChanged: (value) {
                        _onFieldChanged();
                        widget.controller.updateLicenseNumber(value);
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
