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 ValueChanged<OtoJobCreateDraft>? onCreateJob;

  const OtoJobsSurface({
    super.key,
    required this.snapshot,
    this.themeAdapter,
    this.onExecutionTap,
    this.jobCreateState,
    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();
    return Container(
      color: theme.backgroundColor,
      padding: const EdgeInsets.all(24),
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 820),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(
                    Icons.account_tree_outlined,
                    color: theme.primaryColor,
                    size: 24,
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      'Pipelines / Jobs',
                      style: TextStyle(
                        color: theme.textColor,
                        fontSize: 24,
                        fontWeight: FontWeight.w800,
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20),
              if (widget.jobCreateState != null) ...[
                _buildJobCreateForm(context, theme),
                const SizedBox(height: 20),
              ],
              Expanded(child: _buildContent(context, 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(
          'Create New Job',
          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 _buildJobsList(context, theme, jobs);
    }
  }

  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 _buildJobsList(
    BuildContext context,
    OtoConsoleThemeAdapter theme,
    List<OtoJobViewModel> jobs,
  ) {
    return ListView.separated(
      itemCount: jobs.length,
      separatorBuilder: (context, index) => const SizedBox(height: 12),
      itemBuilder: (context, index) {
        final job = jobs[index];
        return Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: theme.railBackgroundColor,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: theme.borderColor),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(
                      job.name,
                      style: TextStyle(
                        color: theme.textColor,
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  const SizedBox(width: 8),
                  _StatusBadge(state: job.state, theme: theme),
                ],
              ),
              const SizedBox(height: 8),
              Text(
                'Job ID: ${job.jobID}',
                style: TextStyle(color: theme.textSecondaryColor, fontSize: 13),
              ),
              const SizedBox(height: 4),
              Row(
                children: [
                  Expanded(
                    child: Text(
                      'Created: ${job.createdAt}',
                      style: TextStyle(color: theme.textSecondaryColor, fontSize: 12),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Text(
                      'Updated: ${job.updatedAt}',
                      style: TextStyle(color: theme.textSecondaryColor, fontSize: 12),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
              if (job.executionID.isNotEmpty) ...[
                const SizedBox(height: 12),
                InkWell(
                  onTap: () => widget.onExecutionTap?.call(job.executionID),
                  borderRadius: BorderRadius.circular(4),
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 8,
                    ),
                    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: 16,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          'Execution: ${job.executionID}',
                          style: TextStyle(
                            color: theme.primaryColor,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ],
          ),
        );
      },
    );
  }
}

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