import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:medora/controllers/doctor_controller.dart';
import 'package:medora/route/route_names.dart';

class ProfileUploadPage extends StatefulWidget {
  const ProfileUploadPage({super.key});

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

class _ProfileUploadPageState extends State<ProfileUploadPage> {
  final DoctorController _controller = DoctorController();
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _surnameController = TextEditingController();
  final TextEditingController _firstController = TextEditingController();
  final TextEditingController _middlenameController = TextEditingController();
  File? _image;
  final ImagePicker _picker = ImagePicker();
  final _formKey = GlobalKey<FormState>();
  String? _selectedTitle;

  final List<String> _titles = ['Mr', 'Mrs', 'Miss'];

  @override
  void initState() {
    super.initState();

    _titleController.text = _controller.model.title ?? '';
    _surnameController.text = _controller.model.surName ?? '';
    _firstController.text = _controller.model.firstName ?? '';
    _middlenameController.text = _controller.model.middleName ?? '';
  }

  @override
  void dispose() {
    _titleController.dispose();
    _surnameController.dispose();
    _firstController.dispose();
    _middlenameController.dispose();
    super.dispose();
  }

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

  bool _validateAndProceed() {
    if (_image == null) {
      _showError('Please upload your profile picture');
      return false;
    }

    if (_formKey.currentState!.validate()) {
      _controller.updateTitle(_titleController.text);
      _controller.updateSurName(_surnameController.text);
      _controller.updateLastName(_firstController.text);
      _controller.updateMiddleName(_middlenameController.text);
      return true;
    }
    return false;
  }

  Future<void> _getImage(ImageSource source) async {
    try {
      final XFile? image = await _picker.pickImage(source: source);
      if (image != null) {
        setState(() {
          _image = File(image.path);
        });
        _controller.updateProfileImage(image.path);
      }
    } catch (e) {
      debugPrint('Error picking image: $e');
      _showError('Failed to upload image. Please try again.');
    }
  }

  void _showImageSourceActionSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return Container(
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
          ),
          child: SafeArea(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                const Padding(
                  padding: EdgeInsets.symmetric(vertical: 16),
                  child: Text(
                    'Select Image Source',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                ListTile(
                  leading: Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: Colors.blue.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: const Icon(Icons.photo_library, color: Colors.blue),
                  ),
                  title: const Text('Choose from Gallery'),
                  onTap: () {
                    _getImage(ImageSource.gallery);
                    Navigator.pop(context);
                  },
                ),
                ListTile(
                  leading: Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: Colors.blue.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: const Icon(Icons.photo_camera, color: Colors.blue),
                  ),
                  title: const Text('Take a Photo'),
                  onTap: () {
                    _getImage(ImageSource.camera);
                    Navigator.pop(context);
                  },
                ),
                const SizedBox(height: 16),
              ],
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          IconButton(
            onPressed: () {
              if (_validateAndProceed()) {
                Navigator.pushNamed(
                  context,
                  RouteNames.qualificationsScreen,
                  arguments: _controller,
                );
              }
            },
            icon: const Icon(Icons.arrow_forward),
          )
        ],
        title: const Text('Doctor Profile'),
      ),
      body: SafeArea(
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Center(
                  child: Stack(
                    children: [
                      GestureDetector(
                        onTap: () => _showImageSourceActionSheet(context),
                        child: CircleAvatar(
                          radius: 75,
                          backgroundColor: Colors.blue.withOpacity(0.5),
                          backgroundImage:
                              _image != null ? FileImage(_image!) : null,
                          child: _image == null
                              ? const Icon(Icons.person,
                                  size: 50, color: Colors.blue)
                              : null,
                        ),
                      ),
                      Positioned(
                        bottom: 0,
                        right: 0,
                        child: Container(
                          padding: const EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: Colors.blue,
                            shape: BoxShape.circle,
                            border: Border.all(color: Colors.white, width: 2),
                          ),
                          child: const Icon(Icons.camera_alt,
                              size: 16, color: Colors.white),
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 24),
                Container(
                  margin:
                      const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.blueGrey.withOpacity(0.5),
                        blurRadius: 10,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Column(
                    children: [
                      _buildUniformField(
                        label: 'Name',
                        icon: Icons.person,
                        child:
                            Container(), // The child parameter is not used in this implementation
                      ),
                      // _buildTextField(
                      //   'Title',
                      //   _titleController,
                      //   (value) => _controller.updateTitle(value),
                      //   icon: Icons.title,
                      //   isMandatory: true,
                      // ),
                      _buildTextField(
                        'Surname',
                        _surnameController,
                        (value) => _controller.updateSurName(value),
                        icon: Icons.person,
                        isMandatory: true,
                      ),
                      // _buildTextField(
                      //   'Firstname',
                      //   _lastnameController,
                      //   (value) => _controller.updateLastName(value),
                      //   icon: Icons.person_outline,
                      //   isMandatory: true,
                      // ),
                      _buildTextField(
                        'Middle name',
                        _middlenameController,
                        (value) => _controller.updateMiddleName(value),
                        icon: Icons.person_outline,
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 16),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildUniformField({
    required String label,
    required IconData icon,
    required Widget child,
  }) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: Container(
        height: 58, // Set a fixed height
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Colors.grey.shade300, width: 1),
        ),
        child: Row(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              child:
                  Icon(icon, color: Colors.blue, size: 20), // Reduced icon size
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8),
              width: 80,
              child: DropdownButtonHideUnderline(
                child: DropdownButton<String>(
                  isDense: true, // Makes dropdown more compact
                  value: _selectedTitle,
                  hint: const Text(
                    'Title',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey,
                    ),
                  ),
                  style: const TextStyle(
                    fontSize: 16,
                    color: Colors.black87,
                  ),

                  onChanged: (String? newValue) {
                    if (newValue != null) {
                      setState(() {
                        _selectedTitle = newValue;
                        _titleController.text =
                            newValue; // Add this line to update the controller
                      });
                      _controller.updateTitle(_titleController.text);
                    }
                  },

                  items: _titles.map<DropdownMenuItem<String>>(
                    (String code) {
                      return DropdownMenuItem<String>(
                        value: code,
                        child: Text(
                          code,
                          style: const TextStyle(
                            fontSize: 16,
                            color: Colors.black87,
                          ),
                        ),
                      );
                    },
                  ).toList(),
                ),
              ),
            ),
            Expanded(
              child: TextFormField(
                controller: _firstController,
                onChanged: (value) {
                  _controller.updateLastName(value);
                },
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'First name is required';
                  }
                  if (!RegExp(r"^[a-zA-Z\s]+$").hasMatch(value)) {
                    return 'Please enter valid text';
                  }
                  return null;
                },
                style: const TextStyle(
                  fontSize: 16,
                  color: Colors.black87,
                ),
                decoration: InputDecoration(
                  labelText: label,
                  labelStyle: const TextStyle(
                    fontSize: 14,
                    color: Colors.grey,
                    fontWeight: FontWeight.w400,
                  ),
                  hintText: 'Enter name',
                  border: InputBorder.none,
                  contentPadding: const EdgeInsets.symmetric(
                      vertical: 8, horizontal: 12), // Reduced vertical padding
                  // isDense: true, // Makes the input field more compact
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTextField(
    String label,
    TextEditingController controller,
    Function(String) onChanged, {
    required IconData icon,
    bool isMandatory = false,
  }) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: TextFormField(
        controller: controller,
        onChanged: onChanged,
        validator: (value) {
          if (isMandatory && (value == null || value.isEmpty)) {
            return '$label is required';
          }
          if (value != null &&
              value.isNotEmpty &&
              !RegExp(r"^[a-zA-Z\s]+$").hasMatch(value)) {
            return 'Please enter valid text';
          }
          return null;
        },
        style: const TextStyle(
          fontSize: 16,
          color: Colors.black87,
        ),
        decoration: InputDecoration(
          labelText: label,
          labelStyle: const TextStyle(
            fontSize: 14,
            color: Colors.grey,
            fontWeight: FontWeight.w400,
          ),
          prefixIcon: Icon(icon, color: Colors.blue),
          filled: true,
          fillColor: Colors.grey[100],
          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),
          ),
        ),
      ),
    );
  }
}
