import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:telemednet/route_names.dart';
import 'package:telemednet/screens/doctor_screens/address_screen.dart';
import '../../controllers/doctor _controller.dart';

class ProfileUploadPage extends StatefulWidget {
  @override
  _ProfileUploadPageState createState() => _ProfileUploadPageState();
}

class _ProfileUploadPageState extends State<ProfileUploadPage> {
  final DoctorController _controller = DoctorController();
  final _titleController = TextEditingController();
  final _surnameController = TextEditingController();
  final _firstnameController = TextEditingController();
  final _middlenameController = TextEditingController();
  final _qualificationController = TextEditingController();
  File? _image;

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

  Future<void> _pickImage() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      setState(() {
        _image = File(pickedFile.path);
      });
    }
  }

  void _addQualification() {
    if (_qualificationController.text.isNotEmpty) {
      setState(() {
        _controller.profileController
            .addQualification(_qualificationController.text);
        _qualificationController.clear();
      });
    }
  }

  void _removeQualification(String qualification) {
    setState(() {
      _controller.profileController.removeQualification(qualification);
    });
  }

  bool _validateAndProceed() {
    _controller.profileController.updateTitle(_titleController.text);
    _controller.profileController.updateSurName(_surnameController.text);
    _controller.profileController.updateLastName(_firstnameController.text);
    _controller.profileController.updateMiddleName(_middlenameController.text);

    return _controller.profileController.validateProfile();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Doctor Profile'),
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Center(
              child: GestureDetector(
                onTap: _pickImage,
                child: CircleAvatar(
                  radius: 60,
                  backgroundImage: _image != null ? FileImage(_image!) : null,
                  child:
                      _image == null ? Icon(Icons.camera_alt, size: 50) : null,
                ),
              ),
            ),
            SizedBox(height: 24),
            _buildTextField(
              'Title',
              'Mr, Ms..',
              _titleController,
              (value) => _controller.profileController.updateTitle(value),
            ),
            _buildTextField(
              'Surname',
              'Enter surname',
              _surnameController,
              (value) => _controller.profileController.updateSurName(value),
            ),
            _buildTextField(
              'Firstname',
              'Enter firstname',
              _firstnameController,
              (value) => _controller.profileController.updateLastName(value),
            ),
            _buildTextField(
              'Middle name',
              'Enter middle name',
              _middlenameController,
              (value) => _controller.profileController.updateMiddleName(value),
            ),
            SizedBox(height: 16),
            Text(
              'Qualifications',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 8),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _qualificationController,
                    decoration: InputDecoration(
                      hintText: 'Add Qualification',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                SizedBox(width: 8),
                ElevatedButton(
                  onPressed: _addQualification,
                  child: Icon(Icons.add),
                  style: ElevatedButton.styleFrom(
                    shape: CircleBorder(),
                    padding: EdgeInsets.all(12),
                  ),
                ),
              ],
            ),
            SizedBox(height: 16),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: _controller.profileController.model.qualifications
                  .map((qual) => Chip(
                        label: Text(qual),
                        deleteIcon: Icon(Icons.close),
                        onDeleted: () => _removeQualification(qual),
                      ))
                  .toList(),
            ),
          ],
        ),
      ),
      bottomNavigationBar: Padding(
        padding: const EdgeInsets.all(16),
        child: ElevatedButton(
          onPressed: () {
            Navigator.pushNamed(
              context,
              RouteNames.doctorAddressScreen,
              arguments: DoctorAddressScreen(controller: _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,
          ),
        ),
      ),
    );
  }

  Widget _buildTextField(
    String label,
    String hint,
    TextEditingController controller,
    Function(String) onChanged,
  ) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: TextField(
        controller: controller,
        decoration: InputDecoration(
          labelText: label,
          hintText: hint,
          border: OutlineInputBorder(),
        ),
        onChanged: onChanged,
      ),
    );
  }
}
