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

import '../../../core/chat/chat_request_notifier.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 RequestHistoryScreen extends ConsumerWidget {
  const RequestHistoryScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(requestHistoryProvider);

    return Scaffold(
      appBar: AppBar(title: const Text('Riwayat Permintaan')),
      body: RefreshIndicator(
        onRefresh: () => ref.read(requestHistoryProvider.notifier).refresh(),
        child: state.when(
          loading: () => const _CenterScroll(child: CircularProgressIndicator()),
          error: (err, _) => _CenterScroll(
            child: Padding(
              padding: const EdgeInsets.all(24),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Icon(Icons.error_outline, size: 48, color: Colors.grey),
                  const SizedBox(height: 12),
                  const Text('Gagal memuat riwayat'),
                  const SizedBox(height: 12),
                  TextButton(
                    onPressed: () =>
                        ref.read(requestHistoryProvider.notifier).refresh(),
                    child: const Text('Coba lagi'),
                  ),
                ],
              ),
            ),
          ),
          data: (entries) {
            if (entries.isEmpty) {
              return const _CenterScroll(
                child: Padding(
                  padding: EdgeInsets.all(24),
                  child: Text('Belum ada permintaan chat'),
                ),
              );
            }
            return ListView.separated(
              physics: const AlwaysScrollableScrollPhysics(),
              padding: const EdgeInsets.symmetric(vertical: 8),
              itemCount: entries.length,
              separatorBuilder: (_, __) => const Divider(height: 1),
              itemBuilder: (context, index) => _RequestRow(entries[index]),
            );
          },
        ),
      ),
    );
  }
}

class _CenterScroll extends StatelessWidget {
  final Widget child;
  const _CenterScroll({required this.child});

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, c) => SingleChildScrollView(
        physics: const AlwaysScrollableScrollPhysics(),
        child: SizedBox(
          height: c.maxHeight,
          child: Center(child: child),
        ),
      ),
    );
  }
}

class _RequestRow extends ConsumerWidget {
  final RequestHistoryEntry entry;
  const _RequestRow(this.entry);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final status = labelFor(entry);
    return ListTile(
      title: Row(
        children: [
          Flexible(
            child: Text(
              entry.customerCallName,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(fontWeight: FontWeight.w600),
            ),
          ),
          if (entry.topicSensitivity == TopicSensitivity.sensitive) ...[
            const SizedBox(width: 8),
            const SensitivityBadge(
              sensitivity: TopicSensitivity.sensitive,
              fontSize: 10,
            ),
          ],
        ],
      ),
      subtitle: Padding(
        padding: const EdgeInsets.only(top: 4),
        child: Row(
          children: [
            Container(
              padding:
                  const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
              decoration: BoxDecoration(
                color: status.background,
                borderRadius: BorderRadius.circular(999),
              ),
              child: Text(
                status.label,
                style: TextStyle(
                  fontSize: 11,
                  color: status.foreground,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
            const SizedBox(width: 8),
            Text(
              formatRelative(entry.notifiedAt),
              style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
            ),
          ],
        ),
      ),
      trailing: const Icon(Icons.chevron_right),
      onTap: () => _onTap(context, ref),
    );
  }

  Future<void> _onTap(BuildContext context, WidgetRef ref) async {
    if (entry.isPending) {
      await ref
          .read(chatRequestProvider.notifier)
          .setIncomingFromNotification(entry.sessionId);
    } else {
      context.push('/chat/requests/history/${entry.notificationId}');
    }
  }
}
