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

import '../../../../core/theme/app_colors.dart';
import '../../../../core/theme/app_text_styles.dart';
import '../../../../core/theme/app_spacing.dart';
import '../../../../core/theme/app_radius.dart';
import '../../../../core/widgets/fs_button.dart';
import '../../../../core/widgets/fs_empty_state.dart';
import '../../../../core/widgets/fs_error_state.dart';
import '../../../../core/widgets/fs_shimmer.dart';
import '../bloc/kb_cubit.dart';
import '../bloc/kb_state.dart';

class KBListScreen extends StatefulWidget {
  const KBListScreen({super.key});

  @override
  State<KBListScreen> createState() => _KBListScreenState();
}

class _KBListScreenState extends State<KBListScreen> {
  late final KBCubit _cubit;

  @override
  void initState() {
    super.initState();
    _cubit = KBCubit()..loadKnowledgeBases();
  }

  @override
  void dispose() {
    _cubit.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider.value(
      value: _cubit,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Knowledge Base'),
          actions: [
            IconButton(
              icon: const Icon(Icons.refresh, size: 20),
              onPressed: () => _cubit.loadKnowledgeBases(),
              tooltip: 'Refresh',
            ),
          ],
        ),
        floatingActionButton: FloatingActionButton.extended(
          onPressed: () => context.push('/app/more/kb/upload'),
          backgroundColor: AppColors.accent,
          icon: const Icon(Icons.upload_file, color: Colors.white),
          label: Text('Upload',
              style: AppTextStyles.labelMedium.copyWith(color: Colors.white)),
        ),
        body: BlocBuilder<KBCubit, KBState>(
          builder: (context, state) {
            if (state is KBLoading) {
              return Padding(
                padding: AppSpacing.screenAll,
                child: FSShimmerList(itemCount: 5),
              );
            }

            if (state is KBError) {
              return FSErrorState(
                message: state.message,
                onRetry: () => _cubit.loadKnowledgeBases(),
              );
            }

            if (state is KBLoaded) {
              if (state.knowledgeBases.isEmpty) {
                return const FSEmptyState(
                  icon: '🧠',
                  title: 'No Knowledge Bases',
                  subtitle:
                      'Upload PDFs, documents, or URLs to create a knowledge base that grounds AI responses.',
                );
              }

              return RefreshIndicator(
                color: AppColors.accent,
                backgroundColor: AppColors.panel,
                onRefresh: () => _cubit.loadKnowledgeBases(),
                child: ListView.separated(
                  padding: AppSpacing.screenAll,
                  itemCount: state.knowledgeBases.length,
                  separatorBuilder: (_, __) => const SizedBox(height: 10),
                  itemBuilder: (context, index) {
                    final kb = state.knowledgeBases[index];
                    return _buildKBCard(kb);
                  },
                ),
              );
            }

            return const SizedBox.shrink();
          },
        ),
      ),
    );
  }

  Widget _buildKBCard(String name) {
    return Container(
      padding: AppSpacing.cardInner,
      decoration: BoxDecoration(
        color: AppColors.panel,
        border: Border.all(color: AppColors.border),
        borderRadius: AppRadius.mdAll,
      ),
      child: Row(
        children: [
          Container(
            width: 44,
            height: 44,
            decoration: BoxDecoration(
              color: AppColors.purpleBg,
              borderRadius: AppRadius.smAll,
            ),
            alignment: Alignment.center,
            child: const Text('🧠', style: TextStyle(fontSize: 22)),
          ),
          const SizedBox(width: 14),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(name, style: AppTextStyles.titleSmall),
                const SizedBox(height: 2),
                Text(
                  'ChromaDB Collection',
                  style: AppTextStyles.caption,
                ),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
            decoration: BoxDecoration(
              color: AppColors.successBg,
              borderRadius: AppRadius.pill,
            ),
            child: Text(
              'ACTIVE',
              style: TextStyle(
                color: AppColors.successLight,
                fontSize: 9,
                fontWeight: FontWeight.w700,
                letterSpacing: 0.5,
              ),
            ),
          ),
        ],
      ),
    );
  }
}