import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get_thumbnail_video/index.dart';
import 'package:get_thumbnail_video/video_thumbnail.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/features/auth/model/model_auth.dart';
import 'package:recording_tool/features/auth/view_model_auth/view_model_auth.dart';
import 'package:recording_tool/features/scan_qrcode/pages/page_record_video_player.dart';
import 'package:recording_tool/gen/assets.gen.dart';
import 'package:recording_tool/shared/widgets/app_bar.dart';
import 'package:recording_tool/shared/widgets/app_empty_view.dart';
import 'package:recording_tool/shared/widgets/app_toast.dart';

/// NAS 文件服务地址，与 AuthServer.getRecordList 保持一致。
const _nasBaseUrl = 'http://sheling.local:9001';

const _videoExtensions = {
  'mp4',
  'mov',
  'm4v',
  'avi',
  'mkv',
  'flv',
  'ts',
  'wmv',
  'webm',
  '3gp',
};

/// 录像文件浏览页：目录逐级下钻，视频点击全屏播放。
class RecordListPage extends ConsumerWidget {
  const RecordListPage({
    super.key,
    required this.breadcrumbs,
    required this.items,
  });

  /// 面包屑，根页为 [赛事名]，下钻时追加目录名。
  final List<String> breadcrumbs;
  final List<RecordListItem> items;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final visibleItems = items
        .where((item) => _isDirectory(item) || _isVideoFile(item))
        .toList(growable: false);

    return Scaffold(
      backgroundColor: const Color(0xFFF5F6F8),
      appBar: AppPageBar(
        centerTitle: false,
        titleSpacing: 0,
        titleWidget: Text(
          breadcrumbs.join(' > '),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: Colors.white,
            fontSize: 15.sp,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
      body: SafeArea(
        top: false,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 4.h),
            Expanded(
              child: visibleItems.isEmpty
                  ? const AppEmptyView(message: '暂无录像内容')
                  : ListView.separated(
                      padding: EdgeInsets.fromLTRB(10.w, 8.h, 10.w, 24.h),
                      itemCount: visibleItems.length,
                      separatorBuilder: (_, _) => SizedBox(height: 8.h),
                      itemBuilder: (context, index) {
                        final item = visibleItems[index];
                        if (_isDirectory(item)) {
                          return _DirectoryCard(
                            item: item,
                            onTap: () => _openDirectory(context, ref, item),
                          );
                        }
                        return _VideoCard(
                          item: item,
                          onTap: () => _openVideo(context, item),
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _openDirectory(
    BuildContext context,
    WidgetRef ref,
    RecordListItem item,
  ) async {
    final path = item.path?.trim() ?? '';
    if (path.isEmpty) {
      AppToast.show('目录路径无效');
      return;
    }

    EasyLoading.show(status: '加载中...');
    try {
      final children = await ref
          .read(authProvider.notifier)
          .fetchRecordList(path);
      EasyLoading.dismiss();
      if (children == null) {
        AppToast.show('目录加载失败，请重试');
        return;
      }
      if (!context.mounted) return;

      final nextBreadcrumbs = [...breadcrumbs, item.name ?? ''];
      AppNavigator.push(
        RecordListPage(breadcrumbs: nextBreadcrumbs, items: children),
        context: context,
        // 多级目录复用同一页面类型，用路径区分路由，避免防重复拦截。
        name: 'RecordListPage-$path',
      );
    } catch (error) {
      EasyLoading.dismiss();
      AppToast.show('目录加载失败，请重试');
    }
  }

  void _openVideo(BuildContext context, RecordListItem item) {
    final url = resolveRecordUrl(item.url?.trim() ?? '');
    if (url.isEmpty) {
      AppToast.show('视频地址无效');
      return;
    }
    AppNavigator.push(
      RecordVideoPlayerPage(url: url, title: item.name ?? ''),
      context: context,
      name: 'RecordVideoPlayerPage-$url',
    );
  }
}

bool _isDirectory(RecordListItem item) {
  return item.type == RecordItemType.directory.value;
}

bool _isVideoFile(RecordListItem item) {
  if (item.type != RecordItemType.file.value) return false;
  var ext = (item.extension ?? '').toLowerCase();
  if (ext.startsWith('.')) ext = ext.substring(1);
  if (ext.isEmpty) {
    final name = item.name ?? '';
    final dotIndex = name.lastIndexOf('.');
    if (dotIndex >= 0 && dotIndex < name.length - 1) {
      ext = name.substring(dotIndex + 1).toLowerCase();
    }
  }
  return _videoExtensions.contains(ext);
}

/// 相对地址补全 NAS 前缀。
String resolveRecordUrl(String raw) {
  if (raw.isEmpty) return '';
  if (raw.startsWith('http://') || raw.startsWith('https://')) return raw;
  return raw.startsWith('/') ? '$_nasBaseUrl$raw' : '$_nasBaseUrl/$raw';
}

String _formatDate(DateTime? time) {
  if (time == null) return '';
  return '${time.year}-${time.month}-${time.day}';
}

class _DirectoryCard extends StatelessWidget {
  const _DirectoryCard({required this.item, required this.onTap});

  final RecordListItem item;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    final date = _formatDate(item.modTime);

    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(6.r),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(6.r),
        child: Container(
          constraints: BoxConstraints(minHeight: 72.h),
          padding: EdgeInsets.fromLTRB(20.w, 12.h, 14.w, 12.h),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      item.name ?? '',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 14.sp,
                        height: 1.2,
                        color: const Color(0xFF30343A),
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    if (date.isNotEmpty) ...[
                      SizedBox(height: 6.h),
                      Text(
                        date,
                        style: TextStyle(
                          fontSize: 11.sp,
                          height: 1.2,
                          color: const Color(0xFF6E747D),
                        ),
                      ),
                    ],
                  ],
                ),
              ),
              SizedBox(width: 12.w),
              Row(
                children: [
                  // Text(
                  //   '视频',
                  //   style: TextStyle(
                  //     fontSize: 14.sp,
                  //     color: const Color(0xFF358BFE),
                  //     fontWeight: FontWeight.w600,
                  //   ),
                  // ),
                  Icon(
                    Icons.chevron_right,
                    size: 20.r,
                    color: const Color(0xFF9AA3AF),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _VideoCard extends StatelessWidget {
  const _VideoCard({required this.item, required this.onTap});

  final RecordListItem item;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    final date = _formatDate(item.modTime);

    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(6.r),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(6.r),
        child: Padding(
          padding: EdgeInsets.all(10.r),
          child: Row(
            children: [
              _VideoThumbnail(url: resolveRecordUrl(item.url?.trim() ?? '')),
              SizedBox(width: 12.w),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      item.name ?? '',
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 14.sp,
                        height: 1.25,
                        color: const Color(0xFF30343A),
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    if (date.isNotEmpty) ...[
                      SizedBox(height: 6.h),
                      Text(
                        date,
                        style: TextStyle(
                          fontSize: 11.sp,
                          height: 1.2,
                          color: const Color(0xFF6E747D),
                        ),
                      ),
                    ],
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

/// 视频首帧封面：异步生成缩略图，失败保留灰色占位，中央始终叠加播放图标。
class _VideoThumbnail extends StatefulWidget {
  const _VideoThumbnail({required this.url});

  final String url;

  @override
  State<_VideoThumbnail> createState() => _VideoThumbnailState();
}

class _VideoThumbnailState extends State<_VideoThumbnail> {
  /// 按 url 缓存首帧，避免列表滚动重建时重复生成。
  static final Map<String, Uint8List> _cache = {};

  Uint8List? _bytes;

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    if (widget.url.isEmpty) return;
    final cached = _cache[widget.url];
    if (cached != null) {
      _bytes = cached;
      return;
    }
    try {
      final data = await VideoThumbnail.thumbnailData(
        video: widget.url,
        imageFormat: ImageFormat.JPEG,
        maxWidth: 320,
        quality: 60,
      );
      _cache[widget.url] = data;
      if (!mounted) return;
      setState(() => _bytes = data);
    } catch (_) {
      // 生成失败保持占位图，不影响点击播放。
    }
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(4.r),
      child: SizedBox(
        width: 108.w,
        height: 68.h,
        child: Stack(
          fit: StackFit.expand,
          children: [
            ColoredBox(color: const Color(0xFFEDEFF2)),
            if (_bytes != null)
              Image.memory(_bytes!, fit: BoxFit.cover, gaplessPlayback: true),
            Center(
              child: Container(
                width: 30.r,
                height: 30.r,
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.35),
                  shape: BoxShape.circle,
                ),
                child: Image(
                  image: AssetImage(Assets.images.imageVideoIcon.path),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
