import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/material.dart';
import 'package:mam_core/mam_core.dart';

import '../theme/app_theme.dart';

class SessionTable extends StatelessWidget {
  final List<SessionRow> sessions;
  final String? selectedName;
  final ValueChanged<String> onSelect;

  const SessionTable({
    super.key,
    required this.sessions,
    required this.selectedName,
    required this.onSelect,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: AppColors.border),
      ),
      clipBehavior: Clip.antiAlias,
      child: DataTable2(
        columnSpacing: 16,
        horizontalMargin: 16,
        minWidth: 900,
        headingRowColor: WidgetStateProperty.all(AppColors.surfaceAlt),
        headingTextStyle: const TextStyle(
          color: AppColors.textSecondary,
          fontWeight: FontWeight.w700,
          fontSize: 12,
          letterSpacing: 0.6,
        ),
        dataRowHeight: 44,
        empty: const Center(
          child: Text(
            '(no sessions registered)',
            style: TextStyle(color: AppColors.textSecondary),
          ),
        ),
        columns: const [
          DataColumn2(label: Text('NAME'), size: ColumnSize.L),
          DataColumn2(label: Text('SERVER'), size: ColumnSize.S),
          DataColumn2(label: Text('YAML'), size: ColumnSize.S),
          DataColumn2(label: Text('TMUX'), size: ColumnSize.S),
          DataColumn2(label: Text('CMD'), size: ColumnSize.S),
          DataColumn2(label: Text('RESUME'), size: ColumnSize.S),
          DataColumn2(label: Text('JOB_ID'), size: ColumnSize.S),
          DataColumn2(label: Text('JOB_STATUS'), size: ColumnSize.S),
          DataColumn2(label: Text('DRIFT'), size: ColumnSize.S),
        ],
        rows: sessions.map((s) {
          final selected = s.name == selectedName;
          return DataRow2(
            selected: selected,
            color: selected
                ? WidgetStateProperty.all(
                    AppColors.accent.withValues(alpha: 0.16),
                  )
                : null,
            onTap: () => onSelect(s.name),
            cells: [
              DataCell(
                Text(
                  s.name,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(color: AppColors.textPrimary),
                ),
              ),
              DataCell(
                Text(
                  s.server,
                  style: const TextStyle(color: AppColors.textSecondary),
                ),
              ),
              DataCell(_StatusChip(status: s.status)),
              DataCell(_TmuxChip(alive: s.tmuxAlive)),
              DataCell(
                Text(
                  s.pane.cmd ?? '?',
                  style: const TextStyle(color: AppColors.textPrimary),
                ),
              ),
              DataCell(
                Text(
                  s.resumeState,
                  style: const TextStyle(color: AppColors.textSecondary),
                ),
              ),
              DataCell(
                Text(
                  s.jobId,
                  style: const TextStyle(color: AppColors.textSecondary),
                ),
              ),
              DataCell(
                Text(
                  s.jobStatus,
                  style: const TextStyle(color: AppColors.textSecondary),
                ),
              ),
              DataCell(
                s.hasDrift
                    ? Text(
                        s.driftClasses.join(','),
                        style: const TextStyle(
                          color: AppColors.warning,
                          fontWeight: FontWeight.w600,
                        ),
                      )
                    : const Text(
                        '-',
                        style: TextStyle(color: AppColors.textSecondary),
                      ),
              ),
            ],
          );
        }).toList(),
      ),
    );
  }
}

class _StatusChip extends StatelessWidget {
  final String status;
  const _StatusChip({required this.status});

  @override
  Widget build(BuildContext context) {
    Color color;
    switch (status) {
      case 'running':
        color = AppColors.success;
      case 'stopped':
      case 'terminated':
      case 'archived':
        color = AppColors.textSecondary;
      default:
        color = AppColors.warning;
    }
    return Text(
      status,
      style: TextStyle(color: color, fontWeight: FontWeight.w600),
    );
  }
}

class _TmuxChip extends StatelessWidget {
  final bool alive;
  const _TmuxChip({required this.alive});

  @override
  Widget build(BuildContext context) {
    return Text(
      alive ? 'alive' : 'dead',
      style: TextStyle(
        color: alive ? AppColors.success : AppColors.danger,
        fontWeight: FontWeight.w600,
      ),
    );
  }
}
