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

import '../../providers/reports_provider.dart';
import '../../utils/app_time.dart';

/// A Metabase-inspired date filter with quick presets, relative offsets,
/// and a custom date-range picker.
class ReportDateFilter extends ConsumerWidget {
  const ReportDateFilter({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final range = ref.watch(reportDateRangeProvider);
    final theme = Theme.of(context);
    final colors = theme.colorScheme;
    final text = theme.textTheme;

    return Card(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        child: Row(
          children: [
            Icon(Icons.calendar_today, size: 18, color: colors.primary),
            const SizedBox(width: 8),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(range.label, style: text.labelLarge),
                  Text(
                    AppTime.formatDateRange(range.dateTimeRange),
                    style: text.bodySmall?.copyWith(
                      color: colors.onSurfaceVariant,
                    ),
                  ),
                ],
              ),
            ),
            FilledButton.tonalIcon(
              onPressed: () => _showDateFilterDialog(context, ref),
              icon: const Icon(Icons.tune, size: 18),
              label: const Text('Change'),
            ),
          ],
        ),
      ),
    );
  }

  void _showDateFilterDialog(BuildContext context, WidgetRef ref) {
    showDialog(
      context: context,
      builder: (ctx) => _DateFilterDialog(
        current: ref.read(reportDateRangeProvider),
        onApply: (newRange) {
          ref.read(reportDateRangeProvider.notifier).state = newRange;
        },
      ),
    );
  }
}

// ──────────────────────────────────────────────
// Date filter dialog with three tabs
// ──────────────────────────────────────────────

class _DateFilterDialog extends StatefulWidget {
  const _DateFilterDialog({required this.current, required this.onApply});

  final ReportDateRange current;
  final ValueChanged<ReportDateRange> onApply;

  @override
  State<_DateFilterDialog> createState() => _DateFilterDialogState();
}

class _DateFilterDialogState extends State<_DateFilterDialog>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  // Relative tab state
  int _relativeAmount = 30;
  String _relativeUnit = 'days';

  // Custom tab state
  DateTime? _customStart;
  DateTime? _customEnd;

  static const _units = [
    'minutes',
    'hours',
    'days',
    'weeks',
    'months',
    'quarters',
    'years',
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _customStart = widget.current.start;
    _customEnd = widget.current.end;
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colors = theme.colorScheme;
    final text = theme.textTheme;

    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 440, maxHeight: 520),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Padding(
              padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
              child: Row(
                children: [
                  Icon(Icons.date_range, color: colors.primary),
                  const SizedBox(width: 8),
                  Text('Filter Date Range', style: text.titleMedium),
                  const Spacer(),
                  IconButton(
                    icon: const Icon(Icons.close, size: 20),
                    onPressed: () => Navigator.pop(context),
                  ),
                ],
              ),
            ),
            TabBar(
              controller: _tabController,
              labelStyle: text.labelMedium,
              tabs: const [
                Tab(text: 'Presets'),
                Tab(text: 'Relative'),
                Tab(text: 'Custom'),
              ],
            ),
            Flexible(
              child: TabBarView(
                controller: _tabController,
                children: [
                  _buildPresetsTab(context),
                  _buildRelativeTab(context),
                  _buildCustomTab(context),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // ─── Presets Tab ───

  Widget _buildPresetsTab(BuildContext context) {
    final now = AppTime.now();
    final today = DateTime(now.year, now.month, now.day);

    final presets = <_Preset>[
      _Preset('Today', today, today.add(const Duration(days: 1))),
      _Preset('Yesterday', today.subtract(const Duration(days: 1)), today),
      _Preset(
        'Last 7 Days',
        today.subtract(const Duration(days: 7)),
        today.add(const Duration(days: 1)),
      ),
      _Preset(
        'Last 30 Days',
        today.subtract(const Duration(days: 30)),
        today.add(const Duration(days: 1)),
      ),
      _Preset(
        'Last 90 Days',
        today.subtract(const Duration(days: 90)),
        today.add(const Duration(days: 1)),
      ),
      _Preset(
        'This Week',
        today.subtract(Duration(days: today.weekday - 1)),
        today.add(const Duration(days: 1)),
      ),
      _Preset(
        'This Month',
        DateTime(now.year, now.month, 1),
        DateTime(now.year, now.month + 1, 1),
      ),
      _Preset(
        'This Quarter',
        DateTime(now.year, ((now.month - 1) ~/ 3) * 3 + 1, 1),
        DateTime(now.year, ((now.month - 1) ~/ 3) * 3 + 4, 1),
      ),
      _Preset(
        'This Year',
        DateTime(now.year, 1, 1),
        DateTime(now.year + 1, 1, 1),
      ),
      _Preset(
        'Last Week',
        today.subtract(Duration(days: today.weekday + 6)),
        today.subtract(Duration(days: today.weekday - 1)),
      ),
      _Preset(
        'Last Month',
        DateTime(now.year, now.month - 1, 1),
        DateTime(now.year, now.month, 1),
      ),
      _Preset(
        'Last Quarter',
        DateTime(now.year, ((now.month - 1) ~/ 3) * 3 - 2, 1),
        DateTime(now.year, ((now.month - 1) ~/ 3) * 3 + 1, 1),
      ),
      _Preset(
        'Last Year',
        DateTime(now.year - 1, 1, 1),
        DateTime(now.year, 1, 1),
      ),
    ];

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Wrap(
        spacing: 8,
        runSpacing: 8,
        children: presets.map((p) {
          final isSelected = widget.current.label == p.label;
          return ChoiceChip(
            label: Text(p.label),
            selected: isSelected,
            onSelected: (_) {
              widget.onApply(
                ReportDateRange(start: p.start, end: p.end, label: p.label),
              );
              Navigator.pop(context);
            },
          );
        }).toList(),
      ),
    );
  }

  // ─── Relative Tab ───

  Widget _buildRelativeTab(BuildContext context) {
    final theme = Theme.of(context);
    final text = theme.textTheme;

    // Compute preview
    final previewRange = _computeRelativeRange(_relativeAmount, _relativeUnit);
    final previewText = AppTime.formatDateRange(previewRange.dateTimeRange);

    return Padding(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text('Previous', style: text.labelLarge),
          const SizedBox(height: 12),
          Row(
            children: [
              SizedBox(
                width: 80,
                child: TextFormField(
                  initialValue: _relativeAmount.toString(),
                  keyboardType: TextInputType.number,
                  decoration: const InputDecoration(
                    isDense: true,
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 10,
                    ),
                  ),
                  onChanged: (v) {
                    setState(() {
                      _relativeAmount = int.tryParse(v) ?? _relativeAmount;
                    });
                  },
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: DropdownButtonFormField<String>(
                  initialValue: _relativeUnit,
                  decoration: const InputDecoration(
                    isDense: true,
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 10,
                    ),
                  ),
                  items: _units
                      .map((u) => DropdownMenuItem(value: u, child: Text(u)))
                      .toList(),
                  onChanged: (v) {
                    if (v != null) setState(() => _relativeUnit = v);
                  },
                ),
              ),
              const SizedBox(width: 12),
              Text('ago', style: text.bodyLarge),
            ],
          ),
          const SizedBox(height: 16),
          Text(
            previewText,
            style: text.bodyMedium?.copyWith(
              color: theme.colorScheme.onSurfaceVariant,
            ),
          ),
          const SizedBox(height: 20),
          Align(
            alignment: Alignment.centerRight,
            child: FilledButton(
              onPressed: () {
                widget.onApply(previewRange);
                Navigator.pop(context);
              },
              child: const Text('Apply'),
            ),
          ),
        ],
      ),
    );
  }

  ReportDateRange _computeRelativeRange(int amount, String unit) {
    final now = AppTime.now();
    final end = now;
    DateTime start;

    switch (unit) {
      case 'minutes':
        start = now.subtract(Duration(minutes: amount));
      case 'hours':
        start = now.subtract(Duration(hours: amount));
      case 'days':
        start = now.subtract(Duration(days: amount));
      case 'weeks':
        start = now.subtract(Duration(days: amount * 7));
      case 'months':
        start = DateTime(now.year, now.month - amount, now.day);
      case 'quarters':
        start = DateTime(now.year, now.month - (amount * 3), now.day);
      case 'years':
        start = DateTime(now.year - amount, now.month, now.day);
      default:
        start = now.subtract(Duration(days: amount));
    }

    return ReportDateRange(start: start, end: end, label: 'Last $amount $unit');
  }

  // ─── Custom Tab ───

  Widget _buildCustomTab(BuildContext context) {
    final theme = Theme.of(context);
    final text = theme.textTheme;
    final colors = theme.colorScheme;

    return Padding(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text('Start Date', style: text.labelLarge),
          const SizedBox(height: 8),
          OutlinedButton.icon(
            icon: const Icon(Icons.calendar_today, size: 16),
            label: Text(
              _customStart != null
                  ? AppTime.formatDate(_customStart!)
                  : 'Select start date',
            ),
            onPressed: () async {
              final picked = await showDatePicker(
                context: context,
                initialDate: _customStart ?? AppTime.now(),
                firstDate: DateTime(2020),
                lastDate: DateTime(2030),
              );
              if (picked != null) setState(() => _customStart = picked);
            },
          ),
          const SizedBox(height: 16),
          Text('End Date', style: text.labelLarge),
          const SizedBox(height: 8),
          OutlinedButton.icon(
            icon: const Icon(Icons.calendar_today, size: 16),
            label: Text(
              _customEnd != null
                  ? AppTime.formatDate(_customEnd!)
                  : 'Select end date',
            ),
            onPressed: () async {
              final picked = await showDatePicker(
                context: context,
                initialDate: _customEnd ?? AppTime.now(),
                firstDate: DateTime(2020),
                lastDate: DateTime(2030),
              );
              if (picked != null) setState(() => _customEnd = picked);
            },
          ),
          if (_customStart != null && _customEnd != null) ...[
            const SizedBox(height: 12),
            Text(
              AppTime.formatDateRange(
                DateTimeRange(start: _customStart!, end: _customEnd!),
              ),
              style: text.bodyMedium?.copyWith(color: colors.onSurfaceVariant),
            ),
          ],
          const SizedBox(height: 20),
          Align(
            alignment: Alignment.centerRight,
            child: FilledButton(
              onPressed: (_customStart != null && _customEnd != null)
                  ? () {
                      widget.onApply(
                        ReportDateRange(
                          start: _customStart!,
                          end: _customEnd!.add(const Duration(days: 1)),
                          label: 'Custom Range',
                        ),
                      );
                      Navigator.pop(context);
                    }
                  : null,
              child: const Text('Apply'),
            ),
          ),
        ],
      ),
    );
  }
}

class _Preset {
  const _Preset(this.label, this.start, this.end);
  final String label;
  final DateTime start;
  final DateTime end;
}
