// collection/collection_screen.dart

import 'package:flutter/material.dart';
import 'package:puzzleweave/audio/jc_audio_controller.dart';
import 'package:puzzleweave/config/device.dart';
import 'package:puzzleweave/l10n/app_localizations.dart';
import 'package:puzzleweave/models/download.dart';
import 'package:puzzleweave/models/items.dart';
import 'dart:ui' as ui;

import 'package:provider/provider.dart';

class ImageDetailDialog extends StatefulWidget {
  final ListItem item;
  const ImageDetailDialog({super.key, required this.item});

  @override
  State<StatefulWidget> createState() => _ImageDetailDialog();
}

class _ImageDetailDialog extends State<ImageDetailDialog> {
  bool _isLoading = true;

  ui.Image? image;

  String? _error; // 新增错误状态

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

    loadImage();
  }

  void loadImage() async {
    try {
      Device device = context.read<Device>();
      double dpr = device.devicePixelRatio;

      // 计算最佳尺寸（屏幕宽度90%，按2:3比例计算高度）
      final bestWidth = (device.screenSize.width * 0.9 * dpr).round();
      final bestHeight = (bestWidth * 3 / 2).round();

      ItemLoader itemLoader = ItemLoader.load(widget.item);
      final loadedImage = await itemLoader.getImageBySize(bestWidth, bestHeight);

      if (mounted) {
        setState(() {
          image = loadedImage;
          _isLoading = false;
          _error = null;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
          _error = "图片加载失败";
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final device = context.read<Device>();
    final screenWidth = device.screenSize.width;

    return Scaffold(
      // 背景设为黑色半透明，突出图片
      backgroundColor: Colors.black.withOpacity(0.8),
      body: Stack(
        children: [
          // 主内容区：加载中/错误/图片
          Center(child: _buildContent(screenWidth)),
          // 左上角关闭按钮
          Positioned(
            top: device.appBarHeight + 16, // 适配状态栏高度
            left: 16,
            child: _buildCloseButton(),
          ),
        ],
      ),
    );
  }

  // 构建主体内容（加载中/错误/图片）
  Widget _buildContent(double screenWidth) {
    final audio = context.read<JcAudioController>();
    if (_isLoading) {
      // 加载状态：居中显示进度条
      return const CircularProgressIndicator(color: Colors.white, strokeWidth: 3);
    }

    if (_error != null) {
      // 错误状态：显示错误信息和重试按钮
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.error_outline, color: Colors.red, size: 48),
          const SizedBox(height: 16),
          Text(_error!, style: const TextStyle(color: Colors.white, fontSize: 18)),
          TextButton(
            onPressed: () {
              audio.playSfx(SfxType.click);
              loadImage();
            },
            child: Text(AppLocalizations.of(context)!.retry, style: TextStyle(color: Colors.blue, fontSize: 16)),
          ),
        ],
      );
    }

    return ConstrainedBox(
      constraints: BoxConstraints(
        maxWidth: screenWidth * 0.9, // 最大宽度为屏幕90%
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(16), // 圆角大小（可自定义，如12、16）
        // 可选：添加边框+背景，让圆角更有层次感
        child: DecoratedBox(
          decoration: BoxDecoration(
            color: Colors.grey[900], // 图片加载前的背景色（避免白边）
            // 可选：添加边框
            border: Border.all(
              color: Colors.white.withOpacity(0.3), // 边框颜色（半透明白色）
              width: 2, // 边框宽度
            ),
          ),
          child: RawImage(image: image!, fit: BoxFit.contain, alignment: Alignment.center),
        ),
      ),
    );
  }

  // 构建关闭按钮
  Widget _buildCloseButton() {
    return GestureDetector(
      onTap: () => Navigator.pop(context),
      child: Container(
        width: 40,
        height: 40,
        decoration: BoxDecoration(
          color: Colors.black54, // 半透黑背景
          shape: BoxShape.circle,
        ),
        child: const Icon(Icons.close, color: Colors.white, size: 24),
      ),
    );
  }
}
