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

enum AltWorkbenchSection {
  dashboard,
  markets,
  backtests,
  portfolio,
  research,
  settings,
}

class AltWorkbenchShell extends StatefulWidget {
  final Widget dashboard;

  const AltWorkbenchShell({super.key, required this.dashboard});

  @override
  State<AltWorkbenchShell> createState() => _AltWorkbenchShellState();
}

class _AltWorkbenchShellState extends State<AltWorkbenchShell> {
  AltWorkbenchSection _section = AltWorkbenchSection.dashboard;
  bool _agentOpen = false;

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

  Widget _buildCenterContent() {
    return switch (_section) {
      AltWorkbenchSection.dashboard => widget.dashboard,
      AltWorkbenchSection.markets => const _AltPlaceholder(
        icon: Icons.candlestick_chart_outlined,
        title: 'Markets',
        subtitle:
            'Market data import, normalization, and feed status mount here.',
      ),
      AltWorkbenchSection.backtests => const _AltPlaceholder(
        icon: Icons.analytics_outlined,
        title: 'Backtests',
        subtitle:
            'Backtest run queues, reports, and scenario controls mount here.',
      ),
      AltWorkbenchSection.portfolio => const _AltPlaceholder(
        icon: Icons.account_balance_wallet_outlined,
        title: 'Portfolio',
        subtitle:
            'Portfolio exposure and execution review surfaces mount here.',
      ),
      AltWorkbenchSection.research => const _AltPlaceholder(
        icon: Icons.science_outlined,
        title: 'Research',
        subtitle:
            'Signals, notebooks, and experiment tracking surfaces mount here.',
      ),
      AltWorkbenchSection.settings => const _AltPlaceholder(
        icon: Icons.tune,
        title: 'Settings',
        subtitle: 'API endpoint and operator workspace preferences mount here.',
      ),
    };
  }

  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;
  }

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

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

class _AltTitleBar extends StatelessWidget {
  final AltWorkbenchSection section;

  const _AltTitleBar({required this.section});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 52,
      decoration: const BoxDecoration(
        color: Color(0xFFFFFFFF),
        border: Border(bottom: BorderSide(color: Color(0xFFDDE5E2))),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          Container(
            width: 28,
            height: 28,
            decoration: BoxDecoration(
              color: const Color(0xFF006C67).withValues(alpha: 0.12),
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Icon(
              Icons.show_chart,
              color: Color(0xFF006C67),
              size: 18,
            ),
          ),
          const SizedBox(width: 12),
          const Text(
            'ALT Console',
            style: TextStyle(
              color: Color(0xFF10201D),
              fontWeight: FontWeight.w800,
              fontSize: 16,
            ),
          ),
          const SizedBox(width: 12),
          Container(width: 1, height: 22, color: const Color(0xFFDDE5E2)),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              _sectionLabel(section),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(color: Color(0xFF5B6B67), fontSize: 13),
            ),
          ),
        ],
      ),
    );
  }
}

class _AltActivityRail extends StatelessWidget {
  final AltWorkbenchSection selected;
  final bool agentOpen;
  final ValueChanged<AltWorkbenchSection> onSelect;
  final VoidCallback onToggleAgent;

  const _AltActivityRail({
    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(0xFFFFFFFF),
        border: Border(left: BorderSide(color: Color(0xFFDDE5E2))),
      ),
      child: Column(
        children: [
          const SizedBox(height: 8),
          _RailButton(
            tooltip: 'Agent',
            icon: Icons.smart_toy_outlined,
            selected: agentOpen,
            onPressed: onToggleAgent,
          ),
          const Divider(color: Color(0xFFDDE5E2), height: 16),
          _RailButton(
            tooltip: 'Dashboard',
            icon: Icons.dashboard_outlined,
            selected: selected == AltWorkbenchSection.dashboard,
            onPressed: () => onSelect(AltWorkbenchSection.dashboard),
          ),
          _RailButton(
            tooltip: 'Markets',
            icon: Icons.candlestick_chart_outlined,
            selected: selected == AltWorkbenchSection.markets,
            onPressed: () => onSelect(AltWorkbenchSection.markets),
          ),
          _RailButton(
            tooltip: 'Backtests',
            icon: Icons.analytics_outlined,
            selected: selected == AltWorkbenchSection.backtests,
            onPressed: () => onSelect(AltWorkbenchSection.backtests),
          ),
          _RailButton(
            tooltip: 'Portfolio',
            icon: Icons.account_balance_wallet_outlined,
            selected: selected == AltWorkbenchSection.portfolio,
            onPressed: () => onSelect(AltWorkbenchSection.portfolio),
          ),
          _RailButton(
            tooltip: 'Research',
            icon: Icons.science_outlined,
            selected: selected == AltWorkbenchSection.research,
            onPressed: () => onSelect(AltWorkbenchSection.research),
          ),
          const Spacer(),
          _RailButton(
            tooltip: 'Settings',
            icon: Icons.tune,
            selected: selected == AltWorkbenchSection.settings,
            onPressed: () => onSelect(AltWorkbenchSection.settings),
          ),
          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 ? const Color(0xFF006C67) : const Color(0xFF687A75);
    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
                ? const Color(0xFF006C67).withValues(alpha: 0.08)
                : Colors.transparent,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
        ),
      ),
    );
  }
}

class _AltAgentDock extends StatelessWidget {
  const _AltAgentDock();

  static const _messages = <AgentMessage>[
    AgentMessage(
      id: 'alt-agent-intro',
      role: AgentMessageRole.assistant,
      text:
          'ALT agent shell is ready. Market data, backtest, portfolio, and research capabilities can be registered here.',
    ),
  ];

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

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

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

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

String _sectionLabel(AltWorkbenchSection section) {
  return switch (section) {
    AltWorkbenchSection.dashboard => 'Dashboard',
    AltWorkbenchSection.markets => 'Markets',
    AltWorkbenchSection.backtests => 'Backtests',
    AltWorkbenchSection.portfolio => 'Portfolio',
    AltWorkbenchSection.research => 'Research',
    AltWorkbenchSection.settings => 'Settings',
  };
}
