import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../../../core/chat/widgets/sensitivity_badge.dart';
import '../../../core/constants.dart';
import '../models/request_history_entry.dart';
import '../notifiers/request_history_notifier.dart';
import '../utils/request_status_label.dart';

class RequestHistoryDetailScreen extends ConsumerWidget {
  final String notificationId;
  const RequestHistoryDetailScreen({super.key, required this.notificationId});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(requestHistoryProvider);
    final entry = state.valueOrNull == null
        ? null
        : ref.read(requestHistoryProvider.notifier).findById(notificationId);

    return Scaffold(
      appBar: AppBar(title: const Text('Detail Permintaan')),
      body: state.isLoading && entry == null
          ? const Center(child: CircularProgressIndicator())
          : entry == null
              ? _NotFound(
                  onRetry: () =>
                      ref.read(requestHistoryProvider.notifier).refresh(),
                )
              : _Detail(entry: entry),
    );
  }
}

class _NotFound extends StatelessWidget {
  final VoidCallback onRetry;
  const _NotFound({required this.onRetry});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.search_off, size: 48, color: Colors.grey),
            const SizedBox(height: 12),
            const Text('Permintaan tidak ditemukan'),
            const SizedBox(height: 12),
            TextButton(onPressed: onRetry, child: const Text('Muat ulang')),
          ],
        ),
      ),
    );
  }
}

class _Detail extends StatelessWidget {
  final RequestHistoryEntry entry;
  const _Detail({required this.entry});

  @override
  Widget build(BuildContext context) {
    final status = labelFor(entry);
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Card(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Flexible(
                    child: Text(
                      entry.customerCallName,
                      style: const TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  if (entry.topicSensitivity == TopicSensitivity.sensitive) ...[
                    const SizedBox(width: 8),
                    const SensitivityBadge(
                      sensitivity: TopicSensitivity.sensitive,
                      fontSize: 11,
                    ),
                  ],
                ],
              ),
              const SizedBox(height: 16),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                decoration: BoxDecoration(
                  color: status.background,
                  borderRadius: BorderRadius.circular(999),
                ),
                child: Text(
                  status.label,
                  style: TextStyle(
                    fontSize: 12,
                    color: status.foreground,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
              const Divider(height: 32),
              _LabeledRow('Diterima notifikasi', formatAbsolute(entry.notifiedAt)),
              if (entry.respondedAt != null) ...[
                const SizedBox(height: 8),
                _LabeledRow(
                  'Direspon pada',
                  formatAbsolute(entry.respondedAt!),
                ),
              ],
              if (entry.response == RequestResponse.accepted) ...[
                const SizedBox(height: 24),
                SizedBox(
                  width: double.infinity,
                  child: FilledButton.icon(
                    icon: const Icon(Icons.chat_bubble_outline),
                    label: const Text('Lihat percakapan'),
                    onPressed: () =>
                        context.push('/chat/history/${entry.sessionId}'),
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}

class _LabeledRow extends StatelessWidget {
  final String label;
  final String value;
  const _LabeledRow(this.label, this.value);

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: 140,
          child: Text(label, style: TextStyle(color: Colors.grey.shade700)),
        ),
        Expanded(child: Text(value)),
      ],
    );
  }
}
