import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;

import '../models/task.dart';

class TaskProvider extends ChangeNotifier {
  List<Task> _tasks = [];
  int _pageNum = 1;
  int _pageSize = 10;
  int _total = 0;
  String? _statusFilter;
  bool _loading = false;

  List<Task> get tasks => _tasks;
  int get pageNum => _pageNum;
  int get pageSize => _pageSize;
  int get total => _total;
  String? get statusFilter => _statusFilter;
  bool get loading => _loading;

  // TODO: 抽到配置
  final String baseUrl = 'http://localhost:8003';

  Future<void> fetchTasks({String? status, int? pageNum, int? pageSize}) async {
    _loading = true;
    notifyListeners();

    _statusFilter = status ?? _statusFilter;
    _pageNum = pageNum ?? _pageNum;
    _pageSize = pageSize ?? _pageSize;

    final query = <String, String>{
      'pageNum': _pageNum.toString(),
      'pageSize': _pageSize.toString(),
    };
    if (_statusFilter != null && _statusFilter!.isNotEmpty) {
      query['status'] = _statusFilter!;
    }

    final uri = Uri.parse('$baseUrl/api/v1/tasks/list').replace(
      queryParameters: query,
    );

    try {
      final resp = await http.get(uri);
      if (resp.statusCode == 200) {
        final body = json.decode(resp.body) as Map<String, dynamic>;
        final data = body['data'] as Map<String, dynamic>;
        final records = data['records'] as List<dynamic>? ?? [];
        _total = (data['total'] ?? 0) as int;
        _tasks = records
            .map((e) => Task.fromJson(e as Map<String, dynamic>))
            .toList();
      } else {
        if (kDebugMode) {
          print('fetchTasks failed: ${resp.statusCode} ${resp.body}');
        }
      }
    } catch (e) {
      if (kDebugMode) {
        print('fetchTasks error: $e');
      }
    } finally {
      _loading = false;
      notifyListeners();
    }
  }

  Future<Task?> fetchTaskDetail(String taskId) async {
    final uri = Uri.parse('$baseUrl/api/v1/tasks/$taskId/detail');
    try {
      final resp = await http.get(uri);
      if (resp.statusCode == 200) {
        final body = json.decode(resp.body) as Map<String, dynamic>;
        final data = body['data'] as Map<String, dynamic>;
        return Task.fromJson(data);
      }
    } catch (e) {
      if (kDebugMode) {
        print('fetchTaskDetail error: $e');
      }
    }
    return null;
  }

  Future<void> deleteTask(String taskId) async {
    final uri = Uri.parse('$baseUrl/api/v1/tasks/$taskId');
    try {
      final resp = await http.delete(uri);
      if (resp.statusCode == 200) {
        _tasks.removeWhere((t) => t.id == taskId);
        _total = _total > 0 ? _total - 1 : 0;
        notifyListeners();
      }
    } catch (e) {
      if (kDebugMode) {
        print('deleteTask error: $e');
      }
    }
  }
}


