import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import '../../../core/constants/app_colors.dart';
import '../../../core/utils/format_utils.dart';
import '../../../domain/entities/batch_mining_record.dart';
import '../../providers/user_providers.dart';
import '../../providers/mining_providers.dart';

/// 补发记录页面
class BatchMiningRecordsListPage extends ConsumerStatefulWidget {
  const BatchMiningRecordsListPage({super.key});

  @override
  ConsumerState<BatchMiningRecordsListPage> createState() => _BatchMiningRecordsListPageState();
}

class _BatchMiningRecordsListPageState extends ConsumerState<BatchMiningRecordsListPage> {
  static const Color _orange = Color(0xFFFF6B00);
  static const Color _green = Color(0xFF22C55E);
  static const Color _grayText = Color(0xFF6B7280);
  static const Color _darkText = Color(0xFF1F2937);

  int _currentPage = 1;
  static const int _pageSize = 20;

  @override
  Widget build(BuildContext context) {
    final user = ref.watch(userNotifierProvider);
    final accountSequence = user.accountSequence ?? '';

    final recordsParams = BatchMiningRecordsParams(
      accountSequence: accountSequence,
      page: _currentPage,
      pageSize: _pageSize,
    );
    final recordsAsync = ref.watch(batchMiningRecordsProvider(recordsParams));

    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: _darkText, size: 20),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text(
          '补发记录',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: _darkText,
          ),
        ),
        centerTitle: true,
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          setState(() => _currentPage = 1);
          ref.invalidate(batchMiningRecordsProvider(recordsParams));
        },
        child: recordsAsync.when(
          loading: () => _buildLoadingList(),
          error: (error, stack) => _buildErrorView(error.toString(), recordsParams),
          data: (recordsPage) {
            if (recordsPage == null || recordsPage.items.isEmpty) {
              return _buildEmptyView();
            }
            return _buildRecordsList(recordsPage);
          },
        ),
      ),
    );
  }

  Widget _buildLoadingList() {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: 10,
      itemBuilder: (context, index) => _buildShimmerCard(),
    );
  }

  Widget _buildShimmerCard() {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                width: 120,
                height: 16,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              Container(
                width: 80,
                height: 20,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Container(
                width: 60,
                height: 12,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              const SizedBox(width: 16),
              Container(
                width: 80,
                height: 12,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildErrorView(String error, BatchMiningRecordsParams params) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.error_outline, size: 48, color: AppColors.error),
          const SizedBox(height: 16),
          Text('加载失败', style: TextStyle(fontSize: 16, color: _grayText)),
          const SizedBox(height: 8),
          Text(error, style: TextStyle(fontSize: 12, color: _grayText)),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: () {
              ref.invalidate(batchMiningRecordsProvider(params));
            },
            style: ElevatedButton.styleFrom(backgroundColor: _orange),
            child: const Text('重试', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.inbox_outlined, size: 64, color: _grayText.withOpacity(0.5)),
          const SizedBox(height: 16),
          Text(
            '暂无补发记录',
            style: TextStyle(fontSize: 16, color: _grayText),
          ),
        ],
      ),
    );
  }

  Widget _buildRecordsList(BatchMiningRecordsPage recordsPage) {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: recordsPage.items.length + 1,
      itemBuilder: (context, index) {
        if (index == recordsPage.items.length) {
          return _buildPaginationInfo(recordsPage);
        }
        return _buildRecordCard(recordsPage.items[index]);
      },
    );
  }

  Widget _buildRecordCard(BatchMiningRecord record) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 第一行：批次/阶段信息 + 补发金额
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: _orange.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      '第${record.batch}批',
                      style: const TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                        color: _orange,
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.blue.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      '阶段${record.phase}',
                      style: const TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                        color: Colors.blue,
                      ),
                    ),
                  ),
                ],
              ),
              Text(
                '+${formatDecimal(record.amount, 13)}',
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: _green,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),

          // 第二行：认种量 + 阶段天数
          Row(
            children: [
              Expanded(
                child: _buildInfoItem('认种量', '${record.treeCount} 棵'),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: _buildInfoItem('阶段天数', '${record.daysInPhase} 天'),
              ),
            ],
          ),
          const SizedBox(height: 8),

          // 第三行：提前天数
          Row(
            children: [
              Expanded(
                child: _buildInfoItem('提前天数', '${record.preMineDays} 天'),
              ),
              const SizedBox(width: 16),
              const Expanded(child: SizedBox()),
            ],
          ),

          // 备注（如果有）
          if (record.remark != null && record.remark!.isNotEmpty) ...[
            const SizedBox(height: 8),
            Row(
              children: [
                Icon(Icons.note_outlined, size: 12, color: _grayText.withOpacity(0.7)),
                const SizedBox(width: 4),
                Expanded(
                  child: Text(
                    record.remark!,
                    style: TextStyle(fontSize: 11, color: _grayText.withOpacity(0.7)),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ],

          const SizedBox(height: 8),
          // 记录时间
          Row(
            children: [
              Icon(Icons.access_time, size: 12, color: _grayText.withOpacity(0.7)),
              const SizedBox(width: 4),
              Text(
                DateFormat('yyyy-MM-dd HH:mm:ss').format(record.createdAt.toLocal()),
                style: TextStyle(fontSize: 11, color: _grayText.withOpacity(0.7)),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildInfoItem(String label, String value) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          '$label: ',
          style: TextStyle(fontSize: 12, color: _grayText.withOpacity(0.7)),
        ),
        Flexible(
          child: Text(
            value,
            style: const TextStyle(
              fontSize: 12,
              color: _darkText,
              fontWeight: FontWeight.w500,
            ),
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ],
    );
  }

  Widget _buildPaginationInfo(BatchMiningRecordsPage recordsPage) {
    final totalPages = recordsPage.totalPages > 0
        ? recordsPage.totalPages
        : (recordsPage.total / _pageSize).ceil();

    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16),
      child: Column(
        children: [
          Text(
            '共 ${recordsPage.total} 条记录，第 $_currentPage / $totalPages 页',
            style: TextStyle(fontSize: 12, color: _grayText),
          ),
          const SizedBox(height: 12),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              if (_currentPage > 1)
                TextButton.icon(
                  onPressed: () {
                    setState(() => _currentPage--);
                  },
                  icon: const Icon(Icons.chevron_left, size: 18),
                  label: const Text('上一页'),
                  style: TextButton.styleFrom(foregroundColor: _orange),
                ),
              const SizedBox(width: 16),
              if (_currentPage < totalPages)
                TextButton.icon(
                  onPressed: () {
                    setState(() => _currentPage++);
                  },
                  icon: const Text('下一页'),
                  label: const Icon(Icons.chevron_right, size: 18),
                  style: TextButton.styleFrom(foregroundColor: _orange),
                ),
            ],
          ),
        ],
      ),
    );
  }
}
