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

enum NomadWorkbenchSection {
  workspace,
  workflow,
  terminal,
  review,
  webContext,
  settings,
  iop,
}

class NomadCodeWorkbenchShell extends StatefulWidget {
  final Widget workspace;
  final Widget? iopContent;

  const NomadCodeWorkbenchShell({
    super.key,
    required this.workspace,
    this.iopContent,
  });

  @override
  State<NomadCodeWorkbenchShell> createState() =>
      _NomadCodeWorkbenchShellState();
}

class _NomadCodeWorkbenchShellState extends State<NomadCodeWorkbenchShell> {
  NomadWorkbenchSection _section = NomadWorkbenchSection.workspace;
  bool _agentOpen = false;

  void _select(NomadWorkbenchSection section) {
    setState(() {
      _section = section;
      _agentOpen = false;
    });
  }

  void _toggleAgent() {
    setState(() {
      _agentOpen = !_agentOpen;
    });
  }

  @override
  Widget build(BuildContext context) {
    final compactAgentDock =
        _agentOpen && MediaQuery.sizeOf(context).width < 960;
    return Scaffold(
      backgroundColor: const Color(0xFF0F0F1A),
      body: SafeArea(
        child: Column(
          children: [
            _WorkbenchTitleBar(section: _section),
            Expanded(
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  if (!compactAgentDock) Expanded(child: _buildCenterContent()),
                  if (_agentOpen)
                    SizedBox(
                      width: _agentPanelWidth(context),
                      child: const _AgentDockPanel(),
                    ),
                  _WorkbenchActivityRail(
                    selected: _section,
                    agentOpen: _agentOpen,
                    onSelect: _select,
                    onToggleAgent: _toggleAgent,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCenterContent() {
    return switch (_section) {
      NomadWorkbenchSection.workspace => widget.workspace,
      NomadWorkbenchSection.workflow => const _WorkbenchPlaceholder(
        icon: Icons.account_tree_outlined,
        title: 'Workflow',
        subtitle: 'Workflow management surface will mount here.',
      ),
      NomadWorkbenchSection.terminal => const _WorkbenchPlaceholder(
        icon: Icons.terminal,
        title: 'Terminal',
        subtitle:
            'Remote command sessions and terminal bridges will mount here.',
      ),
      NomadWorkbenchSection.review => const _WorkbenchPlaceholder(
        icon: Icons.rate_review_outlined,
        title: 'Review',
        subtitle:
            'Diff, branch, commit, and PR review surfaces will mount here.',
      ),
      NomadWorkbenchSection.webContext => const _WorkbenchPlaceholder(
        icon: Icons.web_asset_outlined,
        title: 'Web Context',
        subtitle: 'WebView observation and control context will mount here.',
      ),
      NomadWorkbenchSection.settings => const _WorkbenchPlaceholder(
        icon: Icons.tune,
        title: 'Settings',
        subtitle: 'Workspace and integration settings will mount here.',
      ),
      NomadWorkbenchSection.iop =>
        widget.iopContent ??
            const _WorkbenchPlaceholder(
              icon: Icons.hub_outlined,
              title: 'IOP',
              subtitle:
                  'Optional IOP console package will mount here when included.',
            ),
    };
  }

  double _agentPanelWidth(BuildContext context) {
    final width = MediaQuery.sizeOf(context).width;
    if (width < 960) return (width - 60).clamp(0.0, 520.0);
    if (width < 1120) return 360;
    return 420;
  }
}

class _WorkbenchTitleBar extends StatelessWidget {
  final NomadWorkbenchSection section;

  const _WorkbenchTitleBar({required this.section});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 52,
      decoration: const BoxDecoration(
        color: Color(0xFF16162A),
        border: Border(bottom: BorderSide(color: Color(0xFF252548))),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          Container(
            width: 28,
            height: 28,
            decoration: BoxDecoration(
              color: Colors.deepPurpleAccent.withValues(alpha: 0.2),
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Icon(
              Icons.blur_on,
              color: Colors.deepPurpleAccent,
              size: 18,
            ),
          ),
          const SizedBox(width: 12),
          const Text(
            'NomadCode Console',
            style: TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.w800,
              fontSize: 16,
            ),
          ),
          const SizedBox(width: 12),
          Container(width: 1, height: 22, color: const Color(0xFF303050)),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              _sectionLabel(section),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(color: Colors.white70, fontSize: 13),
            ),
          ),
        ],
      ),
    );
  }
}

class _WorkbenchActivityRail extends StatelessWidget {
  final NomadWorkbenchSection selected;
  final bool agentOpen;
  final ValueChanged<NomadWorkbenchSection> onSelect;
  final VoidCallback onToggleAgent;

  const _WorkbenchActivityRail({
    required this.selected,
    required this.agentOpen,
    required this.onSelect,
    required this.onToggleAgent,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 60,
      decoration: const BoxDecoration(
        color: Color(0xFF111122),
        border: Border(left: BorderSide(color: Color(0xFF252548))),
      ),
      child: Column(
        children: [
          const SizedBox(height: 8),
          _RailButton(
            tooltip: 'Agent',
            icon: Icons.smart_toy_outlined,
            selected: agentOpen,
            onPressed: onToggleAgent,
          ),
          const Divider(color: Color(0xFF252548), height: 16),
          _RailButton(
            tooltip: 'Workspace',
            icon: Icons.dashboard_outlined,
            selected: selected == NomadWorkbenchSection.workspace,
            onPressed: () => onSelect(NomadWorkbenchSection.workspace),
          ),
          _RailButton(
            tooltip: 'Workflow',
            icon: Icons.account_tree_outlined,
            selected: selected == NomadWorkbenchSection.workflow,
            onPressed: () => onSelect(NomadWorkbenchSection.workflow),
          ),
          _RailButton(
            tooltip: 'Terminal',
            icon: Icons.terminal,
            selected: selected == NomadWorkbenchSection.terminal,
            onPressed: () => onSelect(NomadWorkbenchSection.terminal),
          ),
          _RailButton(
            tooltip: 'Review',
            icon: Icons.rate_review_outlined,
            selected: selected == NomadWorkbenchSection.review,
            onPressed: () => onSelect(NomadWorkbenchSection.review),
          ),
          _RailButton(
            tooltip: 'Web Context',
            icon: Icons.web_asset_outlined,
            selected: selected == NomadWorkbenchSection.webContext,
            onPressed: () => onSelect(NomadWorkbenchSection.webContext),
          ),
          const Spacer(),
          _RailButton(
            tooltip: 'Settings',
            icon: Icons.tune,
            selected: selected == NomadWorkbenchSection.settings,
            onPressed: () => onSelect(NomadWorkbenchSection.settings),
          ),
          _RailButton(
            tooltip: 'IOP',
            icon: Icons.hub_outlined,
            selected: selected == NomadWorkbenchSection.iop,
            onPressed: () => onSelect(NomadWorkbenchSection.iop),
          ),
          const SizedBox(height: 8),
        ],
      ),
    );
  }
}

class _RailButton extends StatelessWidget {
  final String tooltip;
  final IconData icon;
  final bool selected;
  final VoidCallback onPressed;

  const _RailButton({
    required this.tooltip,
    required this.icon,
    required this.selected,
    required this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    final color = selected ? Colors.cyanAccent : Colors.white60;
    return Tooltip(
      message: tooltip,
      waitDuration: const Duration(milliseconds: 500),
      child: SizedBox(
        width: 56,
        height: 48,
        child: IconButton(
          onPressed: onPressed,
          icon: Icon(icon, color: color),
          style: IconButton.styleFrom(
            backgroundColor: selected
                ? Colors.cyanAccent.withValues(alpha: 0.08)
                : Colors.transparent,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        ),
      ),
    );
  }
}

class _AgentDockPanel extends StatelessWidget {
  const _AgentDockPanel();

  static const _messages = <AgentMessage>[
    AgentMessage(
      id: 'nomad-agent-intro',
      role: AgentMessageRole.assistant,
      text:
          'NomadCode agent is docked to the right rail. Workflow, Web Context, and optional IOP capabilities can be registered here.',
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Color(0xFF141426),
        border: Border(left: BorderSide(color: Color(0xFF252548))),
      ),
      child: const AgentShell(
        messages: _messages,
        placeholder: 'Ask the workspace agent',
      ),
    );
  }
}

class _WorkbenchPlaceholder extends StatelessWidget {
  final IconData icon;
  final String title;
  final String subtitle;

  const _WorkbenchPlaceholder({
    required this.icon,
    required this.title,
    required this.subtitle,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xFF0F0F1A),
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 460),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(icon, color: Colors.cyanAccent, size: 40),
              const SizedBox(height: 16),
              Text(
                title,
                textAlign: TextAlign.center,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 22,
                  fontWeight: FontWeight.w800,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                subtitle,
                textAlign: TextAlign.center,
                style: const TextStyle(color: Colors.white54, fontSize: 14),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

String _sectionLabel(NomadWorkbenchSection section) {
  return switch (section) {
    NomadWorkbenchSection.workspace => 'Workspace',
    NomadWorkbenchSection.workflow => 'Workflow',
    NomadWorkbenchSection.terminal => 'Terminal',
    NomadWorkbenchSection.review => 'Review',
    NomadWorkbenchSection.webContext => 'Web Context',
    NomadWorkbenchSection.settings => 'Settings',
    NomadWorkbenchSection.iop => 'IOP Management',
  };
}
