import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../services/api_client.dart';
import '../models/api_error.dart';
import '../theme/app_theme.dart';
import '../theme/modern_glass_button.dart';
import '../injection.dart';

class ShareFileDialog extends StatefulWidget {
  final String orgId;
  final String fileId;
  final String fileName;

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

  @override
  State<ShareFileDialog> createState() => _ShareFileDialogState();
}

class _ShareFileDialogState extends State<ShareFileDialog> {
  bool _isLoading = true;
  String? _shareUrl;
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadShareLink();
  }

  Future<void> _loadShareLink() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final apiClient = getIt<ApiClient>();
      final path = widget.orgId.isEmpty || widget.orgId == 'personal'
          ? '/orgs/files/${widget.fileId}/share'
          : '/orgs/${widget.orgId}/files/${widget.fileId}/share';
      final response = await apiClient.getRaw(path);

      setState(() {
        _shareUrl = response['shareUrl'];
        _isLoading = false;
      });
    } catch (e) {
      if (e is ApiError && e.status == 404) {
        // No link exists, create one automatically
        setState(() {
          _isLoading = true; // Keep loading for creation
        });
        try {
          final apiClient = getIt<ApiClient>();
          final path = widget.orgId.isEmpty || widget.orgId == 'personal'
              ? '/orgs/files/${widget.fileId}/share'
              : '/orgs/${widget.orgId}/files/${widget.fileId}/share';
          final response = await apiClient.postRaw(path, data: {});

          setState(() {
            _shareUrl = response['shareUrl'];
            _isLoading = false;
          });
        } catch (createError) {
          setState(() {
            _error = createError is ApiError
                ? createError.message
                : 'Failed to create share link';
            _isLoading = false;
          });
        }
        return;
      }
      setState(() {
        _error = 'Failed to load share link';
        _isLoading = false;
      });
    }
  }

  Future<void> _createShareLink() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final apiClient = getIt<ApiClient>();
      final path = widget.orgId.isEmpty || widget.orgId == 'personal'
          ? '/orgs/files/${widget.fileId}/share'
          : '/orgs/${widget.orgId}/files/${widget.fileId}/share';
      final response = await apiClient.postRaw(path, data: {});

      setState(() {
        _shareUrl = response['shareUrl'];
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _error = e is ApiError ? e.message : 'Failed to create share link';
        _isLoading = false;
      });
    }
  }

  void _copyToClipboard() {
    if (_shareUrl != null) {
      Clipboard.setData(ClipboardData(text: _shareUrl!));
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('Copied!')));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: AppTheme.primaryBackground,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Container(
        width: 500,
        constraints: const BoxConstraints(maxHeight: 400),
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // Header
            Row(
              children: [
                Expanded(
                  child: Text(
                    'Share "${widget.fileName}"',
                    style: TextStyle(
                      color: AppTheme.primaryText,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                const SizedBox(width: 16),
                IconButton(
                  onPressed: () => Navigator.of(context).pop(),
                  icon: Icon(Icons.close, color: AppTheme.secondaryText),
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                ),
              ],
            ),
            const SizedBox(height: 16),
            if (_isLoading)
              const Center(
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(
                    AppTheme.accentColor,
                  ),
                ),
              )
            else if (_error != null)
              Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      _error!,
                      style: TextStyle(color: AppTheme.errorColor),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 16),
                    SizedBox(
                      width: 160,
                      child: ModernGlassButton(
                        onPressed: _loadShareLink,
                        child: const Text('Retry'),
                      ),
                    ),
                  ],
                ),
              )
            else
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (_shareUrl != null) ...[
                    Text(
                      'Anyone with this link can view and download the file.',
                      style: TextStyle(color: AppTheme.secondaryText),
                    ),
                    const SizedBox(height: 16),
                    Row(
                      children: [
                        Expanded(
                          child: TextField(
                            controller: TextEditingController(text: _shareUrl),
                            readOnly: true,
                            maxLines: 1,
                            style: TextStyle(color: AppTheme.primaryText),
                            decoration: InputDecoration(
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: AppTheme.secondaryText.withValues(
                                    alpha: 0.3,
                                  ),
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: AppTheme.secondaryText.withValues(
                                    alpha: 0.3,
                                  ),
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: AppTheme.accentColor,
                                ),
                              ),
                              contentPadding: const EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 8,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 16),
                        ModernGlassButton(
                          onPressed: _copyToClipboard,
                          child: const Icon(Icons.content_copy),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                  ] else ...[
                    Text(
                      'No share link yet. Create a public, read-only link for this file.',
                      style: TextStyle(color: AppTheme.secondaryText),
                    ),
                    const SizedBox(height: 16),
                    ModernGlassButton(
                      onPressed: _createShareLink,
                      isLoading: _isLoading,
                      child: _isLoading
                          ? const SizedBox(
                              height: 16,
                              width: 16,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(
                                  AppTheme.accentColor,
                                ),
                              ),
                            )
                          : const Text('Create link'),
                    ),
                  ],
                ],
              ),
          ],
        ),
      ),
    );
  }
}
