import 'package:flutter/material.dart';

import 'oto_console_contract.dart';

class OtoConsoleOverview extends StatelessWidget {
  final OtoConsoleConfig config;
  final OtoCoreConnectionSnapshot connection;
  final VoidCallback? onRefresh;
  final OtoConsoleThemeAdapter? themeAdapter;
  final String? statusText;

  const OtoConsoleOverview({
    super.key,
    required this.config,
    this.connection = const OtoCoreConnectionSnapshot.checking(),
    this.onRefresh,
    this.themeAdapter,
    this.statusText,
  });

  String get _statusLabel => statusText ?? connection.label;

  @override
  Widget build(BuildContext context) {
    final theme = themeAdapter ?? const OtoConsoleThemeAdapter();
    final statusColor = _statusColor(theme, connection.state);

    return Container(
      color: theme.backgroundColor,
      padding: const EdgeInsets.all(24),
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 840),
          child: ListView(
            children: [
              LayoutBuilder(
                builder: (context, constraints) {
                  final narrow = constraints.maxWidth < 620;
                  final title = Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'OTO CONTROL PLANE',
                        style: TextStyle(
                          color: theme.primaryColor,
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                          letterSpacing: 1.8,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        'Build Operations Overview',
                        style: TextStyle(
                          color: theme.textColor,
                          fontSize: 28,
                          fontWeight: FontWeight.w800,
                        ),
                      ),
                    ],
                  );
                  final badge = _StatusBadge(
                    label: _statusLabel,
                    color: statusColor,
                  );
                  if (narrow) {
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [title, const SizedBox(height: 16), badge],
                    );
                  }
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Expanded(child: title),
                      const SizedBox(width: 24),
                      badge,
                    ],
                  );
                },
              ),
              const SizedBox(height: 32),
              _SectionHeader(
                title: 'CORE API ENDPOINTS',
                icon: Icons.lan_outlined,
                theme: theme,
              ),
              const SizedBox(height: 12),
              _EndpointTile(
                title: 'OTO Server HTTP API',
                value: config.serverHttpUrl,
                icon: Icons.http_outlined,
                theme: theme,
              ),
              const SizedBox(height: 16),
              _EndpointTile(
                title: 'OTO Server Wire',
                value: config.serverWireUrl,
                icon: Icons.swap_calls_outlined,
                theme: theme,
              ),
              if (connection.policyNote.isNotEmpty) ...[
                const SizedBox(height: 16),
                _EndpointTile(
                  title: 'Browser API Policy',
                  value: connection.policyNote,
                  icon: Icons.policy_outlined,
                  theme: theme,
                ),
              ],
              const SizedBox(height: 32),
              _SectionHeader(
                title: 'CORE CONNECTION STATUS',
                icon: Icons.monitor_heart_outlined,
                theme: theme,
              ),
              const SizedBox(height: 12),
              _ConnectionGrid(theme: theme, connection: connection),
              const SizedBox(height: 32),
              _SectionHeader(
                title: 'AUTHENTICATION',
                icon: Icons.security_outlined,
                theme: theme,
              ),
              const SizedBox(height: 12),
              _EndpointTile(
                title: 'Active Auth Token Reference',
                value: config.authTokenReference?.isNotEmpty == true
                    ? config.authTokenReference!
                    : 'None',
                icon: Icons.key_outlined,
                theme: theme,
              ),
              if (onRefresh != null) ...[
                const SizedBox(height: 32),
                Align(
                  alignment: Alignment.centerLeft,
                  child: FilledButton.icon(
                    onPressed: onRefresh,
                    icon: const Icon(Icons.refresh),
                    label: const Text('Refresh'),
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  Color _statusColor(
    OtoConsoleThemeAdapter theme,
    OtoCoreConnectionState state,
  ) {
    return switch (state) {
      OtoCoreConnectionState.checking => theme.textSecondaryColor,
      OtoCoreConnectionState.online => theme.primaryColor,
      OtoCoreConnectionState.degraded => theme.accentColor,
      OtoCoreConnectionState.offline => theme.accentColor,
    };
  }
}

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

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

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.12),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: color.withValues(alpha: 0.5)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 8,
            height: 8,
            decoration: BoxDecoration(color: color, shape: BoxShape.circle),
          ),
          const SizedBox(width: 8),
          Flexible(
            child: Text(
              label.toUpperCase(),
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
              style: TextStyle(
                color: color,
                fontSize: 12,
                fontWeight: FontWeight.w800,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _SectionHeader extends StatelessWidget {
  final String title;
  final IconData icon;
  final OtoConsoleThemeAdapter theme;

  const _SectionHeader({
    required this.title,
    required this.icon,
    required this.theme,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Icon(icon, color: theme.primaryColor, size: 18),
        const SizedBox(width: 8),
        Expanded(
          child: Text(
            title,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: theme.textSecondaryColor,
              fontSize: 12,
              fontWeight: FontWeight.w800,
            ),
          ),
        ),
      ],
    );
  }
}

class _EndpointTile extends StatelessWidget {
  final String title;
  final String value;
  final IconData icon;
  final OtoConsoleThemeAdapter theme;

  const _EndpointTile({
    required this.title,
    required this.value,
    required this.icon,
    required this.theme,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: theme.railBackgroundColor,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: theme.borderColor),
      ),
      child: Row(
        children: [
          Icon(icon, color: theme.primaryColor, size: 22),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: theme.textSecondaryColor,
                    fontSize: 12,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  value,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                  style: TextStyle(
                    color: theme.textColor,
                    fontSize: 15,
                    fontWeight: FontWeight.w700,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _ConnectionGrid extends StatelessWidget {
  final OtoConsoleThemeAdapter theme;
  final OtoCoreConnectionSnapshot connection;

  const _ConnectionGrid({required this.theme, required this.connection});

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final narrow = constraints.maxWidth < 620;
        final tiles = [
          _EndpointStatusTile(
            status: connection.health,
            color: _endpointColor(connection.health),
            theme: theme,
          ),
          _EndpointStatusTile(
            status: connection.readiness,
            color: _endpointColor(connection.readiness),
            theme: theme,
          ),
        ];
        if (narrow) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [tiles[0], const SizedBox(height: 16), tiles[1]],
          );
        }
        return Row(
          children: [
            Expanded(child: tiles[0]),
            const SizedBox(width: 16),
            Expanded(child: tiles[1]),
          ],
        );
      },
    );
  }

  Color _endpointColor(OtoCoreEndpointStatus status) {
    return switch (status.state) {
      OtoCoreConnectionState.checking => theme.textSecondaryColor,
      OtoCoreConnectionState.online => theme.primaryColor,
      OtoCoreConnectionState.degraded => theme.accentColor,
      OtoCoreConnectionState.offline => theme.accentColor,
    };
  }
}

class _EndpointStatusTile extends StatelessWidget {
  final OtoCoreEndpointStatus status;
  final Color color;
  final OtoConsoleThemeAdapter theme;

  const _EndpointStatusTile({
    required this.status,
    required this.color,
    required this.theme,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.08),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: color.withValues(alpha: 0.25)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            status.label,
            style: TextStyle(color: theme.textSecondaryColor, fontSize: 12),
          ),
          const SizedBox(height: 6),
          Text(
            status.ok ? 'OK' : status.message,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
            style: TextStyle(
              color: color,
              fontSize: 18,
              fontWeight: FontWeight.w800,
            ),
          ),
          const SizedBox(height: 6),
          Text(
            status.statusCode == null
                ? status.path
                : '${status.path} - HTTP ${status.statusCode}',
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
            style: TextStyle(color: theme.textSecondaryColor, fontSize: 12),
          ),
        ],
      ),
    );
  }
}
