import 'package:flutter/material.dart';
import '../../../integrations/proto_socket/proto_socket_lifecycle.dart';
import '../domain/project_workspace.dart';
import '../domain/workspace_task.dart';

/// Loads the active tasks for a workspace through the service boundary.
///
/// When null the page keeps its mock task rendering; when present the page
/// renders loaded [WorkspaceTask] rows with deterministic loading/error/empty
/// states.
typedef WorkspaceTaskLoader =
    Future<List<WorkspaceTask>> Function(ProjectWorkspace project);

class WorkspaceHomePage extends StatefulWidget {
  final Future<bool> Function(ProjectWorkspace)? onLaunchCodeServer;
  final WorkspaceTaskLoader? loadTasks;
  final ProtoSocketLifecycle? protoSocketLifecycle;
  final bool showAppBar;

  const WorkspaceHomePage({
    super.key,
    this.onLaunchCodeServer,
    this.loadTasks,
    this.protoSocketLifecycle,
    this.showAppBar = true,
  });

  @override
  State<WorkspaceHomePage> createState() => _WorkspaceHomePageState();
}

class _WorkspaceHomePageState extends State<WorkspaceHomePage> {
  ProjectWorkspace? _selectedProject;
  Future<List<WorkspaceTask>>? _tasksFuture;

  @override
  void initState() {
    super.initState();
    // Default to the first active workspace
    if (mockProjectWorkspaces.isNotEmpty) {
      _selectedProject = mockProjectWorkspaces.first;
      _reloadTasks();
    }
  }

  @override
  void didUpdateWidget(covariant WorkspaceHomePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.loadTasks == widget.loadTasks) return;
    _reloadTasks();
  }

  void _selectProject(ProjectWorkspace project) {
    setState(() {
      _selectedProject = project;
      _reloadTasks();
    });
  }

  /// Recomputes `_tasksFuture` for the current selection. Only starts a load
  /// when a service boundary is wired; otherwise the page stays on mock rows.
  void _reloadTasks() {
    final loader = widget.loadTasks;
    final project = _selectedProject;
    _tasksFuture = (loader != null && project != null) ? loader(project) : null;
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isLargeScreen = MediaQuery.of(context).size.width > 600;

    final body = isLargeScreen
        ? _buildDualPaneLayout(theme)
        : _buildSinglePaneLayout(theme);

    return Scaffold(
      backgroundColor: const Color(0xFF0F0F1A), // Sleek deep dark background
      appBar: widget.showAppBar ? _buildAppBar() : null,
      body: body,
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(6),
            decoration: BoxDecoration(
              color: Colors.deepPurpleAccent.withValues(alpha: 0.2),
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Icon(
              Icons.blur_on,
              color: Colors.deepPurpleAccent,
              size: 24,
            ),
          ),
          const SizedBox(width: 12),
          const Text(
            'NomadCode Console',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              letterSpacing: 0.5,
              color: Colors.white,
            ),
          ),
        ],
      ),
      backgroundColor: const Color(0xFF16162A),
      elevation: 0,
      actions: [
        IconButton(
          icon: const Icon(Icons.refresh, color: Colors.white70),
          onPressed: () {
            // Refresh state placeholder
          },
        ),
      ],
    );
  }

  Widget _buildDualPaneLayout(ThemeData theme) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // Left Panel: Workspaces list
        Expanded(
          flex: 2,
          child: Container(
            decoration: const BoxDecoration(
              color: Color(0xFF131326),
              border: Border(
                right: BorderSide(color: Color(0xFF1E1E38), width: 1),
              ),
            ),
            child: _buildWorkspaceList(),
          ),
        ),
        // Right Panel: Selected Workspace Details
        Expanded(
          flex: 3,
          child: _selectedProject == null
              ? const Center(
                  child: Text(
                    'Select a workspace to view details',
                    style: TextStyle(color: Colors.white38),
                  ),
                )
              : _buildWorkspaceDetails(theme, _selectedProject!),
        ),
      ],
    );
  }

  Widget _buildSinglePaneLayout(ThemeData theme) {
    return Column(
      children: [
        Expanded(child: _buildWorkspaceList()),
        if (_selectedProject != null)
          Container(
            padding: const EdgeInsets.all(16),
            decoration: const BoxDecoration(
              color: Color(0xFF16162A),
              border: Border(
                top: BorderSide(color: Color(0xFF1E1E38), width: 1),
              ),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        _selectedProject!.name,
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    _buildLaunchButton(_selectedProject!),
                  ],
                ),
              ],
            ),
          ),
      ],
    );
  }

  Widget _buildWorkspaceList() {
    return ListView.builder(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
      itemCount: mockProjectWorkspaces.length,
      itemBuilder: (context, index) {
        final project = mockProjectWorkspaces[index];
        final isSelected = _selectedProject?.id == project.id;

        return Card(
          color: isSelected ? const Color(0xFF21213D) : const Color(0xFF181830),
          elevation: isSelected ? 4 : 1,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
            side: BorderSide(
              color: isSelected
                  ? Colors.deepPurpleAccent
                  : const Color(0xFF26264A),
              width: 1.5,
            ),
          ),
          margin: const EdgeInsets.only(bottom: 12),
          child: InkWell(
            borderRadius: BorderRadius.circular(12),
            onTap: () => _selectProject(project),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Row(
                children: [
                  Container(
                    width: 48,
                    height: 48,
                    decoration: BoxDecoration(
                      color: isSelected
                          ? Colors.deepPurpleAccent.withValues(alpha: 0.15)
                          : const Color(0xFF232345),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      project.status == ProjectStatus.active
                          ? Icons.code
                          : Icons.pause_circle_outline,
                      color: project.status == ProjectStatus.active
                          ? Colors.cyanAccent
                          : Colors.amberAccent,
                      size: 24,
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          project.name,
                          style: const TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 16,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          project.description,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                            color: Colors.white60,
                            fontSize: 13,
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(width: 8),
                  if (project.tasksCount > 0)
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.deepPurpleAccent.withValues(alpha: 0.3),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Text(
                        '${project.tasksCount} Tasks',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 10,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildWorkspaceDetails(ThemeData theme, ProjectWorkspace project) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      project.name,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 28,
                        fontWeight: FontWeight.bold,
                        letterSpacing: -0.5,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: project.status == ProjectStatus.active
                            ? Colors.cyanAccent.withValues(alpha: 0.15)
                            : Colors.amberAccent.withValues(alpha: 0.15),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Text(
                        project.status.name.toUpperCase(),
                        style: TextStyle(
                          color: project.status == ProjectStatus.active
                              ? Colors.cyanAccent
                              : Colors.amberAccent,
                          fontSize: 11,
                          fontWeight: FontWeight.bold,
                          letterSpacing: 1.0,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              _buildLaunchButton(project),
            ],
          ),
          const SizedBox(height: 24),
          const Divider(color: Color(0xFF26264A)),
          const SizedBox(height: 16),
          const Text(
            'DESCRIPTION',
            style: TextStyle(
              color: Colors.white38,
              fontSize: 12,
              fontWeight: FontWeight.bold,
              letterSpacing: 1.0,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            project.description,
            style: const TextStyle(
              color: Colors.white70,
              fontSize: 15,
              height: 1.5,
            ),
          ),
          const SizedBox(height: 32),
          const Text(
            'ACTIVE TASKS',
            style: TextStyle(
              color: Colors.white38,
              fontSize: 12,
              fontWeight: FontWeight.bold,
              letterSpacing: 1.0,
            ),
          ),
          const SizedBox(height: 16),
          _buildTaskSection(project),
          _buildProtoSocketDiagnosticsSection(),
        ],
      ),
    );
  }

  /// Renders the ACTIVE TASKS body. Falls back to mock rows when no service
  /// boundary is wired, otherwise reflects the service load state.
  Widget _buildTaskSection(ProjectWorkspace project) {
    if (widget.loadTasks == null) {
      return _buildMockTaskSection(project);
    }
    return FutureBuilder<List<WorkspaceTask>>(
      future: _tasksFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Padding(
            padding: EdgeInsets.symmetric(vertical: 20),
            child: Center(child: CircularProgressIndicator()),
          );
        }
        if (snapshot.hasError) {
          return _buildTaskError();
        }
        final tasks = snapshot.data ?? const <WorkspaceTask>[];
        if (tasks.isEmpty) {
          return _buildEmptyTasks();
        }
        return Column(
          children: [for (final task in tasks) _buildTaskRow(task)],
        );
      },
    );
  }

  Widget _buildMockTaskSection(ProjectWorkspace project) {
    if (project.tasksCount == 0) {
      return _buildEmptyTasks();
    }
    return Column(
      children: List.generate(
        project.tasksCount,
        (i) => Container(
          margin: const EdgeInsets.only(bottom: 12),
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: const Color(0xFF181835),
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: const Color(0xFF2B2B52)),
          ),
          child: Row(
            children: [
              const Icon(Icons.sync, color: Colors.deepPurpleAccent),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Task #${1000 + i + (project.name.hashCode % 100)}',
                      style: const TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                        fontSize: 14,
                      ),
                    ),
                    const SizedBox(height: 4),
                    const Text(
                      'Running workflow core optimizations...',
                      style: TextStyle(color: Colors.white54, fontSize: 12),
                    ),
                  ],
                ),
              ),
              _buildStatusChip('running'),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTaskRow(WorkspaceTask task) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFF181835),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: const Color(0xFF2B2B52)),
      ),
      child: Row(
        children: [
          const Icon(Icons.sync, color: Colors.deepPurpleAccent),
          const SizedBox(width: 16),
          Expanded(
            child: Text(
              task.title,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
                fontSize: 14,
              ),
            ),
          ),
          const SizedBox(width: 8),
          _buildStatusChip(task.status),
        ],
      ),
    );
  }

  Widget _buildProtoSocketDiagnosticsSection() {
    final lifecycle = widget.protoSocketLifecycle;
    if (lifecycle == null) return const SizedBox.shrink();
    return StreamBuilder<ProtoSocketDiagnostics>(
      stream: lifecycle.diagnosticsStream,
      initialData: lifecycle.diagnostics,
      builder: (context, snapshot) {
        final diagnostics = snapshot.data ?? lifecycle.diagnostics;
        final stateColor = _diagnosticsStateColor(diagnostics.state);
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 32),
            const Text(
              'PROTO-SOCKET',
              style: TextStyle(
                color: Colors.white38,
                fontSize: 12,
                fontWeight: FontWeight.bold,
                letterSpacing: 1.0,
              ),
            ),
            const SizedBox(height: 16),
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: const Color(0xFF14142B),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: const Color(0xFF222244)),
              ),
              child: Wrap(
                spacing: 10,
                runSpacing: 10,
                children: [
                  _buildDiagnosticsChip(
                    Icons.wifi_tethering,
                    'state',
                    diagnostics.state.name,
                    color: stateColor,
                  ),
                  _buildDiagnosticsChip(
                    Icons.link,
                    'connection_id',
                    _diagnosticValue(diagnostics.connectionId),
                  ),
                  _buildDiagnosticsChip(
                    Icons.device_hub,
                    'protocol_version',
                    _diagnosticValue(diagnostics.protocolVersion),
                  ),
                  _buildDiagnosticsChip(
                    Icons.label_outline,
                    'channel',
                    _diagnosticValue(diagnostics.channel),
                  ),
                  _buildDiagnosticsChip(
                    Icons.flash_on,
                    'action',
                    _diagnosticValue(diagnostics.action),
                  ),
                  _buildDiagnosticsChip(
                    Icons.error_outline,
                    'error_code',
                    _diagnosticValue(diagnostics.errorCode, empty: 'none'),
                    color: diagnostics.errorCode == null
                        ? Colors.greenAccent
                        : Colors.redAccent,
                  ),
                  _buildDiagnosticsChip(
                    Icons.schedule,
                    'timestamp',
                    _diagnosticValue(diagnostics.timestamp),
                  ),
                ],
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildDiagnosticsChip(
    IconData icon,
    String label,
    String value, {
    Color color = Colors.cyanAccent,
  }) {
    return Container(
      constraints: const BoxConstraints(minWidth: 132, maxWidth: 280),
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.08),
        borderRadius: BorderRadius.circular(6),
        border: Border.all(color: color.withValues(alpha: 0.22)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, color: color, size: 16),
          const SizedBox(width: 8),
          Flexible(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  label,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(color: Colors.white38, fontSize: 10),
                ),
                const SizedBox(height: 2),
                Text(
                  value,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: color,
                    fontSize: 12,
                    fontWeight: FontWeight.w700,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatusChip(String status) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.cyanAccent.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(6),
      ),
      child: Text(
        status,
        style: const TextStyle(
          color: Colors.cyanAccent,
          fontSize: 11,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  Widget _buildEmptyTasks() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: const Color(0xFF14142B),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: const Color(0xFF222244)),
      ),
      child: const Row(
        children: [
          Icon(Icons.check_circle_outline, color: Colors.greenAccent),
          SizedBox(width: 16),
          Expanded(
            child: Text(
              'No active tasks. All tasks are idle.',
              style: TextStyle(color: Colors.white54, fontSize: 14),
            ),
          ),
        ],
      ),
    );
  }

  /// Non-secret failure state with a retry affordance. The underlying exception
  /// is intentionally not surfaced to avoid leaking transport/server detail.
  Widget _buildTaskError() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: const Color(0xFF2B1420),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: const Color(0xFF44222E)),
      ),
      child: Row(
        children: [
          const Icon(Icons.error_outline, color: Colors.redAccent),
          const SizedBox(width: 16),
          const Expanded(
            child: Text(
              'Failed to load tasks.',
              style: TextStyle(color: Colors.white70, fontSize: 14),
            ),
          ),
          TextButton(
            onPressed: () => setState(_reloadTasks),
            child: const Text('Retry'),
          ),
        ],
      ),
    );
  }

  Widget _buildLaunchButton(ProjectWorkspace project) {
    return ElevatedButton.icon(
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.deepPurpleAccent,
        foregroundColor: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        elevation: 6,
        shadowColor: Colors.deepPurpleAccent.withValues(alpha: 0.4),
      ),
      icon: const Icon(Icons.rocket_launch, size: 20),
      label: const Text(
        'Open Workspace',
        style: TextStyle(fontWeight: FontWeight.bold, letterSpacing: 0.5),
      ),
      onPressed: () async {
        if (widget.onLaunchCodeServer != null) {
          final success = await widget.onLaunchCodeServer!(project);
          if (success && mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('Launching ${project.name} workspace...'),
                behavior: SnackBarBehavior.floating,
              ),
            );
          }
        }
      },
    );
  }

  Color _diagnosticsStateColor(ProtoSocketConnectionState state) {
    switch (state) {
      case ProtoSocketConnectionState.connected:
        return Colors.greenAccent;
      case ProtoSocketConnectionState.connecting:
        return Colors.amberAccent;
      case ProtoSocketConnectionState.failed:
        return Colors.redAccent;
      case ProtoSocketConnectionState.disconnected:
        return Colors.white54;
    }
  }

  String _diagnosticValue(String? value, {String empty = 'n/a'}) {
    if (value == null || value.isEmpty) return empty;
    return value;
  }
}
