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

class OtoJobsSurface extends StatefulWidget {
  final OtoSurfaceSnapshot<List<OtoJobViewModel>> snapshot;
  final OtoConsoleThemeAdapter? themeAdapter;
  final ValueChanged<String>? onExecutionTap;
  final OtoActionViewState? jobCreateState;
  final bool showCreateForm;
  final bool createOnly;
  final ValueChanged<OtoJobCreateDraft>? onCreateJob;

  const OtoJobsSurface({
    super.key,
    required this.snapshot,
    this.themeAdapter,
    this.onExecutionTap,
    this.jobCreateState,
    this.showCreateForm = true,
    this.createOnly = false,
    this.onCreateJob,
  });

  @override
  State<OtoJobsSurface> createState() => _OtoJobsSurfaceState();
}

class _OtoJobsSurfaceState extends State<OtoJobsSurface> {
  final TextEditingController _idController = TextEditingController();
  final TextEditingController _nameController = TextEditingController();

  @override
  void dispose() {
    _idController.dispose();
    _nameController.dispose();
    super.dispose();
  }

  void _submitJobCreate() {
    final draft = OtoJobCreateDraft(
      id: _idController.text.trim(),
      name: _nameController.text.trim(),
    );
    if (draft.isValid && widget.onCreateJob != null) {
      widget.onCreateJob!(draft);
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = widget.themeAdapter ?? const OtoConsoleThemeAdapter();
    final jobCount = widget.snapshot.data?.length ?? 0;
    final showCreateForm =
        widget.showCreateForm && widget.jobCreateState != null;
    final title = widget.createOnly ? 'New Item' : 'Pipelines / Jobs';
    final icon = widget.createOnly
        ? Icons.add_circle_outline
        : Icons.account_tree_outlined;
    return Container(
      color: theme.backgroundColor,
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              Icon(icon, color: theme.primaryColor, size: 24),
              const SizedBox(width: 12),
              Expanded(
                child: Text(
                  title,
                  style: TextStyle(
                    color: theme.textColor,
                    fontSize: 24,
                    fontWeight: FontWeight.w800,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          if (!widget.createOnly) ...[
            _BuildContextStrip(theme: theme, jobCount: jobCount),
            const SizedBox(height: 20),
          ],
          if (showCreateForm) ...[
            _CreatePanel(
              theme: theme,
              child: _buildJobCreateForm(context, theme),
            ),
            const SizedBox(height: 20),
          ],
          if (!widget.createOnly)
            Expanded(child: _buildContent(context, theme))
          else if (!showCreateForm)
            Expanded(child: _buildCreateUnavailableState(theme)),
        ],
      ),
    );
  }

  Widget _buildJobCreateForm(
    BuildContext context,
    OtoConsoleThemeAdapter theme,
  ) {
    final createState = widget.jobCreateState!;
    final isEnabled = !createState.isSubmitting;
    final canSubmit =
        _idController.text.trim().isNotEmpty &&
        _nameController.text.trim().isNotEmpty &&
        isEnabled;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Text(
          'New Item',
          style: TextStyle(
            color: theme.primaryColor,
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            Expanded(
              flex: 1,
              child: TextField(
                controller: _idController,
                enabled: isEnabled,
                decoration: const InputDecoration(
                  labelText: 'Job ID',
                  border: OutlineInputBorder(),
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 12,
                    vertical: 8,
                  ),
                  floatingLabelBehavior: FloatingLabelBehavior.never,
                ),
                onChanged: (_) => setState(() {}),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              flex: 2,
              child: TextField(
                controller: _nameController,
                enabled: isEnabled,
                decoration: const InputDecoration(
                  labelText: 'Job Name',
                  border: OutlineInputBorder(),
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 12,
                    vertical: 8,
                  ),
                  floatingLabelBehavior: FloatingLabelBehavior.never,
                ),
                onChanged: (_) => setState(() {}),
              ),
            ),
            const SizedBox(width: 12),
            ElevatedButton(
              onPressed: canSubmit ? _submitJobCreate : null,
              style: ElevatedButton.styleFrom(
                backgroundColor: theme.primaryColor,
                foregroundColor: theme.backgroundColor,
                padding: const EdgeInsets.symmetric(
                  horizontal: 24,
                  vertical: 8,
                ),
              ),
              child: createState.isSubmitting
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  : const Text('Create'),
            ),
          ],
        ),
        if (createState.isSuccess || createState.isFailed) ...[
          const SizedBox(height: 8),
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: createState.isSuccess
                  ? theme.primaryColor.withValues(alpha: 0.1)
                  : Colors.red.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(4),
              border: Border.all(
                color: createState.isSuccess
                    ? theme.primaryColor.withValues(alpha: 0.3)
                    : Colors.red.withValues(alpha: 0.3),
              ),
            ),
            child: Text(
              createState.message ??
                  (createState.isSuccess ? 'Job created' : 'Job create failed'),
              style: TextStyle(
                color: createState.isSuccess ? theme.primaryColor : Colors.red,
                fontSize: 13,
              ),
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildContent(BuildContext context, OtoConsoleThemeAdapter theme) {
    switch (widget.snapshot.state) {
      case OtoSurfaceLoadState.loading:
        return const Center(child: CircularProgressIndicator());
      case OtoSurfaceLoadState.empty:
        return _buildEmptyState(theme);
      case OtoSurfaceLoadState.error:
        return _buildErrorState(theme);
      case OtoSurfaceLoadState.data:
        final jobs = widget.snapshot.data ?? [];
        if (jobs.isEmpty) {
          return _buildEmptyState(theme);
        }
        return _JenkinsJobDashboard(
          jobs: jobs,
          onExecutionTap: widget.onExecutionTap,
          theme: theme,
        );
    }
  }

  Widget _buildEmptyState(OtoConsoleThemeAdapter theme) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Container(
          padding: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            color: theme.railBackgroundColor,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: theme.borderColor),
          ),
          child: Row(
            children: [
              Icon(
                Icons.account_tree_outlined,
                color: theme.primaryColor,
                size: 32,
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'No pipeline jobs',
                      style: TextStyle(
                        color: theme.textColor,
                        fontSize: 18,
                        fontWeight: FontWeight.w800,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      'Job queue is empty.',
                      style: TextStyle(color: theme.textSecondaryColor),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildErrorState(OtoConsoleThemeAdapter theme) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Container(
          padding: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            color: Colors.red.withValues(alpha: 0.1),
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: Colors.red.withValues(alpha: 0.5)),
          ),
          child: Row(
            children: [
              const Icon(Icons.error_outline, color: Colors.red, size: 32),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Error loading jobs',
                      style: TextStyle(
                        color: theme.textColor,
                        fontSize: 18,
                        fontWeight: FontWeight.w800,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      widget.snapshot.errorMessage ??
                          'An unknown error occurred.',
                      style: TextStyle(color: theme.textSecondaryColor),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildCreateUnavailableState(OtoConsoleThemeAdapter theme) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: theme.railBackgroundColor,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: theme.borderColor),
      ),
      child: Row(
        children: [
          Icon(Icons.add_circle_outline, color: theme.primaryColor, size: 32),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Pipeline creation unavailable',
                  style: TextStyle(
                    color: theme.textColor,
                    fontSize: 18,
                    fontWeight: FontWeight.w800,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  'No create surface is mounted.',
                  style: TextStyle(color: theme.textSecondaryColor),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

/// Build Queue / Build History context strip shown above the job table.
/// Queue depth has no OTO Core data source yet (out of scope for this
/// pass), so it renders a structural placeholder count.
class _BuildContextStrip extends StatelessWidget {
  final OtoConsoleThemeAdapter theme;
  final int jobCount;

  const _BuildContextStrip({required this.theme, required this.jobCount});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        _ContextChip(
          icon: Icons.queue_outlined,
          label: 'Build Queue',
          value: '0',
          theme: theme,
        ),
        const SizedBox(width: 12),
        _ContextChip(
          icon: Icons.history,
          label: 'Build History',
          value: '$jobCount',
          theme: theme,
        ),
      ],
    );
  }
}

class _ContextChip extends StatelessWidget {
  final IconData icon;
  final String label;
  final String value;
  final OtoConsoleThemeAdapter theme;

  const _ContextChip({
    required this.icon,
    required this.label,
    required this.value,
    required this.theme,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: theme.railBackgroundColor,
        borderRadius: BorderRadius.circular(6),
        border: Border.all(color: theme.borderColor),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, color: theme.textSecondaryColor, size: 14),
          const SizedBox(width: 6),
          Text(
            label,
            style: TextStyle(
              color: theme.textSecondaryColor,
              fontSize: 12,
              fontWeight: FontWeight.w700,
            ),
          ),
          const SizedBox(width: 6),
          Text(
            value,
            style: TextStyle(
              color: theme.textColor,
              fontSize: 12,
              fontWeight: FontWeight.w800,
            ),
          ),
        ],
      ),
    );
  }
}

class _CreatePanel extends StatelessWidget {
  final Widget child;
  final OtoConsoleThemeAdapter theme;

  const _CreatePanel({required this.child, 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: child,
    );
  }
}

/// Jenkins Dashboard-style job table: header row + dense job rows. Replaces
/// the former card-style ListView of `_RecordRow`.
class _JenkinsJobDashboard extends StatelessWidget {
  final List<OtoJobViewModel> jobs;
  final ValueChanged<String>? onExecutionTap;
  final OtoConsoleThemeAdapter theme;

  const _JenkinsJobDashboard({
    required this.jobs,
    this.onExecutionTap,
    required this.theme,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        _JobTableHeader(theme: theme),
        Expanded(
          child: ListView.separated(
            itemCount: jobs.length,
            separatorBuilder: (context, index) =>
                Divider(height: 1, color: theme.borderColor),
            itemBuilder: (context, index) => _JobTableRow(
              job: jobs[index],
              onExecutionTap: onExecutionTap,
              theme: theme,
            ),
          ),
        ),
      ],
    );
  }
}

class _JobTableHeader extends StatelessWidget {
  final OtoConsoleThemeAdapter theme;

  const _JobTableHeader({required this.theme});

  @override
  Widget build(BuildContext context) {
    final style = TextStyle(
      color: theme.textSecondaryColor,
      fontSize: 12,
      fontWeight: FontWeight.w800,
    );
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      decoration: BoxDecoration(
        color: theme.railBackgroundColor,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(8)),
        border: Border.all(color: theme.borderColor),
      ),
      child: Row(
        children: [
          Expanded(flex: 3, child: Text('Name', style: style)),
          Expanded(flex: 2, child: Text('Status', style: style)),
          Expanded(flex: 2, child: Text('Last Run', style: style)),
          Expanded(flex: 2, child: Text('Updated', style: style)),
          Expanded(flex: 3, child: Text('Actions', style: style)),
        ],
      ),
    );
  }
}

class _JobTableRow extends StatelessWidget {
  final OtoJobViewModel job;
  final ValueChanged<String>? onExecutionTap;
  final OtoConsoleThemeAdapter theme;

  const _JobTableRow({
    required this.job,
    this.onExecutionTap,
    required this.theme,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: theme.railBackgroundColor,
        border: Border(
          left: BorderSide(color: theme.borderColor),
          right: BorderSide(color: theme.borderColor),
        ),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            flex: 3,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  job.name,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: theme.textColor,
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  'Job ID: ${job.jobID}',
                  style: TextStyle(
                    color: theme.textSecondaryColor,
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            flex: 2,
            child: _StatusBadge(state: job.state, theme: theme),
          ),
          Expanded(
            flex: 2,
            child: job.executionID.isNotEmpty
                ? _ExecutionLink(
                    executionID: job.executionID,
                    onTap: onExecutionTap,
                    theme: theme,
                  )
                : Text(
                    '-',
                    style: TextStyle(
                      color: theme.textSecondaryColor,
                      fontSize: 12,
                    ),
                  ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              job.updatedAt,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: theme.textSecondaryColor, fontSize: 12),
            ),
          ),
          Expanded(
            flex: 3,
            child: _JobTaskMenu(
              job: job,
              onExecutionTap: onExecutionTap,
              theme: theme,
            ),
          ),
        ],
      ),
    );
  }
}

class _ExecutionLink extends StatelessWidget {
  final String executionID;
  final ValueChanged<String>? onTap;
  final OtoConsoleThemeAdapter theme;

  const _ExecutionLink({
    required this.executionID,
    this.onTap,
    required this.theme,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () => onTap?.call(executionID),
      borderRadius: BorderRadius.circular(4),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
        decoration: BoxDecoration(
          color: theme.primaryColor.withValues(alpha: 0.08),
          borderRadius: BorderRadius.circular(4),
          border: Border.all(color: theme.primaryColor.withValues(alpha: 0.2)),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.play_circle_outline,
              color: theme.primaryColor,
              size: 14,
            ),
            const SizedBox(width: 6),
            Flexible(
              child: Text(
                'Execution: $executionID',
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: theme.primaryColor,
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// Job-context task menu limited to the primitives directly applicable to
/// OTO today: `Status`, `Build History`, `Stages`. `Build Now`/`Configure`
/// are intentionally not implemented (no job dispatch/config contract yet).
class _JobTaskMenu extends StatelessWidget {
  final OtoJobViewModel job;
  final ValueChanged<String>? onExecutionTap;
  final OtoConsoleThemeAdapter theme;

  const _JobTaskMenu({
    required this.job,
    this.onExecutionTap,
    required this.theme,
  });

  @override
  Widget build(BuildContext context) {
    final hasExecution = job.executionID.isNotEmpty;
    return Wrap(
      spacing: 4,
      runSpacing: 2,
      children: [
        _TaskMenuChip(
          label: 'Status',
          enabled: true,
          onTap: null,
          theme: theme,
        ),
        _TaskMenuChip(
          label: 'Build History',
          enabled: hasExecution,
          onTap: hasExecution
              ? () => onExecutionTap?.call(job.executionID)
              : null,
          theme: theme,
        ),
        _TaskMenuChip(
          label: 'Stages',
          enabled: hasExecution,
          onTap: hasExecution
              ? () => onExecutionTap?.call(job.executionID)
              : null,
          theme: theme,
        ),
      ],
    );
  }
}

class _TaskMenuChip extends StatelessWidget {
  final String label;
  final bool enabled;
  final VoidCallback? onTap;
  final OtoConsoleThemeAdapter theme;

  const _TaskMenuChip({
    required this.label,
    required this.enabled,
    this.onTap,
    required this.theme,
  });

  @override
  Widget build(BuildContext context) {
    final color = enabled
        ? theme.primaryColor
        : theme.textSecondaryColor.withValues(alpha: 0.5);
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(4),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
        child: Text(
          label,
          style: TextStyle(
            color: color,
            fontSize: 12,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    );
  }
}

class _StatusBadge extends StatelessWidget {
  final String state;
  final OtoConsoleThemeAdapter theme;

  const _StatusBadge({required this.state, required this.theme});

  @override
  Widget build(BuildContext context) {
    Color color;
    switch (state.toLowerCase()) {
      case 'queued':
        color = theme.textSecondaryColor;
        break;
      case 'running':
        color = theme.accentColor;
        break;
      case 'succeeded':
        color = theme.primaryColor;
        break;
      case 'failed':
        color = Colors.red;
        break;
      case 'canceled':
        color = Colors.orange;
        break;
      default:
        color = theme.textSecondaryColor;
        break;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.12),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withValues(alpha: 0.5)),
      ),
      child: Text(
        state.toUpperCase(),
        style: TextStyle(
          color: color,
          fontSize: 11,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}
