import 'package:flutter/material.dart';
import '../theme/app_colors.dart';
import '../theme/app_text_styles.dart';
import '../models/focus_session.dart';
import '../services/storage_service.dart';
import 'package:intl/intl.dart';
import '../l10n/app_localizations.dart';

/// History Screen - Shows past focus sessions
class HistoryScreen extends StatefulWidget {
  const HistoryScreen({super.key});

  @override
  State<HistoryScreen> createState() => _HistoryScreenState();
}

class _HistoryScreenState extends State<HistoryScreen> {
  final StorageService _storageService = StorageService();

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    final sessions = _storageService.getAllSessions();
    final todayTotal = _storageService.getTodayTotalMinutes();
    final todayDistractions = _storageService.getTodayDistractionCount();
    final todaySessions = _storageService.getTodaySessionsCount();

    // Group sessions by date
    final sessionsByDate = <DateTime, List<FocusSession>>{};
    for (final session in sessions) {
      final date = DateTime(
        session.startTime.year,
        session.startTime.month,
        session.startTime.day,
      );
      if (!sessionsByDate.containsKey(date)) {
        sessionsByDate[date] = [];
      }
      sessionsByDate[date]!.add(session);
    }

    // Sort dates (newest first)
    final sortedDates = sessionsByDate.keys.toList()
      ..sort((a, b) => b.compareTo(a));

    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: AppBar(
        title: Text(l10n.yourFocusJourney),
        backgroundColor: AppColors.background,
      ),
      body: sessions.isEmpty
          ? _buildEmptyState(context, l10n)
          : ListView(
              padding: const EdgeInsets.all(24),
              children: [
                // Today's Summary Card
                _buildTodaySummary(
                  l10n,
                  todayTotal,
                  todayDistractions,
                  todaySessions,
                ),

                const SizedBox(height: 24),

                // Sessions by date
                ...sortedDates.map((date) {
                  final dateSessions = sessionsByDate[date]!;
                  return _buildDateSection(l10n, date, dateSessions);
                }),
              ],
            ),
    );
  }

  Widget _buildEmptyState(BuildContext context, AppLocalizations l10n) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              '📊',
              style: TextStyle(fontSize: 64),
            ),
            const SizedBox(height: 24),
            Text(
              l10n.noFocusSessionsYet,
              style: AppTextStyles.headline,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 12),
            Text(
              l10n.startFirstSession,
              style: AppTextStyles.helperText,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 32),
            ElevatedButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('Start Focusing'),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTodaySummary(AppLocalizations l10n, int totalMins, int distractions, int sessions) {
    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: AppColors.white,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                '📅 ${l10n.today}',
                style: const TextStyle(
                  fontFamily: 'Nunito',
                  fontSize: 20,
                  fontWeight: FontWeight.w600,
                  color: AppColors.textPrimary,
                ),
              ),
              const Spacer(),
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 12,
                  vertical: 6,
                ),
                decoration: BoxDecoration(
                  color: AppColors.success.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  l10n.sessions(sessions),
                  style: const TextStyle(
                    fontFamily: 'Nunito',
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: AppColors.success,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 20),
          Row(
            children: [
              Expanded(
                child: _buildStat('Total', l10n.minutesValue(totalMins, l10n.minutes(totalMins)), '⏱️'),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: _buildStat(
                  'Distractions',
                  l10n.distractionsCount(distractions, l10n.times(distractions)),
                  '🤚',
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStat(String label, String value, String emoji) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          emoji,
          style: const TextStyle(fontSize: 24),
        ),
        const SizedBox(height: 8),
        Text(
          label,
          style: const TextStyle(
            fontFamily: 'Nunito',
            fontSize: 14,
            fontWeight: FontWeight.w300,
            color: AppColors.textSecondary,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            fontFamily: 'Nunito',
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: AppColors.textPrimary,
          ),
        ),
      ],
    );
  }

  Widget _buildDateSection(AppLocalizations l10n, DateTime date, List<FocusSession> sessions) {
    final isToday = _isToday(date);
    final dateLabel = isToday
        ? l10n.today
        : DateFormat('EEE, MMM d').format(date);

    final totalMinutes = sessions.fold<int>(
      0,
      (sum, session) => sum + session.actualMinutes,
    );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Date header
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 16),
          child: Row(
            children: [
              Text(
                dateLabel,
                style: const TextStyle(
                  fontFamily: 'Nunito',
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                  color: AppColors.textPrimary,
                ),
              ),
              const SizedBox(width: 12),
              Text(
                '(${l10n.minutesValue(totalMinutes, l10n.minutes(totalMinutes))})',
                style: const TextStyle(
                  fontFamily: 'Nunito',
                  fontSize: 16,
                  fontWeight: FontWeight.w400,
                  color: AppColors.textSecondary,
                ),
              ),
            ],
          ),
        ),

        // Session cards
        ...sessions.map((session) => _buildSessionCard(l10n, session)),
      ],
    );
  }

  Widget _buildSessionCard(AppLocalizations l10n, FocusSession session) {
    final timeStr = DateFormat('HH:mm').format(session.startTime);
    final statusEmoji = session.completed ? '✅' : '⏸️';
    final statusText = session.completed ? l10n.completed : l10n.stoppedEarly;

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: AppColors.divider,
          width: 1,
        ),
      ),
      child: Row(
        children: [
          // Time
          Text(
            timeStr,
            style: const TextStyle(
              fontFamily: 'Nunito',
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: AppColors.textPrimary,
            ),
          ),

          const SizedBox(width: 16),

          // Duration
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  l10n.minutesValue(session.actualMinutes, l10n.minutes(session.actualMinutes)),
                  style: AppTextStyles.bodyText,
                ),
                if (session.distractionCount > 0)
                  Padding(
                    padding: const EdgeInsets.only(top: 4),
                    child: Text(
                      l10n.distractionsCount(session.distractionCount, l10n.times(session.distractionCount)),
                      style: const TextStyle(
                        fontFamily: 'Nunito',
                        fontSize: 14,
                        fontWeight: FontWeight.w400,
                        color: AppColors.textSecondary,
                      ),
                    ),
                  ),
              ],
            ),
          ),

          // Status badge
          Container(
            padding: const EdgeInsets.symmetric(
              horizontal: 8,
              vertical: 4,
            ),
            decoration: BoxDecoration(
              color: session.completed
                  ? AppColors.success.withValues(alpha: 0.1)
                  : AppColors.distractionButton,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Text(
              '$statusEmoji $statusText',
              style: TextStyle(
                fontFamily: 'Nunito',
                fontSize: 12,
                fontWeight: FontWeight.w600,
                color: session.completed
                    ? AppColors.success
                    : AppColors.textSecondary,
              ),
            ),
          ),
        ],
      ),
    );
  }

  bool _isToday(DateTime date) {
    final now = DateTime.now();
    return date.year == now.year &&
        date.month == now.month &&
        date.day == now.day;
  }
}
