// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// add_edit_timing.dart
//
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:nokken/src/core/ui/widgets/shared_widgets.dart';
import 'package:nokken/src/core/ui/widgets/dropdown_widgets.dart';
import 'package:nokken/src/core/ui/theme/app_theme.dart';
import 'package:nokken/src/core/ui/theme/app_colors.dart';
import 'package:nokken/src/core/ui/theme/app_icons.dart';
import 'package:nokken/src/core/ui/theme/app_text_styles.dart';
import 'package:nokken/src/core/utils/date_time_formatter.dart';
import 'package:nokken/src/core/constants/date_constants.dart';
import 'package:nokken/src/features/medication_tracker/models/medication.dart';

/// Timing Section for medication schedule
class TimingSection extends StatelessWidget {
  final DateTime selectedStartDate;
  final ValueChanged<DateTime> onStartDateChanged;
  final int frequency;
  final List<TimeOfDay> times;
  final Set<String> selectedDays;
  final ValueChanged<int> onFrequencyChanged;
  final Function(int, TimeOfDay) onTimeChanged;
  final ValueChanged<Set<String>> onDaysChanged;
  final bool isEveryTwoWeeks;
  final MedicationType medicationType;
  final bool asNeeded;
  final ValueChanged<bool> onAsNeededChanged;

  const TimingSection({
    super.key,
    required this.selectedStartDate,
    required this.onStartDateChanged,
    required this.frequency,
    required this.times,
    required this.selectedDays,
    required this.onFrequencyChanged,
    required this.onTimeChanged,
    required this.onDaysChanged,
    this.isEveryTwoWeeks = false,
    required this.medicationType,
    required this.asNeeded,
    required this.onAsNeededChanged,
  });

  @override
  Widget build(BuildContext context) {
    // Customize the title based on medication type
    String sectionTitle = 'Timing';
    if (medicationType == MedicationType.patch) {
      sectionTitle = 'Change Schedule';
    }

    return SharedWidgets.basicCard(
      context: context,
      title: sectionTitle,
      children: [
        _buildStartDateSelector(context),

        // "Take as Needed" toggle
        _buildAsNeededToggle(),

        // Only show scheduling UI if not an as-needed medication
        if (!asNeeded) ...[
          if (!isEveryTwoWeeks && medicationType != MedicationType.patch)
            _buildFrequencySelector(),
          SharedWidgets.verticalSpace(AppTheme.doubleSpacing),
          _buildDaySelector(context),
          SharedWidgets.verticalSpace(AppTheme.doubleSpacing),
          ...List.generate(
            frequency,
            (index) => _buildTimeInput(context, index),
          ),
        ] else ...[
          // Show description for as-needed medications
          SharedWidgets.verticalSpace(AppTheme.doubleSpacing),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: AppColors.info.withAlpha(20),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              children: [
                Icon(AppIcons.getIcon('info'), color: AppColors.info, size: 20),
                SharedWidgets.horizontalSpace(),
                const Expanded(
                  child: Text(
                    'This medication will not be scheduled for specific times. You can record doses as needed from the Daily Tracker screen.',
                    style: TextStyle(fontStyle: FontStyle.italic),
                  ),
                ),
              ],
            ),
          ),
        ],
      ],
    );
  }

  /// Build the "Take as Needed" toggle
  Widget _buildAsNeededToggle() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          'Take as Needed',
          style: TextStyle(
            fontWeight: FontWeight.w500,
            fontSize: 16,
          ),
        ),
        Switch(
          value: asNeeded,
          onChanged: onAsNeededChanged,
          activeColor: AppColors.tertiary,
        ),
      ],
    );
  }

  /// Build the frequency selector (times per day)
  Widget _buildFrequencySelector() {
    return Row(
      children: [
        const Text('Times per day: '),
        IconButton(
          icon: Icon(AppIcons.getIcon('remove')),
          onPressed:
              frequency > 1 ? () => onFrequencyChanged(frequency - 1) : null,
        ),
        Text('$frequency'),
        IconButton(
          icon: Icon(AppIcons.getIcon('add')),
          onPressed:
              frequency < 10 ? () => onFrequencyChanged(frequency + 1) : null,
        ),
      ],
    );
  }

  /// Build the days of week selector
  Widget _buildDaySelector(BuildContext context) {
    // Create dropdown items for each day
    final dayItems = DateConstants.orderedDays.map((day) {
      return DropdownMenuItem<String>(
        value: day,
        child: Text(day),
      );
    }).toList();

    // Callback to determine if a day can be deselected
    bool canDeselectDay(String day) {
      return !isEveryTwoWeeks || selectedDays.length > 1;
    }

    return Row(
      children: [
        Text('Days: ', style: AppTextStyles.titleMedium),
        Expanded(
          child: DropdownWidgets.multiSelectDropdown(
            selectedValues: selectedDays,
            items: dayItems,
            onChanged: onDaysChanged,
            placeholder: 'Select days...',
            decoration: const InputDecoration(
              contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              border: OutlineInputBorder(),
            ),
            canDeselect: canDeselectDay,
          ),
        ),
      ],
    );
  }

  /// Show date picker dialog and handle date selection
  Future<void> _selectStartDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: selectedStartDate,
      firstDate: DateTime(2000),
      lastDate: DateTime(2034),
    );
    if (picked != null && picked != selectedStartDate) {
      onStartDateChanged(picked);
    }
  }

  /// Build the start date selector
  Widget _buildStartDateSelector(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SharedWidgets.verticalSpace(),
        ListTile(
          title: Text(
            'Start Date: ${DateTimeFormatter.formatDateDDMMYY(selectedStartDate)}',
          ),
          trailing: Icon(AppIcons.getIcon('calendar')),
          onTap: () => _selectStartDate(context),
        ),
      ],
    );
  }

  /// Build time input for a specific time slot
  Widget _buildTimeInput(BuildContext context, int index) {
    final time = times[index];
    final isPM = time.hour >= 12;
    final hour12 =
        time.hour > 12 ? time.hour - 12 : (time.hour == 0 ? 12 : time.hour);

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              'Time ${index + 1}:',
              style: const TextStyle(fontSize: 16),
            ),
          ),
          // Hour input
          SizedBox(
            width: 45,
            child: TextFormField(
              initialValue: hour12.toString(),
              keyboardType: TextInputType.number,
              textAlign: TextAlign.center,
              decoration: AppTheme.defaultTextFieldDecoration,
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(2),
              ],
              onChanged: (value) {
                if (value.isNotEmpty) {
                  final newHour = int.parse(value);
                  if (newHour >= 1 && newHour <= 12) {
                    final hour24 = isPM
                        ? (newHour == 12 ? 12 : newHour + 12)
                        : (newHour == 12 ? 0 : newHour);
                    onTimeChanged(
                      index,
                      TimeOfDay(hour: hour24, minute: time.minute),
                    );
                  }
                }
              },
            ),
          ),
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 8),
            child: Text(':', style: TextStyle(fontSize: 20)),
          ),
          // Minute input
          SizedBox(
            width: 45,
            child: TextFormField(
              initialValue: time.minute.toString().padLeft(2, '0'),
              keyboardType: TextInputType.number,
              textAlign: TextAlign.center,
              decoration: AppTheme.defaultTextFieldDecoration,
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(2),
              ],
              onChanged: (value) {
                if (value.isNotEmpty) {
                  final newMinute = int.parse(value);
                  if (newMinute >= 0 && newMinute < 60) {
                    onTimeChanged(
                      index,
                      TimeOfDay(hour: time.hour, minute: newMinute),
                    );
                  }
                }
              },
            ),
          ),
          SharedWidgets.horizontalSpace(12),
          // AM/PM toggle
          TextButton(
            onPressed: () {
              final currentHour = time.hour;
              final hour12 = currentHour > 12
                  ? currentHour - 12
                  : (currentHour == 0 ? 12 : currentHour);

              final newIsPM = !isPM;
              final newHour = newIsPM
                  ? (hour12 == 12 ? 12 : hour12 + 12)
                  : (hour12 == 12 ? 0 : hour12);

              onTimeChanged(
                index,
                TimeOfDay(hour: newHour, minute: time.minute),
              );
            },
            style: TextButton.styleFrom(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
              side: BorderSide(color: AppColors.outline),
            ),
            child: Text(
              isPM ? 'PM' : 'AM',
              style: AppTextStyles.buttonText,
            ),
          ),
        ],
      ),
    );
  }
}
