import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/api/api_service.dart';
import '../../core/auth/auth_store.dart';
import '../../core/l10n/app_localizations.dart';
import '../../core/theme/app_theme.dart';
import '../../core/widgets/loading_overlay.dart';

final scheduleProvider = FutureProvider.autoDispose.family<List<dynamic>, String>((ref, participantId) async {
  return ref.watch(apiServiceProvider).getSchedule(participantId);
});

class ScheduleScreen extends ConsumerStatefulWidget {
  const ScheduleScreen({super.key});

  @override
  ConsumerState<ScheduleScreen> createState() => _ScheduleScreenState();
}

class _ScheduleScreenState extends ConsumerState<ScheduleScreen> {
  int _selectedDay = DateTime.now().weekday - 1;

  static const _daysEn = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

  @override
  Widget build(BuildContext context) {
    final l = AppLocalizations.of(context);
    final auth = ref.watch(authStoreProvider);
    final participants = auth.participants;
    final firstId = participants.isNotEmpty ? (participants.first['uuid'] ?? '') : '';

    return Scaffold(
      backgroundColor: const Color(0xFFF8FAFC),
      appBar: AppBar(
        title: Text(l.t('schedule')),
        centerTitle: true,
        backgroundColor: Colors.white,
        surfaceTintColor: Colors.transparent,
      ),
      body: Column(
        children: [
          // Day selector
          Container(
            height: 80,
            color: Colors.white,
            padding: const EdgeInsets.symmetric(vertical: 12),
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.symmetric(horizontal: 12),
              itemCount: 7,
              itemBuilder: (ctx, i) {
                final isSelected = i == _selectedDay;
                final now = DateTime.now();
                final dayDate = now.subtract(Duration(days: now.weekday - 1 - i));
                return GestureDetector(
                  onTap: () => setState(() => _selectedDay = i),
                  child: AnimatedContainer(
                    duration: 250.ms,
                    width: 52,
                    margin: const EdgeInsets.symmetric(horizontal: 4),
                    decoration: BoxDecoration(
                      color: isSelected ? AppTheme.primaryColor : Colors.transparent,
                      borderRadius: BorderRadius.circular(14),
                      border: isSelected ? null : Border.all(color: Colors.grey.shade200),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          _daysEn[i],
                          style: TextStyle(
                            fontSize: 11,
                            color: isSelected ? Colors.white70 : Colors.grey.shade500,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          '${dayDate.day}',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: isSelected ? Colors.white : Colors.black87,
                          ),
                        ),
                      ],
                    ),
                  ),
                ).animate(delay: Duration(milliseconds: i * 40)).fadeIn(duration: 300.ms);
              },
            ),
          ),
          const SizedBox(height: 8),
          // Sessions
          Expanded(
            child: firstId.isEmpty
                ? EmptyState(icon: Icons.calendar_today, message: l.t('no_sessions'))
                : Consumer(
                    builder: (ctx, ref, _) {
                      final schedule = ref.watch(scheduleProvider(firstId));
                      return schedule.when(
                        loading: () => const Center(child: CircularProgressIndicator()),
                        error: (e, _) => Center(child: Text(l.t('error_occurred'))),
                        data: (sessions) {
                          final filtered = sessions.where((s) {
                            final dayName = (s as Map)['day_of_week'];
                            return dayName == _daysEn[_selectedDay].toLowerCase() ||
                                _matchDay(dayName, _selectedDay);
                          }).toList();

                          if (filtered.isEmpty) {
                            return EmptyState(
                              icon: Icons.event_busy,
                              message: l.t('no_sessions'),
                            );
                          }

                          return ListView.builder(
                            padding: const EdgeInsets.all(16),
                            itemCount: filtered.length,
                            itemBuilder: (ctx, i) {
                              final session = filtered[i] as Map<String, dynamic>;
                              return _SessionTile(session: session, index: i);
                            },
                          );
                        },
                      );
                    },
                  ),
          ),
        ],
      ),
    );
  }

  bool _matchDay(dynamic dayName, int index) {
    if (dayName == null) return false;
    final d = dayName.toString().toLowerCase();
    final matches = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
    return index < matches.length && d == matches[index];
  }
}

class _SessionTile extends StatelessWidget {
  final Map<String, dynamic> session;
  final int index;

  const _SessionTile({required this.session, required this.index});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(color: Colors.black.withValues(alpha: 0.03), blurRadius: 8, offset: const Offset(0, 2)),
        ],
      ),
      child: Row(
        children: [
          // Time column
          Column(
            children: [
              Text(
                session['start_time'] ?? '',
                style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: AppTheme.primaryColor),
              ),
              Container(
                width: 1,
                height: 20,
                margin: const EdgeInsets.symmetric(vertical: 4),
                color: AppTheme.primaryColor.withValues(alpha: 0.3),
              ),
              Text(
                session['end_time'] ?? '',
                style: TextStyle(fontSize: 12, color: Colors.grey.shade500),
              ),
            ],
          ),
          const SizedBox(width: 16),
          Container(
            width: 4,
            height: 50,
            decoration: BoxDecoration(
              color: AppTheme.primaryColor,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          const SizedBox(width: 14),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  session['group_name'] ?? '',
                  style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
                ),
                const SizedBox(height: 4),
                if (session['trainer_name'] != null)
                  Text(
                    session['trainer_name'],
                    style: TextStyle(fontSize: 12, color: Colors.grey.shade500),
                  ),
                if (session['facility_name'] != null) ...[
                  const SizedBox(height: 2),
                  Row(
                    children: [
                      Icon(Icons.location_on, size: 12, color: Colors.grey.shade400),
                      const SizedBox(width: 4),
                      Text(
                        session['facility_name'],
                        style: TextStyle(fontSize: 11, color: Colors.grey.shade400),
                      ),
                    ],
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    )
        .animate(delay: Duration(milliseconds: 80 * index))
        .fadeIn(duration: 400.ms)
        .slideX(begin: 0.05, end: 0, curve: Curves.easeOut);
  }
}
