import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/reminder_type.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_appointment_history_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';

enum ReminderBottomSheetStep {
  success,
  reminderConfirmation,
  reminderTypeSelection,
  creatingReminder,
  reminderSuccess,
  reminderError,
}

class AppointmentSuccessReminderBottomSheet extends StatefulWidget {
  final PatientAppointmentHistoryResponseModel appointmentModel;
  final MyAppointmentsViewModel myAppointmentsViewModel;
  final VoidCallback onComplete;

  const AppointmentSuccessReminderBottomSheet({
    Key? key,
    required this.appointmentModel,
    required this.myAppointmentsViewModel,
    required this.onComplete,
  }) : super(key: key);

  @override
  State<AppointmentSuccessReminderBottomSheet> createState() => _AppointmentSuccessReminderBottomSheetState();
}

class _AppointmentSuccessReminderBottomSheetState extends State<AppointmentSuccessReminderBottomSheet> {
  ReminderBottomSheetStep currentStep = ReminderBottomSheetStep.success;
  ReminderType? selectedReminderType;
  String errorMessage = '';
  bool isProcessing = false;

  @override
  void initState() {
    super.initState();
    // Auto-progress to reminder confirmation after showing success
    Future.delayed(Duration(milliseconds: 2000), () {
      if (mounted) {
        setState(() {
          currentStep = ReminderBottomSheetStep.reminderConfirmation;
        });
      }
    });
  }

  void _handleNoReminder() {
    Navigator.of(context).pop();
    widget.onComplete();
  }

  void _handleYesReminder() {
    setState(() {
      currentStep = ReminderBottomSheetStep.reminderTypeSelection;
    });
  }

  void _selectReminderType(ReminderType type) {
    setState(() {
      selectedReminderType = type;
    });
  }

  Future<void> _createReminder() async {
    if (selectedReminderType == null) return;

    setState(() {
      currentStep = ReminderBottomSheetStep.creatingReminder;
      isProcessing = true;
    });

    await widget.myAppointmentsViewModel.toggleReminder(
      context: context,
      shouldCreateReminder: true,
      reminderType: selectedReminderType!,
      patientAppointmentHistoryResponseModel: widget.appointmentModel,
      onSuccess: (result) {
        if (mounted) {
          setState(() {
            currentStep = ReminderBottomSheetStep.reminderSuccess;
            isProcessing = false;
          });
          // Auto-close after showing success
          Future.delayed(Duration(milliseconds: 2000), () {
            if (mounted) {
              Navigator.of(context).pop();
              widget.onComplete();
            }
          });
        }
      },
      onError: (error) {
        if (mounted) {
          setState(() {
            currentStep = ReminderBottomSheetStep.reminderError;
            errorMessage = error;
            isProcessing = false;
          });
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: AppColors.whiteColor,
        borderRadius: BorderRadius.vertical(top: Radius.circular(24.r)),
      ),
      padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 24.h),
      child: AnimatedSwitcher(
        duration: Duration(milliseconds: 300),
        child: _buildStepContent(),
      ),
    );
  }

  Widget _buildStepContent() {
    switch (currentStep) {
      case ReminderBottomSheetStep.success:
        return _buildSuccessStep();
      case ReminderBottomSheetStep.reminderConfirmation:
        return _buildReminderConfirmationStep();
      case ReminderBottomSheetStep.reminderTypeSelection:
        return _buildReminderTypeSelectionStep();
      case ReminderBottomSheetStep.creatingReminder:
        return _buildCreatingReminderStep();
      case ReminderBottomSheetStep.reminderSuccess:
        return _buildReminderSuccessStep();
      case ReminderBottomSheetStep.reminderError:
        return _buildReminderErrorStep();
    }
  }

  Widget _buildSuccessStep() {
    return Column(
      key: ValueKey('success'),
      mainAxisSize: MainAxisSize.min,
      children: [
        Utils.getSuccessWidget(loadingText: LocaleKeys.appointmentSuccess.tr(context: context)),
        SizedBox(height: 16.h),
        Center(
          child: "Your appointment has been booked successfully!".toText14(
            color: AppColors.greyTextColor,
          ),
        ),
      ],
    );
  }

  Widget _buildReminderConfirmationStep() {
    return Column(
      key: ValueKey('confirmation'),
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(
          Icons.notifications_active_outlined,
          size: 56.h,
          color: AppColors.primaryRedColor,
        ),
        SizedBox(height: 16.h),
        Center(child: "Add Reminder?".toText20(isBold: true)),
        SizedBox(height: 12.h),
        Center(
          child: "Would you like to add a reminder for this appointment?".toText14(
            color: AppColors.greyTextColor,
          ),
        ),
        SizedBox(height: 24.h),
        Row(
          children: [
            Expanded(
              child: CustomButton(
                text: LocaleKeys.cancel.tr(context: context),
                onPressed: _handleNoReminder,
                backgroundColor: AppColors.whiteColor,
                borderColor: AppColors.greyTextColor,
                textColor: AppColors.greyTextColor,
                fontSize: 14.f,
                fontWeight: FontWeight.w600,
                borderRadius: 12,
                height: 48.h,
              ),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: CustomButton(
                text: LocaleKeys.confirm.tr(context: context),
                onPressed: _handleYesReminder,
                backgroundColor: AppColors.primaryRedColor,
                borderColor: AppColors.primaryRedColor,
                textColor: Colors.white,
                fontSize: 14.f,
                fontWeight: FontWeight.w600,
                borderRadius: 12,
                height: 48.h,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildReminderTypeSelectionStep() {
    return Column(
      key: ValueKey('type_selection'),
      mainAxisSize: MainAxisSize.min,
      children: [
        Center(child: "Select Reminder Type".toText20(isBold: true)),
        SizedBox(height: 8.h),
        Center(
          child: "Choose what type of reminder you want to set".toText14(
            color: AppColors.greyTextColor,
          ),
        ),
        SizedBox(height: 24.h),
        _buildReminderTypeCard(
          type: ReminderType.appointment,
          icon: Icons.event_outlined,
          title: "Appointment Reminder",
          description: "Get reminded about your upcoming appointment",
        ),
        SizedBox(height: 12.h),
        _buildReminderTypeCard(
          type: ReminderType.payment,
          icon: Icons.payment_outlined,
          title: "Payment Reminder",
          description: "Get reminded about payment for this appointment",
        ),
        SizedBox(height: 12.h),
        _buildReminderTypeCard(
          type: ReminderType.checkIn,
          icon: Icons.check_circle_outline,
          title: "Check-In Reminder",
          description: "Get reminded to check in for your appointment",
        ),
        SizedBox(height: 24.h),
        Row(
          children: [
            Expanded(
              child: CustomButton(
                text: LocaleKeys.cancel.tr(context: context),
                onPressed: () {
                  setState(() {
                    currentStep = ReminderBottomSheetStep.reminderConfirmation;
                    selectedReminderType = null;
                  });
                },
                backgroundColor: AppColors.whiteColor,
                borderColor: AppColors.greyTextColor,
                textColor: AppColors.greyTextColor,
                fontSize: 14.f,
                fontWeight: FontWeight.w600,
                borderRadius: 12,
                height: 48.h,
              ),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: CustomButton(
                text: "Continue",
                onPressed: selectedReminderType != null ? _createReminder : null,
                backgroundColor: selectedReminderType != null ? AppColors.primaryRedColor : AppColors.greyTextColor.withAlpha(76),
                borderColor: selectedReminderType != null ? AppColors.primaryRedColor : AppColors.greyTextColor.withAlpha(76),
                textColor: Colors.white,
                fontSize: 14.f,
                fontWeight: FontWeight.w600,
                borderRadius: 12,
                height: 48.h,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildReminderTypeCard({
    required ReminderType type,
    required IconData icon,
    required String title,
    required String description,
  }) {
    final isSelected = selectedReminderType == type;
    return GestureDetector(
      onTap: () => _selectReminderType(type),
      child: Container(
        padding: EdgeInsets.all(16.h),
        decoration: BoxDecoration(
          color: isSelected ? AppColors.primaryRedColor.withAlpha(26) : AppColors.scaffoldBgColor,
          border: Border.all(
            color: isSelected ? AppColors.primaryRedColor : AppColors.borderOnlyColor,
            width: isSelected ? 2 : 1,
          ),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Row(
          children: [
            Container(
              padding: EdgeInsets.all(12.h),
              decoration: BoxDecoration(
                color: isSelected ? AppColors.primaryRedColor : AppColors.greyTextColor.withAlpha(26),
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Icon(
                icon,
                color: isSelected ? Colors.white : AppColors.greyTextColor,
                size: 24.h,
              ),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  title.toText16(
                    isBold: true,
                    color: isSelected ? AppColors.primaryRedColor : AppColors.textColor,
                  ),
                  SizedBox(height: 4.h),
                  description.toText12(
                    color: AppColors.greyTextColor,
                  ),
                ],
              ),
            ),
            if (isSelected)
              Icon(
                Icons.check_circle,
                color: AppColors.primaryRedColor,
                size: 24.h,
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildCreatingReminderStep() {
    return Column(
      key: ValueKey('creating'),
      mainAxisSize: MainAxisSize.min,
      children: [
        CircularProgressIndicator(color: AppColors.primaryRedColor),
        SizedBox(height: 24.h),
        Center(
          child: "Creating your reminder...".toText16(
            isBold: true,
          ),
        ),
        SizedBox(height: 8.h),
        Center(
          child: "Please wait while we set up your reminder".toText14(
            color: AppColors.greyTextColor,
          ),
        ),
      ],
    );
  }

  Widget _buildReminderSuccessStep() {
    return Column(
      key: ValueKey('reminder_success'),
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(
          Icons.check_circle,
          size: 64.h,
          color: AppColors.successColor,
        ),
        SizedBox(height: 16.h),
        Center(
          child: LocaleKeys.reminderSuccess.tr(context: context).toText20(
            isBold: true,
          ),
        ),
        SizedBox(height: 8.h),
        Center(
          child: "Your ${selectedReminderType?.displayName ?? 'reminder'} has been set successfully!".toText14(
            color: AppColors.greyTextColor,
          ),
        ),
      ],
    );
  }

  Widget _buildReminderErrorStep() {
    return Column(
      key: ValueKey('error'),
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(
          Icons.error_outline,
          size: 64.h,
          color: AppColors.primaryRedColor,
        ),
        SizedBox(height: 16.h),
        Center(
          child: "Error".toText20(
            isBold: true,
            color: AppColors.primaryRedColor,
          ),
        ),
        SizedBox(height: 8.h),
        Center(
          child: errorMessage.toText14(
            color: AppColors.greyTextColor,
          ),
        ),
        SizedBox(height: 24.h),
        CustomButton(
          text: "Close",
          onPressed: () {
            Navigator.of(context).pop();
            widget.onComplete();
          },
          backgroundColor: AppColors.primaryRedColor,
          borderColor: AppColors.primaryRedColor,
          textColor: Colors.white,
          fontSize: 14.f,
          fontWeight: FontWeight.w600,
          borderRadius: 12,
          height: 48.h,
        ),
      ],
    );
  }
}

