import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:medora/controllers/consultation_center_controller.dart';
import 'package:medora/data/services/consultation_center_service.dart';
import 'package:medora/route/route_names.dart';
import 'package:medora/screens/doctor_screen/doctor_consultation_schedule/consultation_day_screen.dart';

class CenterFeeAndDurationScreen extends StatefulWidget {
  final ConsultationCenterController controller;

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

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

class CenterFeeAndDurationScreenState
    extends State<CenterFeeAndDurationScreen> {
  final _formKey = GlobalKey<FormState>();
  late final ConsultationCenterController _controller;
  late TextEditingController _averageDuration;
  late TextEditingController _consultationFee;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller;
    final center = _controller.model;
    _averageDuration =
        TextEditingController(text: center.averageDurationMinutes ?? '');
    _consultationFee =
        TextEditingController(text: center.consultationFee ?? '');
  }

  @override
  void dispose() {
    _averageDuration.dispose();
    _consultationFee.dispose();
    super.dispose();
  }

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

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

  bool _validateAndProceed() {
    if (_formKey.currentState!.validate()) {
      _controller.updateConsultationFee(_consultationFee.text);
      _controller.updateAverageDuration(_averageDuration.text.trim());
      return true;
    }
    return false;
  }

  Future<void> _saveCenter() async {
    // Validate form before proceeding
    if (!_validateAndProceed()) {
      return;
    }

    try {
      // Create a list with the current controller for the new service method
      final List<ConsultationCenterController> controllers = [_controller];

      // Use the new saveConsultationCenters method
      bool success =
          await ConsultationCenterService.saveConsultationCenters(controllers);

      if (success) {
        // ignore: use_build_context_synchronously
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Doctor consultation saved successfully!'),
            backgroundColor: Colors.green,
          ),
        );
        // ignore: use_build_context_synchronously
        Navigator.of(context)
            .pushReplacementNamed(RouteNames.scheduleConsultationScreen);
      } else {
        _showError('Failed to save business center. Please try again.');
      }
    } catch (e) {
      _showError('An error occurred while saving. Please try again.');
      print('Error saving consultation center: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
            onPressed: _saveCenter,
            icon: const Icon(Icons.check),
          ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                'Fee & Duration',
                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: _consultationFee,
                      keyboardType: TextInputType.number,
                      textAlign: TextAlign.end,
                      inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter consultation fee';
                        }
                        int? fee = int.tryParse(value);
                        if (fee == null || fee <= 0) {
                          return 'Please enter valid consultation fee';
                        }
                        return null;
                      },
                      decoration: InputDecoration(
                        labelText: 'Consultation fee',
                        prefixIcon: const Icon(Icons.money, 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.updateConsultationFee(value);
                      },
                    ),
                    const SizedBox(height: 24),
                    TextFormField(
                      controller: _averageDuration,
                      textAlign: TextAlign.end,
                      keyboardType: TextInputType.number,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter average duration minutes';
                        }
                        int? duration = int.tryParse(value);
                        if (duration == null || duration <= 0) {
                          return 'Please enter valid duration';
                        }
                        return null;
                      },
                      decoration: InputDecoration(
                        labelText: 'Average duration (minutes)',
                        prefixIcon:
                            const Icon(Icons.timelapse, 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.updateAverageDuration(value);
                      },
                    ),
                    const SizedBox(height: 24),
                    // New Schedule Time link
                    Center(
                      child: TextButton(
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => ConsultationDayScreen(
                                controller: widget.controller,
                              ),
                            ),
                          );
                        },
                        style: TextButton.styleFrom(
                          foregroundColor: Colors.white,
                          backgroundColor: Colors.blue,
                          padding: const EdgeInsets.symmetric(
                              horizontal: 32, vertical: 12),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                        ),
                        child: const Text(
                          'Schedule Time',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
