import 'package:flutter/material.dart';
import 'package:medora/controllers/consultation_center_controller.dart';
import 'package:medora/route/route_names.dart';

class BusinessCenterScreen extends StatefulWidget {
  final ConsultationCenterController controller;
  const BusinessCenterScreen({
    super.key,
    required this.controller,
  });
  @override
  State<BusinessCenterScreen> createState() => _ConsultationCenterScreenState();
}

class _ConsultationCenterScreenState extends State<BusinessCenterScreen> {
  late ConsultationCenterController _controller;
  late TextEditingController _floorBuildingController;
  late TextEditingController _streetController;
  late TextEditingController _cityController;
  late TextEditingController _stateController;
  late TextEditingController _countryController;
  late TextEditingController _postalCodeController;
  late TextEditingController _addressTypeController;
  final _formKey = GlobalKey<FormState>();
  String? selectedAddressType;
  bool showCustomTypeField = false;

  final List<String> addressTypes = ['Home', 'Office', 'Others'];

  @override
  void initState() {
    super.initState();
    _controller = widget.controller;
    _loadSavedData();
  }

  @override
  void dispose() {
    _floorBuildingController.dispose();
    _streetController.dispose();
    _cityController.dispose();
    _stateController.dispose();
    _countryController.dispose();
    _postalCodeController.dispose();
    _addressTypeController.dispose();
    super.dispose();
  }

  void _loadSavedData() {
    final center = _controller.model;
    _floorBuildingController =
        TextEditingController(text: center.floorBuilding ?? '');
    _streetController = TextEditingController(text: center.street ?? '');
    _cityController = TextEditingController(text: center.city ?? '');
    _stateController = TextEditingController(text: center.state ?? '');
    _countryController = TextEditingController(text: center.country ?? '');
    _postalCodeController =
        TextEditingController(text: center.postalCode ?? '');
    _addressTypeController =
        TextEditingController(text: center.addressType ?? '');
    selectedAddressType = widget.controller.model.addressType;
    if (selectedAddressType != null &&
        !addressTypes.contains(selectedAddressType)) {
      showCustomTypeField = true;
    }
  }

  bool _validateAndProceed() {
    if (_formKey.currentState!.validate()) {
      _controller.updateFloorBuilding(_floorBuildingController.text);
      _controller.updateStreet(_streetController.text);
      _controller.updateCity(_cityController.text);
      _controller.updateState(_stateController.text);
      _controller.updateCountry(_countryController.text);
      _controller.updatePostalCode(_postalCodeController.text);
      _controller.updateAddressType(_addressTypeController.text);

      return true;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
            onPressed: () {
              if (_validateAndProceed()) {
                Navigator.pushNamed(
                  context,
                  RouteNames.centerFeeAndDuration,
                  arguments: _controller,
                );
              }
            },
            icon: const Icon(Icons.arrow_forward),
          ),
        ],
        title: const Text('Address Details'),
      ),
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: 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: [
                _buildTextField(
                  label: 'Floor, Building',
                  controller: _floorBuildingController,
                  onChanged: (value) =>
                      widget.controller.updateFloorBuilding(value),
                  icon: Icons.apartment,
                  isMandatory: true,
                ),
                _buildTextField(
                  label: 'Street or Road',
                  controller: _streetController,
                  onChanged: (value) => widget.controller.updateStreet(value),
                  icon: Icons.streetview,
                  isMandatory: true,
                ),
                _buildTextField(
                  label: 'City',
                  controller: _cityController,
                  onChanged: (value) => widget.controller.updateCity(value),
                  icon: Icons.location_city,
                  isMandatory: true,
                ),
                _buildTextField(
                  label: 'State',
                  controller: _stateController,
                  onChanged: (value) => widget.controller.updateState(value),
                  icon: Icons.map,
                  isMandatory: true,
                ),
                _buildTextField(
                  label: 'Country',
                  controller: _countryController,
                  onChanged: (value) => widget.controller.updateCountry(value),
                  icon: Icons.flag,
                  isMandatory: true,
                ),
                _buildPostalCodeField(
                  label: 'Postal Code',
                  controller: _postalCodeController,
                  onChanged: (value) =>
                      widget.controller.updatePostalCode(value),
                  icon: Icons.mail,
                  isMandatory: true,
                ),
                // const SizedBox(height: 16),
                // _buildAddressTypeChips(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTextField({
    required String label,
    required TextEditingController controller,
    required 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-Z0-9\s]+$").hasMatch(value)) {
            return 'Please enter valid text';
          }
          return null;
        },
        decoration: InputDecoration(
          labelText: label,
          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),
          ),
        ),
      ),
    );
  }

  Widget _buildPostalCodeField({
    required String label,
    required TextEditingController controller,
    required Function(String) onChanged,
    required IconData icon,
    bool isMandatory = false,
  }) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: TextFormField(
        controller: controller,
        onChanged: onChanged,
        keyboardType: TextInputType.number,
        maxLength: 6,
        validator: (value) {
          if (isMandatory && (value == null || value.isEmpty)) {
            return '$label is required';
          }
          if (value != null && !RegExp(r'^[0-9]+$').hasMatch(value)) {
            return 'Please enter numbers only';
          }
          return null;
        },
        decoration: InputDecoration(
          labelText: label,
          prefixIcon: Icon(icon, color: Colors.blue),
          // filled: true,
          // fillColor: Colors.grey[100],
          contentPadding:
              const EdgeInsets.symmetric(vertical: 20, horizontal: 12),
          counterText: '',
          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),
          ),
        ),
      ),
    );
  }
}
