import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/components/kasy_app_bar.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/core/widgets/kasy_scroll_behavior.dart';
import 'package:kasy_kit/features/local_reminder/providers/reminder_notifier.dart';
import 'package:kasy_kit/features/local_reminder/repositories/reminder_preferences.dart';
import 'package:kasy_kit/i18n/translations.g.dart';

class ReminderPage extends ConsumerWidget {
  const ReminderPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final asyncState = ref.watch(reminderProvider);
    final tr = Translations.of(context).reminderPage;

    return ScrollConfiguration(
      behavior: const KasyKitScrollBehavior(),
      child: KasyOverlayScaffold(
        title: tr.title,
        onBack: () => Navigator.maybePop(context),
        slivers: [
        asyncState.when(
          loading: () => SliverFillRemaining(
            child: Center(
              child: CircularProgressIndicator(
                color: context.colors.primary,
              ),
            ),
          ),
          error: (e, _) => SliverFillRemaining(
            child: Center(child: Text(e.toString())),
          ),
          data: (state) => SliverToBoxAdapter(
            child: _ReminderForm(state: state),
          ),
        ),
      ],
      ),
    );
  }
}

class _ReminderForm extends ConsumerWidget {
  final ReminderState state;

  const _ReminderForm({required this.state});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final tr = Translations.of(context).reminderPage;
    final notifier = ref.read(reminderProvider.notifier);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        SwitchListTile(
          title: Text(
            tr.toggleLabel,
            style: context.textTheme.bodyLarge,
          ),
          value: state.enabled,
          onChanged: notifier.setEnabled,
        ),
        if (state.enabled) ...[
          const Divider(),
          const SizedBox(height: KasySpacing.sm),
          Text(
            tr.typeLabel,
            style: context.textTheme.labelLarge?.copyWith(
              color: context.colors.muted,
            ),
          ),
          const SizedBox(height: KasySpacing.sm),
          _TypeSelector(current: state.type, onChanged: notifier.setType),
          const SizedBox(height: KasySpacing.lg),
          Text(
            tr.timeLabel,
            style: context.textTheme.labelLarge?.copyWith(
              color: context.colors.muted,
            ),
          ),
          const SizedBox(height: KasySpacing.sm),
          _TimeTile(
            hour: state.hour,
            minute: state.minute,
            onChanged: (h, m) => notifier.setTime(h, m),
          ),
          if (state.type == ReminderType.weekly) ...[
            const SizedBox(height: KasySpacing.lg),
            Text(
              tr.dayLabel,
              style: context.textTheme.labelLarge?.copyWith(
                color: context.colors.muted,
              ),
            ),
            const SizedBox(height: KasySpacing.sm),
            _DaySelector(current: state.dayOfWeek, onChanged: notifier.setDayOfWeek),
          ],
          if (state.type == ReminderType.specificDate) ...[
            const SizedBox(height: KasySpacing.lg),
            Text(
              tr.dateLabel,
              style: context.textTheme.labelLarge?.copyWith(
                color: context.colors.muted,
              ),
            ),
            const SizedBox(height: KasySpacing.sm),
            _DateTile(
              date: state.date,
              onChanged: notifier.setDate,
            ),
          ],
        ],
      ],
    );
  }
}

class _TypeSelector extends StatelessWidget {
  final ReminderType current;
  final ValueChanged<ReminderType> onChanged;

  const _TypeSelector({required this.current, required this.onChanged});

  @override
  Widget build(BuildContext context) {
    final tr = Translations.of(context).reminderPage;
    return SegmentedButton<ReminderType>(
      segments: [
        ButtonSegment(value: ReminderType.daily, label: Text(tr.daily)),
        ButtonSegment(value: ReminderType.weekly, label: Text(tr.weekly)),
        ButtonSegment(value: ReminderType.specificDate, label: Text(tr.specificDate)),
      ],
      selected: {current},
      onSelectionChanged: (s) => onChanged(s.first),
      style: ButtonStyle(
        textStyle: WidgetStateProperty.all(context.textTheme.labelSmall),
      ),
    );
  }
}

class _TimeTile extends StatelessWidget {
  final int hour;
  final int minute;
  final void Function(int hour, int minute) onChanged;

  const _TimeTile({required this.hour, required this.minute, required this.onChanged});

  String _pad(int v) => v.toString().padLeft(2, '0');

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () async {
        final picked = await showTimePicker(
          context: context,
          initialTime: TimeOfDay(hour: hour, minute: minute),
        );
        if (picked != null) {
          onChanged(picked.hour, picked.minute);
        }
      },
      borderRadius: BorderRadius.circular(KasySpacing.sm),
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: KasySpacing.md,
          vertical: KasySpacing.smd,
        ),
        decoration: BoxDecoration(
          color: context.colors.surface,
          borderRadius: BorderRadius.circular(KasySpacing.sm),
        ),
        child: Row(
          children: [
            Icon(KasyIcons.time, color: context.colors.primary),
            const SizedBox(width: KasySpacing.sm),
            Text(
              '${_pad(hour)}:${_pad(minute)}',
              style: context.textTheme.headlineMedium?.copyWith(
                color: context.colors.onSurface,
                fontWeight: FontWeight.bold,
              ),
            ),
            const Spacer(),
            Icon(KasyIcons.arrowForwardIos, size: 14, color: context.colors.muted),
          ],
        ),
      ),
    );
  }
}

class _DaySelector extends StatelessWidget {
  final int current;
  final ValueChanged<int> onChanged;

  const _DaySelector({required this.current, required this.onChanged});

  @override
  Widget build(BuildContext context) {
    // 1=Monday ... 7=Sunday (matches DateTime.weekday)
    final days = [
      'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb', 'Dom',
    ];
    return Wrap(
      spacing: KasySpacing.xs,
      children: List.generate(7, (i) {
        final dayIndex = i + 1;
        final selected = current == dayIndex;
        return ChoiceChip(
          label: Text(days[i]),
          selected: selected,
          onSelected: (_) => onChanged(dayIndex),
        );
      }),
    );
  }
}

class _DateTile extends StatelessWidget {
  final DateTime? date;
  final ValueChanged<DateTime> onChanged;

  const _DateTile({required this.date, required this.onChanged});

  @override
  Widget build(BuildContext context) {
    final label = date != null
        ? '${date!.day.toString().padLeft(2, '0')}/${date!.month.toString().padLeft(2, '0')}/${date!.year}  ${date!.hour.toString().padLeft(2, '0')}:${date!.minute.toString().padLeft(2, '0')}'
        : Translations.of(context).reminderPage.selectDate;

    return InkWell(
      onTap: () async {
        final now = DateTime.now();
        final pickedDate = await showDatePicker(
          context: context,
          initialDate: date ?? now,
          firstDate: now,
          lastDate: now.add(const Duration(days: 365)),
        );
        if (pickedDate == null || !context.mounted) return;
        final pickedTime = await showTimePicker(
          context: context,
          initialTime: TimeOfDay(
            hour: date?.hour ?? 9,
            minute: date?.minute ?? 0,
          ),
        );
        if (pickedTime == null) return;
        onChanged(DateTime(
          pickedDate.year,
          pickedDate.month,
          pickedDate.day,
          pickedTime.hour,
          pickedTime.minute,
        ));
      },
      borderRadius: BorderRadius.circular(KasySpacing.sm),
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: KasySpacing.md,
          vertical: KasySpacing.smd,
        ),
        decoration: BoxDecoration(
          color: context.colors.surface,
          borderRadius: BorderRadius.circular(KasySpacing.sm),
        ),
        child: Row(
          children: [
            Icon(KasyIcons.calendar, color: context.colors.primary),
            const SizedBox(width: KasySpacing.sm),
            Text(
              label,
              style: context.textTheme.bodyLarge?.copyWith(
                color: context.colors.onSurface,
              ),
            ),
            const Spacer(),
            Icon(KasyIcons.arrowForwardIos, size: 14, color: context.colors.muted),
          ],
        ),
      ),
    );
  }
}
