import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:it0_app/l10n/app_localizations.dart';
import '../../../../core/config/api_endpoints.dart';
import '../../../../core/network/dio_client.dart';
import '../../../../core/theme/app_colors.dart';
import '../../../../core/utils/date_formatter.dart';
import '../../../../core/errors/error_handler.dart';
import '../../../../core/widgets/empty_state.dart';
import '../../../../core/widgets/error_view.dart';
import '../../../../core/widgets/status_badge.dart';

// ---------------------------------------------------------------------------
// Provider – Standing Orders
// ---------------------------------------------------------------------------

/// Fetches all standing orders from the backend.
final standingOrdersProvider =
    FutureProvider<List<Map<String, dynamic>>>((ref) async {
  final dio = ref.watch(dioClientProvider);
  final response = await dio.get(ApiEndpoints.standingOrders);
  final data = response.data;
  if (data is List) {
    return data.cast<Map<String, dynamic>>();
  }
  if (data is Map && data.containsKey('items')) {
    return (data['items'] as List).cast<Map<String, dynamic>>();
  }
  return [];
});

// ---------------------------------------------------------------------------
// Standing Orders page – ConsumerWidget
// ---------------------------------------------------------------------------

class StandingOrdersPage extends ConsumerWidget {
  const StandingOrdersPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final ordersAsync = ref.watch(standingOrdersProvider);

    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context).standingOrdersPageTitle),
      ),
      body: RefreshIndicator(
        onRefresh: () async => ref.invalidate(standingOrdersProvider),
        child: ordersAsync.when(
          data: (orders) {
            if (orders.isEmpty) {
              return EmptyState(
                icon: Icons.rule_outlined,
                title: AppLocalizations.of(context).noStandingOrdersTitle,
                subtitle: AppLocalizations.of(context).standingOrdersEmptyHint,
              );
            }
            return ListView.builder(
              padding: const EdgeInsets.all(12),
              itemCount: orders.length,
              itemBuilder: (context, index) {
                final order = orders[index];
                return StandingOrderCard(order: order);
              },
            );
          },
          loading: () => const Center(child: CircularProgressIndicator()),
          error: (e, _) => ErrorView(
            error: e,
            onRetry: () => ref.invalidate(standingOrdersProvider),
          ),
        ),
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Standing order card widget
// ---------------------------------------------------------------------------

class StandingOrderCard extends ConsumerStatefulWidget {
  final Map<String, dynamic> order;
  const StandingOrderCard({required this.order});

  @override
  ConsumerState<StandingOrderCard> createState() =>
      StandingOrderCardState();
}

class StandingOrderCardState extends ConsumerState<StandingOrderCard> {
  bool _toggling = false;

  @override
  Widget build(BuildContext context) {
    final order = widget.order;
    final name = order['name'] as String? ?? AppLocalizations.of(context).unnamedOrderName;
    final triggerType = order['trigger_type'] as String? ??
        order['triggerType'] as String? ??
        'unknown';
    final status = order['status'] as String? ?? 'paused';
    final isActive = status.toLowerCase() == 'active';
    final lastExecution = order['last_execution'] as String? ??
        order['lastExecution'] as String?;
    final instruction = order['instruction'] as String? ??
        order['agent_instruction'] as String? ??
        order['agentInstruction'] as String? ??
        '';
    final executions = order['executions'] as List? ??
        order['execution_history'] as List? ??
        order['executionHistory'] as List? ??
        [];
    final orderId = order['id']?.toString() ?? '';

    final lastExecLabel = lastExecution != null
        ? DateFormatter.timeAgo(DateTime.parse(lastExecution))
        : AppLocalizations.of(context).neverExecuted;

    return Card(
      color: AppColors.surface,
      margin: const EdgeInsets.only(bottom: 10),
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(14),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Name row with status badge and toggle
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        name,
                        style: const TextStyle(
                            fontSize: 15, fontWeight: FontWeight.w600),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    const SizedBox(width: 8),
                    StatusBadge(
                      status: status,
                      color: isActive ? AppColors.success : AppColors.textMuted,
                    ),
                    const SizedBox(width: 8),
                    SizedBox(
                      height: 24,
                      child: _toggling
                          ? const SizedBox(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(
                                  strokeWidth: 2),
                            )
                          : Switch(
                              value: isActive,
                              activeColor: AppColors.success,
                              onChanged: (value) =>
                                  _toggleStatus(orderId, value),
                            ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),

                // Trigger type chip
                Row(
                  children: [
                    TriggerChip(triggerType: triggerType),
                    const Spacer(),
                    Icon(Icons.access_time,
                        size: 14, color: AppColors.textMuted),
                    const SizedBox(width: 4),
                    Text(
                      lastExecLabel,
                      style: const TextStyle(
                          color: AppColors.textMuted, fontSize: 12),
                    ),
                  ],
                ),

                // Agent instruction preview
                if (instruction.isNotEmpty) ...[
                  const SizedBox(height: 8),
                  Text(
                    instruction,
                    style: const TextStyle(
                        color: AppColors.textSecondary, fontSize: 13),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ],
            ),
          ),

          // Execution history expansion tile
          if (executions.isNotEmpty)
            Theme(
              data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
              child: ExpansionTile(
                tilePadding:
                    const EdgeInsets.symmetric(horizontal: 14),
                childrenPadding:
                    const EdgeInsets.fromLTRB(14, 0, 14, 10),
                title: Text(
                  '执行历史 (${executions.length})',
                  style: const TextStyle(
                      fontSize: 13, color: AppColors.textSecondary),
                ),
                children: executions
                    .cast<Map<String, dynamic>>()
                    .map((exec) => ExecutionHistoryItem(execution: exec))
                    .toList(),
              ),
            ),
        ],
      ),
    );
  }

  Future<void> _toggleStatus(String orderId, bool activate) async {
    setState(() => _toggling = true);
    try {
      final dio = ref.read(dioClientProvider);
      await dio.patch(
        '${ApiEndpoints.standingOrders}/$orderId',
        data: {'status': activate ? 'active' : 'paused'},
      );
      ref.invalidate(standingOrdersProvider);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('更新状态失败: ${ErrorHandler.friendlyMessage(e)}'),
            backgroundColor: AppColors.error,
          ),
        );
      }
    } finally {
      if (mounted) setState(() => _toggling = false);
    }
  }
}

// ---------------------------------------------------------------------------
// Trigger type chip
// ---------------------------------------------------------------------------

class TriggerChip extends StatelessWidget {
  final String triggerType;
  const TriggerChip({required this.triggerType});

  Color get _color {
    switch (triggerType.toLowerCase()) {
      case 'cron':
        return const Color(0xFFA855F7); // purple
      case 'event':
        return AppColors.info; // blue
      case 'threshold':
        return AppColors.warning; // orange
      default:
        return AppColors.textMuted;
    }
  }

  IconData get _icon {
    switch (triggerType.toLowerCase()) {
      case 'cron':
        return Icons.schedule;
      case 'event':
        return Icons.bolt;
      case 'threshold':
        return Icons.speed;
      default:
        return Icons.help_outline;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: _color.withOpacity(0.15),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _color.withOpacity(0.3)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(_icon, size: 13, color: _color),
          const SizedBox(width: 4),
          Text(
            triggerType.toUpperCase(),
            style: TextStyle(
              color: _color,
              fontSize: 11,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Execution history item
// ---------------------------------------------------------------------------

class ExecutionHistoryItem extends StatelessWidget {
  final Map<String, dynamic> execution;
  const ExecutionHistoryItem({required this.execution});

  @override
  Widget build(BuildContext context) {
    final status = execution['status'] as String? ?? 'unknown';
    final startedAt =
        execution['started_at'] as String? ?? execution['startedAt'] as String?;
    final duration =
        execution['duration'] as String? ?? execution['duration_ms']?.toString();

    final Color statusColor;
    switch (status.toLowerCase()) {
      case 'success':
        statusColor = AppColors.success;
        break;
      case 'failed':
        statusColor = AppColors.error;
        break;
      case 'running':
        statusColor = AppColors.info;
        break;
      default:
        statusColor = AppColors.textMuted;
    }

    final startLabel = startedAt != null
        ? DateFormatter.formatDateTime(DateTime.parse(startedAt))
        : 'Unknown';

    final durationLabel = duration != null ? '${duration}ms' : '-';

    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        children: [
          Container(
            width: 8,
            height: 8,
            decoration: BoxDecoration(
              color: statusColor,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: 8),
          Text(
            status.toUpperCase(),
            style: TextStyle(
              color: statusColor,
              fontSize: 11,
              fontWeight: FontWeight.w600,
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              startLabel,
              style: const TextStyle(
                  color: AppColors.textSecondary, fontSize: 12),
            ),
          ),
          Icon(Icons.timer_outlined,
              size: 13, color: AppColors.textMuted),
          const SizedBox(width: 4),
          Text(
            durationLabel,
            style: const TextStyle(
                color: AppColors.textMuted, fontSize: 12),
          ),
        ],
      ),
    );
  }
}
