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/errors/error_handler.dart';
import '../../../../core/network/dio_client.dart';
import '../../../../core/theme/app_colors.dart';
import '../../../../core/utils/date_formatter.dart';
import '../../../../core/widgets/error_view.dart';

// ---------------------------------------------------------------------------
// Model
// ---------------------------------------------------------------------------

class AgentInstance {
  final String id;
  final String name;
  final String agentType;
  final String serverHost;
  final int hostPort;
  final String containerName;
  final String status; // deploying | running | stopped | error | removed
  final String? errorMessage;
  final DateTime createdAt;

  const AgentInstance({
    required this.id,
    required this.name,
    required this.agentType,
    required this.serverHost,
    required this.hostPort,
    required this.containerName,
    required this.status,
    this.errorMessage,
    required this.createdAt,
  });

  factory AgentInstance.fromJson(Map<String, dynamic> j) => AgentInstance(
        id: j['id'] as String,
        name: j['name'] as String? ?? '未命名',
        agentType: j['agentType'] as String? ?? 'openclaw',
        serverHost: j['serverHost'] as String? ?? '',
        hostPort: j['hostPort'] as int? ?? 0,
        containerName: j['containerName'] as String? ?? '',
        status: j['status'] as String? ?? 'unknown',
        errorMessage: j['errorMessage'] as String?,
        createdAt: DateTime.tryParse(j['createdAt'] as String? ?? '') ?? DateTime.now(),
      );
}

// ---------------------------------------------------------------------------
// Provider
// ---------------------------------------------------------------------------

final myInstancesProvider = FutureProvider<List<AgentInstance>>((ref) async {
  final dio = ref.watch(dioClientProvider);
  try {
    final res = await dio.get(ApiEndpoints.agentInstances);
    final data = res.data;
    if (data is List) {
      return data
          .cast<Map<String, dynamic>>()
          .map(AgentInstance.fromJson)
          .where((i) => i.status != 'removed')
          .toList();
    }
    return [];
  } catch (_) {
    return [];
  }
});

// ---------------------------------------------------------------------------
// Status helpers
// ---------------------------------------------------------------------------

const _statusColors = {
  'running':   Color(0xFF22C55E),
  'deploying': Color(0xFF3B82F6),
  'stopped':   Color(0xFFF59E0B),
  'error':     Color(0xFFEF4444),
};

String _statusLabel(BuildContext context, String status) {
  final l = AppLocalizations.of(context);
  return switch (status) {
    'running'   => l.statusRunning,
    'deploying' => l.statusDeploying,
    'stopped'   => l.statusStopped,
    'error'     => l.statusError,
    _           => status,
  };
}

const _statusIcons = {
  'running':   Icons.circle,
  'deploying': Icons.sync,
  'stopped':   Icons.pause_circle_outline,
  'error':     Icons.error_outline,
};

// ---------------------------------------------------------------------------
// My Agents Page
// ---------------------------------------------------------------------------

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

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

    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: AppBar(
        backgroundColor: AppColors.background,
        title: Text(AppLocalizations.of(context).myAgentsTitle),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh_outlined),
            onPressed: () => ref.invalidate(myInstancesProvider),
          ),
        ],
      ),
      body: instancesAsync.when(
        data: (instances) => instances.isEmpty
            ? _buildEmptyGuide(context)
            : _buildInstanceList(context, ref, instances),
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (e, _) => ErrorView(
          error: e,
          onRetry: () => ref.invalidate(myInstancesProvider),
        ),
      ),
    );
  }

  Widget _buildEmptyGuide(BuildContext context) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        children: [
          const SizedBox(height: 40),
          Container(
            width: 120,
            height: 120,
            decoration: BoxDecoration(
              color: AppColors.primary.withOpacity(0.1),
              shape: BoxShape.circle,
            ),
            child: const Icon(Icons.smart_toy_outlined, size: 60, color: AppColors.primary),
          ),
          const SizedBox(height: 24),
          Text(
            AppLocalizations.of(context).myAgentsEmptyTitle,
            style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: AppColors.textPrimary),
          ),
          const SizedBox(height: 10),
          Text(
            AppLocalizations.of(context).myAgentsEmptyDesc,
            style: const TextStyle(fontSize: 14, color: AppColors.textSecondary, height: 1.6),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 36),
          _StepCard(step: '1', title: AppLocalizations.of(context).myAgentsStep1Title, desc: AppLocalizations.of(context).myAgentsStep1Desc, icon: Icons.smart_toy_outlined, color: AppColors.primary),
          const SizedBox(height: 12),
          _StepCard(step: '2', title: AppLocalizations.of(context).myAgentsStep2Title, desc: AppLocalizations.of(context).myAgentsStep2Desc, icon: Icons.record_voice_over_outlined, color: const Color(0xFF0EA5E9)),
          const SizedBox(height: 12),
          _StepCard(step: '3', title: AppLocalizations.of(context).myAgentsStep3Title, desc: AppLocalizations.of(context).myAgentsStep3Desc, icon: Icons.check_circle_outline, color: AppColors.success),
          const SizedBox(height: 36),
          const _TemplatesSection(),
          const SizedBox(height: 100),
        ],
      ),
    );
  }

  Widget _buildInstanceList(BuildContext context, WidgetRef ref, List<AgentInstance> instances) {
    final running = instances.where((i) => i.status == 'running').length;
    return RefreshIndicator(
      onRefresh: () async => ref.invalidate(myInstancesProvider),
      child: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
              child: Row(
                children: [
                  _SummaryChip(label: AppLocalizations.of(context).summaryTotal(instances.length), color: AppColors.textMuted),
                  const SizedBox(width: 8),
                  _SummaryChip(label: AppLocalizations.of(context).summaryRunning(running), color: const Color(0xFF22C55E)),
                  const SizedBox(width: 8),
                  _SummaryChip(label: AppLocalizations.of(context).summaryStopped(instances.length - running), color: const Color(0xFFF59E0B)),
                ],
              ),
            ),
          ),
          const SliverToBoxAdapter(child: SizedBox(height: 12)),
          SliverPadding(
            padding: const EdgeInsets.fromLTRB(16, 0, 16, 100),
            sliver: SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  if (index.isOdd) return const SizedBox(height: 10);
                  final inst = instances[index ~/ 2];
                  return _InstanceCard(
                    instance: inst,
                    onDismiss: () => _handleDismiss(context, ref, inst),
                    onRename: () => _handleRename(context, ref, inst),
                  );
                },
                childCount: instances.length * 2 - 1,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Dismiss / Rename helpers (top-level functions for ConsumerWidget access)
// ---------------------------------------------------------------------------

Future<void> _handleDismiss(
    BuildContext context, WidgetRef ref, AgentInstance instance) async {
  final confirmed = await showDialog<bool>(
    context: context,
    builder: (ctx) => _DismissConfirmDialog(name: instance.name),
  );
  if (confirmed != true) return;
  try {
    final dio = ref.read(dioClientProvider);
    await dio.delete('${ApiEndpoints.agentInstances}/${instance.id}');
    ref.invalidate(myInstancesProvider);
    if (context.mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(AppLocalizations.of(context).dismissSuccessMessage(instance.name))),
      );
    }
  } catch (e) {
    if (context.mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(AppLocalizations.of(context).dismissErrorMessage(ErrorHandler.friendlyMessage(e))),
          backgroundColor: AppColors.error,
        ),
      );
    }
  }
}

Future<void> _handleRename(
    BuildContext context, WidgetRef ref, AgentInstance instance) async {
  final newName = await showDialog<String>(
    context: context,
    builder: (ctx) => _RenameDialog(currentName: instance.name),
  );
  if (newName == null || newName.trim().isEmpty) return;
  try {
    final dio = ref.read(dioClientProvider);
    await dio.put(
      '${ApiEndpoints.agentInstances}/${instance.id}/name',
      data: {'name': newName.trim()},
    );
    ref.invalidate(myInstancesProvider);
    if (context.mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(AppLocalizations.of(context).renameSuccessMessage)),
      );
    }
  } catch (e) {
    if (context.mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(AppLocalizations.of(context).renameErrorMessage(ErrorHandler.friendlyMessage(e))),
          backgroundColor: AppColors.error,
        ),
      );
    }
  }
}

// ---------------------------------------------------------------------------
// Summary chip
// ---------------------------------------------------------------------------

class _SummaryChip extends StatelessWidget {
  final String label;
  final Color color;

  const _SummaryChip({required this.label, required this.color});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.12),
        borderRadius: BorderRadius.circular(20),
      ),
      child: Text(label, style: TextStyle(fontSize: 12, color: color, fontWeight: FontWeight.w500)),
    );
  }
}

// ---------------------------------------------------------------------------
// Instance card
// ---------------------------------------------------------------------------

class _InstanceCard extends StatelessWidget {
  final AgentInstance instance;
  final VoidCallback? onDismiss;
  final VoidCallback? onRename;

  const _InstanceCard({required this.instance, this.onDismiss, this.onRename});

  void _showActions(BuildContext context) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (ctx) => SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 36,
              height: 4,
              margin: const EdgeInsets.symmetric(vertical: 12),
              decoration: BoxDecoration(
                color: AppColors.textMuted.withOpacity(0.4),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            ListTile(
              leading: const Icon(Icons.drive_file_rename_outline),
              title: Text(AppLocalizations.of(ctx).renameButton),
              onTap: () { Navigator.pop(ctx); onRename?.call(); },
            ),
            const Divider(height: 1),
            ListTile(
              leading: const Icon(Icons.person_remove_outlined, color: AppColors.error),
              title: Text(AppLocalizations.of(ctx).dismissButton, style: const TextStyle(color: AppColors.error)),
              onTap: () { Navigator.pop(ctx); onDismiss?.call(); },
            ),
            const SizedBox(height: 8),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final statusColor = _statusColors[instance.status] ?? AppColors.textMuted;
    final statusLabel = _statusLabel(context, instance.status);
    final statusIcon = _statusIcons[instance.status] ?? Icons.help_outline;
    final timeLabel = DateFormatter.timeAgo(instance.createdAt);
    final isDeploying = instance.status == 'deploying';

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: statusColor.withOpacity(0.2)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 44,
                height: 44,
                decoration: BoxDecoration(
                  color: AppColors.primary.withOpacity(0.12),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: const Icon(Icons.hub_outlined, color: AppColors.primary, size: 24),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      instance.name,
                      style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: AppColors.textPrimary),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 2),
                    Text(
                      instance.agentType.toUpperCase(),
                      style: const TextStyle(fontSize: 11, color: AppColors.textMuted, letterSpacing: 0.5),
                    ),
                  ],
                ),
              ),
              // Status badge
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: statusColor.withOpacity(0.12),
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    isDeploying
                        ? SizedBox(
                            width: 10,
                            height: 10,
                            child: CircularProgressIndicator(strokeWidth: 1.5, color: statusColor),
                          )
                        : Icon(statusIcon, size: 10, color: statusColor),
                    const SizedBox(width: 4),
                    Text(statusLabel, style: TextStyle(fontSize: 11, color: statusColor, fontWeight: FontWeight.w600)),
                  ],
                ),
              ),
              // More options
              IconButton(
                icon: const Icon(Icons.more_vert, size: 18),
                padding: EdgeInsets.zero,
                constraints: const BoxConstraints(),
                color: AppColors.textMuted,
                onPressed: () => _showActions(context),
              ),
            ],
          ),

          // Server info row
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
            decoration: BoxDecoration(color: AppColors.background, borderRadius: BorderRadius.circular(8)),
            child: Row(
              children: [
                const Icon(Icons.dns_outlined, size: 14, color: AppColors.textMuted),
                const SizedBox(width: 6),
                Expanded(
                  child: Text(
                    '${instance.serverHost}:${instance.hostPort}',
                    style: const TextStyle(fontSize: 12, color: AppColors.textSecondary, fontFamily: 'monospace'),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                const SizedBox(width: 8),
                Text(timeLabel, style: const TextStyle(fontSize: 11, color: AppColors.textMuted)),
              ],
            ),
          ),

          // Error message
          if (instance.errorMessage != null) ...[
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: const Color(0xFFEF4444).withOpacity(0.08),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: [
                  const Icon(Icons.warning_amber_outlined, size: 14, color: Color(0xFFEF4444)),
                  const SizedBox(width: 6),
                  Expanded(
                    child: Text(
                      instance.errorMessage!,
                      style: const TextStyle(fontSize: 11, color: Color(0xFFEF4444)),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Step guide card
// ---------------------------------------------------------------------------

class _StepCard extends StatelessWidget {
  final String step;
  final String title;
  final String desc;
  final IconData icon;
  final Color color;

  const _StepCard({required this.step, required this.title, required this.desc, required this.icon, required this.color});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: color.withOpacity(0.2)),
      ),
      child: Row(
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(color: color.withOpacity(0.15), shape: BoxShape.circle),
            child: Center(child: Text(step, style: TextStyle(color: color, fontWeight: FontWeight.bold, fontSize: 14))),
          ),
          const SizedBox(width: 14),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(title, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: AppColors.textPrimary)),
                const SizedBox(height: 3),
                Text(desc, style: const TextStyle(fontSize: 12, color: AppColors.textMuted, height: 1.4)),
              ],
            ),
          ),
          Icon(icon, color: color, size: 22),
        ],
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Template suggestions
// ---------------------------------------------------------------------------

class _TemplatesSection extends StatelessWidget {
  const _TemplatesSection();

  static const _templates = [
    _Template(name: 'OpenClaw 编程助手', desc: '代码审查、自动化测试', icon: Icons.code_outlined, color: Color(0xFF8B5CF6)),
    _Template(name: '运维自动化机器人', desc: '日志分析、故障自愈', icon: Icons.auto_fix_high_outlined, color: Color(0xFFF59E0B)),
    _Template(name: '数据分析助手', desc: '报表生成、异常检测', icon: Icons.bar_chart_outlined, color: Color(0xFF0EA5E9)),
    _Template(name: '安全巡检机器人', desc: '漏洞扫描、合规审查', icon: Icons.shield_outlined, color: Color(0xFFEF4444)),
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(AppLocalizations.of(context).myAgentsTemplatesHeader, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: AppColors.textSecondary)),
        const SizedBox(height: 12),
        GridView.count(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          crossAxisCount: 2,
          mainAxisSpacing: 10,
          crossAxisSpacing: 10,
          childAspectRatio: 1.5,
          children: _templates.map((t) => _TemplateChip(template: t)).toList(),
        ),
      ],
    );
  }
}

class _Template {
  final String name;
  final String desc;
  final IconData icon;
  final Color color;
  const _Template({required this.name, required this.desc, required this.icon, required this.color});
}

class _TemplateChip extends StatelessWidget {
  final _Template template;
  const _TemplateChip({required this.template});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: template.color.withOpacity(0.25)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Icon(template.icon, color: template.color, size: 24),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(template.name, style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: AppColors.textPrimary), maxLines: 1, overflow: TextOverflow.ellipsis),
              const SizedBox(height: 2),
              Text(template.desc, style: const TextStyle(fontSize: 10, color: AppColors.textMuted), maxLines: 1, overflow: TextOverflow.ellipsis),
            ],
          ),
        ],
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Dismiss confirm dialog
// ---------------------------------------------------------------------------

class _DismissConfirmDialog extends StatelessWidget {
  final String name;
  const _DismissConfirmDialog({required this.name});

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      title: Row(
        children: [
          const Icon(Icons.warning_amber_rounded, color: AppColors.error),
          const SizedBox(width: 8),
          Text(AppLocalizations.of(context).dismissTitle),
        ],
      ),
      content: Text(
        AppLocalizations.of(context).dismissConfirmContent(name),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(false),
          child: Text(AppLocalizations.of(context).cancelButton),
        ),
        FilledButton(
          style: FilledButton.styleFrom(backgroundColor: AppColors.error),
          onPressed: () => Navigator.of(context).pop(true),
          child: Text(AppLocalizations.of(context).dismissButton),
        ),
      ],
    );
  }
}

// ---------------------------------------------------------------------------
// Rename dialog
// ---------------------------------------------------------------------------

class _RenameDialog extends StatefulWidget {
  final String currentName;
  const _RenameDialog({required this.currentName});

  @override
  State<_RenameDialog> createState() => _RenameDialogState();
}

class _RenameDialogState extends State<_RenameDialog> {
  late final TextEditingController _ctrl;

  @override
  void initState() {
    super.initState();
    _ctrl = TextEditingController(text: widget.currentName);
  }

  @override
  void dispose() {
    _ctrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      title: Text(AppLocalizations.of(context).renameTitle),
      content: TextField(
        controller: _ctrl,
        autofocus: true,
        decoration: InputDecoration(
          hintText: AppLocalizations.of(context).renameHint,
          border: const OutlineInputBorder(),
        ),
        onSubmitted: (_) => Navigator.of(context).pop(_ctrl.text),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(null),
          child: Text(AppLocalizations.of(context).cancelButton),
        ),
        FilledButton(
          onPressed: () => Navigator.of(context).pop(_ctrl.text),
          child: Text(AppLocalizations.of(context).confirmButton),
        ),
      ],
    );
  }
}
