import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:file_picker/file_picker.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_text_field.dart';
import '../../../../core/utils/validators.dart';
import '../bloc/kb_cubit.dart';
import '../bloc/kb_state.dart';

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

  @override
  State<KBUploadScreen> createState() => _KBUploadScreenState();
}

class _KBUploadScreenState extends State<KBUploadScreen> {
  late final KBCubit _cubit;
  final _formKey = GlobalKey<FormState>();
  final _nameCtrl = TextEditingController();
  final _urlsCtrl = TextEditingController();
  List<PlatformFile> _selectedFiles = [];

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

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

  Future<void> _pickFiles() async {
    final result = await FilePicker.platform.pickFiles(
      allowMultiple: true,
      type: FileType.custom,
      allowedExtensions: ['pdf', 'txt', 'json', 'doc', 'docx'],
      withData: true,
    );

    if (result != null) {
      setState(() {
        _selectedFiles = [..._selectedFiles, ...result.files];
      });
    }
  }

  void _removeFile(int index) {
    setState(() {
      _selectedFiles.removeAt(index);
    });
  }

  void _submit() {
    if (!_formKey.currentState!.validate()) return;

    final urls = _urlsCtrl.text.trim().isNotEmpty
        ? _urlsCtrl.text
            .split(',')
            .map((u) => u.trim())
            .where((u) => u.isNotEmpty)
            .toList()
        : null;

    final fileNames =
        _selectedFiles.map((f) => f.name).toList();
    final fileBytes =
        _selectedFiles.map((f) => f.bytes!.toList()).toList();

    if ((urls == null || urls.isEmpty) && _selectedFiles.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Please add at least one file or URL'),
          backgroundColor: AppColors.error,
        ),
      );
      return;
    }

    _cubit.upload(
      kbName: _nameCtrl.text.trim(),
      urls: urls,
      fileNames: fileNames.isNotEmpty ? fileNames : null,
      fileBytes: fileBytes.isNotEmpty ? fileBytes : null,
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider.value(
      value: _cubit,
      child: Scaffold(
        appBar: AppBar(title: const Text('Upload to Knowledge Base')),
        body: BlocConsumer<KBCubit, KBState>(
          listener: (context, state) {
            if (state is KBUploadSuccess) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(state.message),
                  backgroundColor: AppColors.success,
                ),
              );
              context.pop();
            }
            if (state is KBUploadError) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(state.message),
                  backgroundColor: AppColors.error,
                ),
              );
            }
          },
          builder: (context, state) {
            final isUploading = state is KBUploading;

            return ListView(
              padding: AppSpacing.screenAll,
              children: [
                Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // KB Name
                      FSTextField(
                        label: 'Knowledge Base Name',
                        hint: 'e.g. personal_finance_101',
                        controller: _nameCtrl,
                        validator: (v) =>
                            Validators.required(v, 'KB name'),
                        enabled: !isUploading,
                      ),
                      AppSpacing.vLg,

                      // File Picker
                      Text('FILES',
                          style: AppTextStyles.labelSmall.copyWith(
                              color: AppColors.textSecondary,
                              letterSpacing: 1)),
                      const SizedBox(height: 6),
                      GestureDetector(
                        onTap: isUploading ? null : _pickFiles,
                        child: Container(
                          width: double.infinity,
                          padding: const EdgeInsets.symmetric(
                              vertical: 24, horizontal: 16),
                          decoration: BoxDecoration(
                            color: AppColors.bgSecondary,
                            border: Border.all(
                              color: AppColors.border,
                              style: BorderStyle.solid,
                            ),
                            borderRadius: AppRadius.smAll,
                          ),
                          child: Column(
                            children: [
                              Icon(Icons.cloud_upload_outlined,
                                  color: AppColors.textTertiary, size: 36),
                              const SizedBox(height: 8),
                              Text('Tap to select files',
                                  style: AppTextStyles.bodySmall),
                              const SizedBox(height: 4),
                              Text('PDF, TXT, JSON, DOC, DOCX',
                                  style: AppTextStyles.caption),
                            ],
                          ),
                        ),
                      ),

                      // Selected files list
                      if (_selectedFiles.isNotEmpty) ...[
                        AppSpacing.vSm,
                        ...List.generate(_selectedFiles.length, (i) {
                          final file = _selectedFiles[i];
                          final sizeKb =
                              ((file.size) / 1024).toStringAsFixed(1);
                          return Container(
                            margin: const EdgeInsets.only(top: 6),
                            padding: const EdgeInsets.symmetric(
                                horizontal: 12, vertical: 8),
                            decoration: BoxDecoration(
                              color: AppColors.panel,
                              border:
                                  Border.all(color: AppColors.border),
                              borderRadius: AppRadius.smAll,
                            ),
                            child: Row(
                              children: [
                                Text(_fileIcon(file.extension ?? ''),
                                    style:
                                        const TextStyle(fontSize: 18)),
                                const SizedBox(width: 10),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(file.name,
                                          style:
                                              AppTextStyles.bodySmall,
                                          maxLines: 1,
                                          overflow:
                                              TextOverflow.ellipsis),
                                      Text('${sizeKb}KB',
                                          style:
                                              AppTextStyles.caption),
                                    ],
                                  ),
                                ),
                                if (!isUploading)
                                  GestureDetector(
                                    onTap: () => _removeFile(i),
                                    child: Icon(Icons.close,
                                        size: 18,
                                        color:
                                            AppColors.textTertiary),
                                  ),
                              ],
                            ),
                          );
                        }),
                      ],
                      AppSpacing.vLg,

                      // URLs
                      FSTextField(
                        label: 'Website URLs (Optional)',
                        hint: 'https://site1.com, https://site2.com',
                        controller: _urlsCtrl,
                        maxLines: 3,
                        enabled: !isUploading,
                      ),
                      const SizedBox(height: 4),
                      Text(
                        'Separate multiple URLs with commas',
                        style: AppTextStyles.caption,
                      ),
                    ],
                  ),
                ),
                AppSpacing.vXl,

                FSButton(
                  label: '📤 Upload to Knowledge Base',
                  isLoading: isUploading,
                  onPressed: isUploading ? null : _submit,
                  variant: FSButtonVariant.gradient,
                ),
                AppSpacing.vXl,
              ],
            );
          },
        ),
      ),
    );
  }

  String _fileIcon(String ext) {
    return switch (ext.toLowerCase()) {
      'pdf' => '📄',
      'txt' => '📝',
      'json' => '📊',
      'doc' || 'docx' => '📃',
      _ => '📎',
    };
  }
}