import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../models/task.dart';
import '../providers/task_provider.dart';
import '../widgets/common/app_card.dart';
import '../widgets/common/app_progress.dart';
import '../widgets/common/app_tag.dart';
import '../theme/app_colors.dart';

class TaskCenterPage extends StatefulWidget {
  const TaskCenterPage({super.key});

  @override
  State<TaskCenterPage> createState() => _TaskCenterPageState();
}

class _TaskCenterPageState extends State<TaskCenterPage> {
  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      context.read<TaskProvider>().fetchTasks();
    });
  }

  @override
  Widget build(BuildContext context) {
    final provider = context.watch<TaskProvider>();

    return Scaffold(
      appBar: AppBar(
        title: const Text('任务中心'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: provider.loading
            ? const Center(child: CircularProgressIndicator())
            : Column(
                children: [
                  _buildFilterBar(provider),
                  const SizedBox(height: 12),
                  Expanded(
                    child: ListView.builder(
                      itemCount: provider.tasks.length,
                      itemBuilder: (context, index) {
                        final task = provider.tasks[index];
                        return _buildTaskCard(task);
                      },
                    ),
                  ),
                ],
              ),
      ),
    );
  }

  Widget _buildFilterBar(TaskProvider provider) {
    return Row(
      children: [
        DropdownButton<String>(
          value: provider.statusFilter ?? '',
          items: const [
            DropdownMenuItem(value: '', child: Text('全部')),
            DropdownMenuItem(value: 'pending', child: Text('等待中')),
            DropdownMenuItem(value: 'processing', child: Text('进行中')),
            DropdownMenuItem(value: 'completed', child: Text('已完成')),
            DropdownMenuItem(value: 'failed', child: Text('失败')),
          ],
          onChanged: (value) {
            provider.fetchTasks(status: value?.isEmpty == true ? null : value);
          },
        ),
        const Spacer(),
        Text('共 ${provider.total} 个任务'),
      ],
    );
  }

  Widget _buildTaskCard(Task task) {
    Color statusColor;
    String statusLabel;
    switch (task.status) {
      case 'processing':
        statusColor = AppColors.primary;
        statusLabel = '进行中';
        break;
      case 'completed':
        statusColor = Colors.green;
        statusLabel = '已完成';
        break;
      case 'failed':
        statusColor = Colors.red;
        statusLabel = '失败';
        break;
      default:
        statusColor = Colors.grey;
        statusLabel = '等待中';
    }

    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: AppCard(
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      task.name.isNotEmpty ? task.name : task.id,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text('文档: ${task.documentId}'),
                    const SizedBox(height: 4),
                    if (task.errorMessage != null &&
                        task.errorMessage!.isNotEmpty)
                      Text(
                        task.errorMessage!,
                        style: const TextStyle(
                          fontSize: 12,
                          color: Colors.redAccent,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    const SizedBox(height: 8),
                    AppProgress(
                      value: task.progress / 100.0,
                      height: 6,
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 12),
              AppTag(label: statusLabel, color: statusColor),
            ],
          ),
        ),
      ),
    );
  }
}


