import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:file_picker/file_picker.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../core/utils/time_utils.dart';
import '../../services/app_provider.dart';
import '../../services/api_service.dart';
import '../../widgets/glass_card.dart';
import '../../widgets/scanner_animation.dart';
import '../../widgets/upgrade_prompt.dart';

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

  @override
  State<DocumentScreen> createState() => _DocumentScreenState();
}

class _DocumentScreenState extends State<DocumentScreen> {
  bool _uploading = false;
  bool _scanning = false;
  Map<String, dynamic>? _analysis;

  Future<void> _pickAndUpload() async {
    final result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['pdf', 'doc', 'docx', 'txt', 'png', 'jpg', 'jpeg', 'webp', 'mp3', 'wav', 'ogg', 'csv'],
    );
    if (result == null || result.files.isEmpty) return;
    final file = result.files.first;
    if (file.path == null) return;

    setState(() { _uploading = true; _scanning = true; _analysis = null; });
    try {
      final provider = context.read<AppProvider>();
      final res = await provider.api.uploadFile(file.path!, file.name);
      await provider.loadDocuments();
      setState(() { _uploading = false; _scanning = false; _analysis = res; });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('"${file.name}" uploaded & analyzed'),
            backgroundColor: AppColors.success,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
        );
      }
    } on ApiException catch (e) {
      setState(() { _uploading = false; _scanning = false; });
      if (e.isLimitError) {
        if (mounted) showUpgradePrompt(context, feature: 'document scans');
      } else if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Upload failed: ${e.message}'),
            backgroundColor: AppColors.error,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
        );
      }
    } catch (e) {
      setState(() { _uploading = false; _scanning = false; });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('Upload failed. Please try again.'),
            backgroundColor: AppColors.error,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final provider = context.watch<AppProvider>();

    return SafeArea(
      bottom: false,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
            child: Text('Documents', style: AppTypography.displayLg.copyWith(color: Colors.white)),
          ),
          const SizedBox(height: 8),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Text('Upload & analyze legal documents', style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary)),
          ),
          const SizedBox(height: 24),

          // Upload button
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: GestureDetector(
              onTap: _uploading || _scanning ? null : _pickAndUpload,
              child: GlassCard(
                highlighted: true,
                padding: const EdgeInsets.all(20),
                child: Row(
                  children: [
                    Container(
                      width: 48,
                      height: 48,
                      decoration: BoxDecoration(
                        color: AppColors.royalBlue.withValues(alpha: 0.15),
                        borderRadius: BorderRadius.circular(14),
                      ),
                      child: Icon(
                        _uploading ? Icons.cloud_upload_rounded : Icons.add_rounded,
                        color: AppColors.royalBlue, size: 24,
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            _uploading ? 'Uploading...' : _scanning ? 'Analyzing...' : 'Upload Document',
                            style: AppTypography.headingMd.copyWith(color: Colors.white),
                          ),
                          const SizedBox(height: 2),
                          Text(
                            'PDF, DOC, DOCX, TXT, Images',
                            style: AppTypography.bodySm.copyWith(color: AppColors.textMuted),
                          ),
                        ],
                      ),
                    ),
                    if (_uploading || _scanning)
                      const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(color: AppColors.royalBlue, strokeWidth: 2)),
                  ],
                ),
              ),
            ),
          ),

          // Scanner animation
          if (_scanning)
            Padding(
              padding: const EdgeInsets.fromLTRB(20, 20, 20, 0),
              child: GlassCard(
                padding: const EdgeInsets.all(16),
                child: Column(
                  children: [
                    const ScannerAnimation(height: 120),
                    const SizedBox(height: 12),
                    Text('Scanning document...', style: AppTypography.bodyMd.copyWith(color: AppColors.gold)),
                  ],
                ),
              ),
            ),

          // Analysis result
          if (_analysis != null)
            Padding(
              padding: const EdgeInsets.fromLTRB(20, 20, 20, 0),
              child: GlassCard(
                padding: const EdgeInsets.all(20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.check_circle_rounded, color: AppColors.success, size: 20),
                        const SizedBox(width: 8),
                        Text('Analysis Complete', style: AppTypography.headingMd.copyWith(color: AppColors.success)),
                      ],
                    ),
                    const SizedBox(height: 12),
                    Text(
                      _analysis!['summary']?.toString() ?? 'Document analyzed successfully.',
                      style: AppTypography.bodyMd.copyWith(color: Colors.white, height: 1.5),
                    ),
                  ],
                ),
              ),
            ),

          // Previous documents
          const SizedBox(height: 24),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Text('Previous Documents', style: AppTypography.headingMd.copyWith(color: Colors.white)),
          ),
          const SizedBox(height: 12),
          Expanded(
            child: provider.documents.isEmpty
                ? Center(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(Icons.description_outlined, size: 48, color: AppColors.textMuted),
                        const SizedBox(height: 12),
                        Text('No documents yet', style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted)),
                        const SizedBox(height: 6),
                        Text('Upload a contract, lease, or notice above',
                            style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
                      ],
                    ),
                  )
                : RefreshIndicator(
                    color: AppColors.royalBlue,
                    backgroundColor: AppColors.navy,
                    onRefresh: () => provider.loadDocuments(),
                    child: ListView.builder(
                    padding: const EdgeInsets.fromLTRB(20, 0, 20, 100),
                    itemCount: provider.documents.length,
                    itemBuilder: (context, i) {
                      final doc = provider.documents[i];
                      return Padding(
                        padding: const EdgeInsets.only(bottom: 10),
                        child: GestureDetector(
                          onTap: () => _showDocumentActions(doc),
                          child: GlassCard(
                          padding: const EdgeInsets.all(14),
                          child: Row(
                            children: [
                              Container(
                                width: 40,
                                height: 40,
                                decoration: BoxDecoration(
                                  color: AppColors.royalBlue.withValues(alpha: 0.12),
                                  borderRadius: BorderRadius.circular(10),
                                ),
                                child: const Icon(Icons.description_rounded, color: AppColors.royalBlue, size: 20),
                              ),
                              const SizedBox(width: 12),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(doc['original_name']?.toString() ?? doc['name']?.toString() ?? 'Document', style: AppTypography.bodyLg.copyWith(color: Colors.white), maxLines: 1, overflow: TextOverflow.ellipsis),
                                    Text(timeAgo(doc['created_at']?.toString()), style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
                                  ],
                                ),
                              ),
                              const Icon(Icons.chevron_right_rounded, color: AppColors.textMuted, size: 20),
                            ],
                          ),
                        ),
                        ),
                      );
                    },
                  ),
                  ),
          ),
        ],
      ),
    );
  }

  void _showDocumentActions(Map<String, dynamic> doc) {
    final docName = doc['original_name']?.toString() ?? doc['name']?.toString() ?? 'Document';
    final summary = (doc['analysis'] is Map) ? doc['analysis']['summary']?.toString() : null;
    final docId = doc['id']?.toString();

    showModalBottomSheet(
      context: context,
      backgroundColor: AppColors.navy,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (ctx) => Padding(
        padding: const EdgeInsets.fromLTRB(20, 16, 20, 32),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Center(
              child: Container(
                width: 40, height: 4,
                decoration: BoxDecoration(color: AppColors.glassBorder, borderRadius: BorderRadius.circular(2)),
              ),
            ),
            const SizedBox(height: 16),
            Text(docName, style: AppTypography.headingMd.copyWith(color: Colors.white), maxLines: 2, overflow: TextOverflow.ellipsis),
            if (summary != null) ...[
              const SizedBox(height: 12),
              Text(summary, style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary, height: 1.5), maxLines: 5, overflow: TextOverflow.ellipsis),
            ],
            const SizedBox(height: 20),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton.icon(
                icon: const Icon(Icons.chat_rounded, size: 18),
                label: const Text('Chat about this document'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.royalBlue,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 14),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                ),
                onPressed: docId == null ? null : () {
                  Navigator.pop(ctx);
                  _chatAboutDocument(docId, docName);
                },
              ),
            ),
            const SizedBox(height: 10),
            SizedBox(
              width: double.infinity,
              child: OutlinedButton.icon(
                icon: Icon(Icons.delete_outline_rounded, size: 18, color: AppColors.error),
                label: Text('Delete', style: TextStyle(color: AppColors.error)),
                style: OutlinedButton.styleFrom(
                  side: BorderSide(color: AppColors.error.withValues(alpha: 0.3)),
                  padding: const EdgeInsets.symmetric(vertical: 14),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                ),
                onPressed: docId == null ? null : () async {
                  Navigator.pop(ctx);
                  final provider = context.read<AppProvider>();
                  await provider.removeDocument(docId);
                  if (mounted) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: const Text('Document deleted'),
                        backgroundColor: AppColors.success,
                        behavior: SnackBarBehavior.floating,
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                      ),
                    );
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _chatAboutDocument(String docId, String docName) async {
    try {
      final provider = context.read<AppProvider>();
      // Create a new conversation for this document
      final convId = await provider.createConversation(
        title: 'Re: $docName',
      );
      // Link the document to the conversation
      await provider.api.linkDocumentToConversation(docId, convId);
      if (mounted) {
        Navigator.of(context).pushNamed('/chat', arguments: {
          'conversationId': convId,
          'initialMessage': 'Analyze this document "$docName" and summarize the key points, important clauses, and any potential issues.',
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('Failed to start chat. Please try again.'),
            backgroundColor: AppColors.error,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
        );
      }
    }
  }
}
