import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../blocs/editor_session/editor_session_bloc.dart';
import '../blocs/editor_session/editor_session_event.dart';
import '../blocs/editor_session/editor_session_state.dart';
import '../services/file_service.dart';
import '../injection.dart';
import 'package:go_router/go_router.dart';

// Modal version for overlay display
class EditorPageModal extends StatefulWidget {
  final String orgId;
  final String fileId;
  final VoidCallback onClose;

  const EditorPageModal({
    super.key,
    required this.orgId,
    required this.fileId,
    required this.onClose,
  });

  @override
  State<EditorPageModal> createState() => _EditorPageModalState();
}

class _EditorPageModalState extends State<EditorPageModal> {
  late EditorSessionBloc _editorBloc;

  @override
  void initState() {
    super.initState();
    _editorBloc = EditorSessionBloc(getIt<FileService>());
    _editorBloc.add(
      EditorSessionStarted(orgId: widget.orgId, fileId: widget.fileId),
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider.value(
      value: _editorBloc,
      child: Column(
        children: [
          // Custom AppBar
          Container(
            height: 56,
            decoration: BoxDecoration(
              color: AppTheme.primaryBackground.withValues(alpha: 0.9),
              border: Border(
                bottom: BorderSide(
                  color: AppTheme.accentColor.withValues(alpha: 0.3),
                ),
              ),
            ),
            child: Row(
              children: [
                const SizedBox(width: 16),
                const Text(
                  'Document Editor',
                  style: TextStyle(
                    color: AppTheme.primaryText,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                IconButton(
                  icon: const Icon(Icons.close, color: AppTheme.primaryText),
                  onPressed: () {
                    _editorBloc.add(EditorSessionEnded());
                    widget.onClose();
                  },
                ),
                const SizedBox(width: 8),
              ],
            ),
          ),
          // Editor content
          Expanded(
            child: BlocBuilder<EditorSessionBloc, EditorSessionState>(
              builder: (context, state) {
                if (state is EditorSessionStarting) {
                  return const Center(child: CircularProgressIndicator());
                }
                if (state is EditorSessionFailed) {
                  return Center(
                    child: Text(
                      'Error: ${state.message}',
                      style: const TextStyle(color: AppTheme.primaryText),
                    ),
                  );
                }
                if (state is EditorSessionActive) {
                  return Container(
                    color: AppTheme.secondaryText,
                    child: Center(
                      child: Text(
                        'Collabora Editor Active\\n(URL: ${state.editUrl})',
                        textAlign: TextAlign.center,
                        style: const TextStyle(color: AppTheme.primaryText),
                      ),
                    ),
                  );
                }
                if (state is EditorSessionReadOnly) {
                  return Container(
                    color: AppTheme.secondaryText,
                    child: Center(
                      child: Text(
                        'Read Only Mode\\n(URL: ${state.viewUrl})',
                        textAlign: TextAlign.center,
                        style: const TextStyle(color: AppTheme.primaryText),
                      ),
                    ),
                  );
                }
                if (state is EditorSessionExpired) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Text(
                          'Editing session expired.',
                          style: TextStyle(color: AppTheme.primaryText),
                        ),
                        const SizedBox(height: 16),
                        ElevatedButton(
                          onPressed: () {
                            _editorBloc.add(
                              EditorSessionStarted(
                                orgId: widget.orgId,
                                fileId: widget.fileId,
                              ),
                            );
                          },
                          child: const Text('Reopen'),
                        ),
                      ],
                    ),
                  );
                }
                return const Center(
                  child: Text(
                    'No editor session',
                    style: TextStyle(color: AppTheme.primaryText),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

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

// Original page version (for routing if needed)
class EditorPage extends StatefulWidget {
  final String orgId;
  final String fileId;

  const EditorPage({super.key, required this.orgId, required this.fileId});

  @override
  State<EditorPage> createState() => _EditorPageState();
}

class _EditorPageState extends State<EditorPage> {
  late EditorSessionBloc _editorBloc;

  @override
  void initState() {
    super.initState();
    _editorBloc = EditorSessionBloc(getIt<FileService>());
    _editorBloc.add(
      EditorSessionStarted(orgId: widget.orgId, fileId: widget.fileId),
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider.value(
      value: _editorBloc,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Document Editor'),
          actions: [
            IconButton(
              icon: const Icon(Icons.close),
              onPressed: () {
                _editorBloc.add(EditorSessionEnded());
                GoRouter.of(
                  context,
                ).go('/viewer/${widget.orgId}/${widget.fileId}');
              },
            ),
          ],
        ),
        body: BlocBuilder<EditorSessionBloc, EditorSessionState>(
          builder: (context, state) {
            if (state is EditorSessionStarting) {
              return const Center(child: CircularProgressIndicator());
            }
            if (state is EditorSessionFailed) {
              return Center(child: Text('Error: ${state.message}'));
            }
            if (state is EditorSessionActive) {
              // Placeholder for Collabora iframe
              return Container(
                color: AppTheme.secondaryText,
                child: Center(
                  child: Text(
                    'Collabora Editor Active\n(URL: ${state.editUrl})',
                    textAlign: TextAlign.center,
                    style: const TextStyle(color: AppTheme.primaryText),
                  ),
                ),
              );
            }
            if (state is EditorSessionReadOnly) {
              return Container(
                color: AppTheme.secondaryText,
                child: Center(
                  child: Text(
                    'Read Only Mode\n(URL: ${state.viewUrl})',
                    textAlign: TextAlign.center,
                    style: const TextStyle(color: AppTheme.primaryText),
                  ),
                ),
              );
            }
            if (state is EditorSessionExpired) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Text('Editing session expired.'),
                    ElevatedButton(
                      onPressed: () {
                        _editorBloc.add(
                          EditorSessionStarted(
                            orgId: widget.orgId,
                            fileId: widget.fileId,
                          ),
                        );
                      },
                      child: const Text('Reopen'),
                    ),
                  ],
                ),
              );
            }
            return const Center(child: Text('Editor not started'));
          },
        ),
      ),
    );
  }

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