import 'package:audio_service/audio_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_lucide/flutter_lucide.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../theme/theme_extension.dart';
import 'player_provider.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final fs = Theme.of(context).extension<FabledSwordTheme>()!;
    final queue = ref.watch(queueProvider).value ?? const [];
    final current = ref.watch(mediaItemProvider).value;
    return Scaffold(
      backgroundColor: fs.obsidian,
      appBar: AppBar(
        backgroundColor: fs.obsidian,
        elevation: 0,
        leading: IconButton(
          icon: Icon(LucideIcons.arrow_left, color: fs.parchment),
          onPressed: () => context.pop(),
        ),
        title: Text('Queue', style: TextStyle(color: fs.parchment)),
      ),
      body: queue.isEmpty
          ? Center(
              child: Text('Queue is empty.', style: TextStyle(color: fs.ash)),
            )
          : ListView.separated(
              itemCount: queue.length,
              separatorBuilder: (_, __) => Divider(height: 1, color: fs.iron),
              itemBuilder: (ctx, i) => _QueueRow(
                item: queue[i],
                index: i,
                isCurrent: current?.id == queue[i].id,
                onTap: () async {
                  final h = ref.read(audioHandlerProvider);
                  await h.skipToQueueItem(i);
                  await h.play();
                },
              ),
            ),
    );
  }
}

class _QueueRow extends StatelessWidget {
  const _QueueRow({
    required this.item,
    required this.index,
    required this.isCurrent,
    required this.onTap,
  });

  final MediaItem item;
  final int index;
  final bool isCurrent;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    final fs = Theme.of(context).extension<FabledSwordTheme>()!;
    final dur = item.duration;
    String? durLabel;
    if (dur != null) {
      final m = (dur.inSeconds ~/ 60).toString().padLeft(2, '0');
      final s = (dur.inSeconds % 60).toString().padLeft(2, '0');
      durLabel = '$m:$s';
    }
    return InkWell(
      onTap: isCurrent ? null : onTap,
      child: Container(
        decoration: BoxDecoration(
          border: isCurrent
              ? Border(left: BorderSide(color: fs.accent, width: 2))
              : null,
          color: isCurrent ? fs.iron : null,
        ),
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
        child: Row(children: [
          if (isCurrent)
            Padding(
              padding: const EdgeInsets.only(right: 8),
              child: Icon(LucideIcons.audio_lines, color: fs.accent, size: 16),
            ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  item.title,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: isCurrent ? fs.accent : fs.parchment,
                    fontSize: 14,
                    fontWeight: isCurrent ? FontWeight.w500 : FontWeight.w400,
                  ),
                ),
                Text(
                  '${item.artist ?? ''} · ${item.album ?? ''}',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: fs.ash, fontSize: 12),
                ),
              ],
            ),
          ),
          if (durLabel != null)
            Text(durLabel, style: TextStyle(color: fs.ash, fontSize: 12)),
        ]),
      ),
    );
  }
}
