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

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

class _KV {
  final String label;
  final String value;
  final bool copyable;
  const _KV(this.label, this.value, {this.copyable = false});
}

class DetailPane extends StatelessWidget {
  final SessionRow? session;
  const DetailPane({super.key, required this.session});

  @override
  Widget build(BuildContext context) {
    final s = session;
    return DecoratedBox(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [AppColors.surface, AppColors.surfaceAlt],
        ),
        border: Border(left: BorderSide(color: AppColors.border)),
      ),
      child: s == null
          ? const _EmptyDetail()
          : DefaultTabController(
              length: 2,
              child: Column(
                children: [
                  const TabBar(
                    tabs: [
                      Tab(text: 'INFO'),
                      Tab(text: 'TERMINAL'),
                    ],
                    labelColor: AppColors.accent2,
                    unselectedLabelColor: AppColors.textSecondary,
                    indicatorColor: AppColors.accent2,
                  ),
                  Expanded(
                    child: TabBarView(
                      children: [
                        _DetailContent(session: s),
                        TerminalPane(
                          sessionName: s.name,
                          serverName: s.server,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
    );
  }
}

class _EmptyDetail extends StatelessWidget {
  const _EmptyDetail();

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Text(
        'Select a session to see details',
        style: TextStyle(color: AppColors.textSecondary),
      ),
    );
  }
}

class _DetailContent extends StatelessWidget {
  final SessionRow session;
  const _DetailContent({required this.session});

  @override
  Widget build(BuildContext context) {
    final s = session;
    return SingleChildScrollView(
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _Header(session: s),
          const SizedBox(height: 24),
          _Section(
            title: 'PANE',
            entries: [
              _KV('pid', s.pane.pid?.toString() ?? '?'),
              _KV('cwd', s.pane.cwd ?? '?'),
              _KV('cmd', s.pane.cmd ?? '?'),
              _KV('cmd_full', s.pane.cmdFull ?? '?', copyable: true),
            ],
          ),
          const SizedBox(height: 16),
          _Section(
            title: 'ATTACH',
            entries: [
              _KV('attach_command', s.attachCommand ?? '?', copyable: true),
              _KV('start_command', s.startCommand ?? '?', copyable: true),
            ],
          ),
          const SizedBox(height: 16),
          _Section(
            title: 'STATUS',
            entries: [
              _KV('last_visible_status', s.lastVisibleStatus ?? '?'),
              _KV('resume_state', s.resumeState),
              _KV('job_id', s.jobId),
              _KV('job_status', s.jobStatus),
              _KV(
                'drift_classes',
                s.driftClasses.isEmpty ? '-' : s.driftClasses.join(', '),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _Header extends StatelessWidget {
  final SessionRow session;
  const _Header({required this.session});

  @override
  Widget build(BuildContext context) {
    final s = session;
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [AppColors.accent, AppColors.accent2],
        ),
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: AppColors.accent.withValues(alpha: 0.35),
            blurRadius: 24,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            s.name,
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w700,
              color: Colors.white,
            ),
          ),
          const SizedBox(height: 10),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: [
              _Pill(text: s.status.toUpperCase()),
              _Pill(text: s.tmuxAlive ? 'TMUX ALIVE' : 'TMUX DEAD'),
              if (s.role != null) _Pill(text: s.role!.toUpperCase()),
              _Pill(text: 'SERVER: ${s.server}'),
            ],
          ),
        ],
      ),
    );
  }
}

class _Pill extends StatelessWidget {
  final String text;
  const _Pill({required this.text});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.black.withValues(alpha: 0.25),
        borderRadius: BorderRadius.circular(999),
      ),
      child: Text(
        text,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 11,
          fontWeight: FontWeight.w600,
        ),
      ),
    );
  }
}

class _Section extends StatelessWidget {
  final String title;
  final List<_KV> entries;
  const _Section({required this.title, required this.entries});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: AppColors.border),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: const TextStyle(
              color: AppColors.textSecondary,
              fontSize: 12,
              fontWeight: FontWeight.w700,
              letterSpacing: 1.2,
            ),
          ),
          const SizedBox(height: 12),
          ...entries.map((e) => _KVRow(entry: e)),
        ],
      ),
    );
  }
}

class _KVRow extends StatelessWidget {
  final _KV entry;
  const _KVRow({required this.entry});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 130,
            child: Text(
              entry.label,
              style: const TextStyle(
                color: AppColors.textSecondary,
                fontSize: 12,
              ),
            ),
          ),
          Expanded(
            child: SelectableText(
              entry.value,
              style: const TextStyle(
                color: AppColors.textPrimary,
                fontSize: 13,
                fontFamily: 'monospace',
              ),
            ),
          ),
          if (entry.copyable)
            SizedBox(
              width: 32,
              height: 32,
              child: IconButton(
                padding: EdgeInsets.zero,
                icon: const Icon(
                  Icons.copy,
                  size: 15,
                  color: AppColors.textSecondary,
                ),
                tooltip: 'Copy',
                onPressed: () =>
                    Clipboard.setData(ClipboardData(text: entry.value)),
              ),
            ),
        ],
      ),
    );
  }
}
