import 'package:flutter/material.dart';
import '../blocs/organization/organization_state.dart';
import '../services/org_api.dart';
import '../services/api_client.dart';
import '../theme/app_theme.dart';
import '../theme/modern_glass_button.dart';
import 'package:get_it/get_it.dart';

class JoinPage extends StatefulWidget {
  final String token;

  const JoinPage({super.key, required this.token});

  @override
  State<JoinPage> createState() => _JoinPageState();
}

class _JoinPageState extends State<JoinPage> {
  Organization? _org;
  bool _isLoading = true;
  String? _error;
  bool _isJoining = false;

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

  Future<void> _fetchOrg() async {
    if (widget.token.isEmpty) {
      setState(() {
        _error = 'Invalid invite link';
        _isLoading = false;
      });
      return;
    }

    try {
      // Assume we have a method to get org by token
      // For now, since not implemented, use ApiClient directly
      final apiClient = GetIt.I<ApiClient>();
      final result = await apiClient.get(
        '/join?token=${widget.token}',
        fromJson: (data) => Organization.fromJson(data),
      );
      setState(() {
        _org = result;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _error = 'Invalid or expired invite link';
        _isLoading = false;
      });
    }
  }

  Future<void> _joinOrg() async {
    if (_org == null) return;

    setState(() => _isJoining = true);
    try {
      final orgApi = GetIt.I<OrgApi>();
      await orgApi.createJoinRequest(_org!.id, inviteToken: widget.token);
      // Navigate to home or show success
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Join request sent successfully')),
        );
        Navigator.of(context).pushReplacementNamed('/'); // Assuming home is /
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('Failed to join: $e')));
      }
    } finally {
      setState(() => _isJoining = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.primaryBackground,
      appBar: AppBar(
        title: const Text('Join Organization'),
        backgroundColor: AppTheme.secondaryBackground,
      ),
      body: Center(
        child: _isLoading
            ? const CircularProgressIndicator()
            : _error != null
            ? Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(_error!, style: TextStyle(color: AppTheme.errorColor)),
                  const SizedBox(height: 16),
                  ModernGlassButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('Go Back'),
                  ),
                ],
              )
            : _org != null
            ? Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'Join ${_org!.name}?',
                    style: TextStyle(
                      color: AppTheme.primaryText,
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 16),
                  Text(
                    'You have been invited to join this organization.',
                    style: TextStyle(color: AppTheme.secondaryText),
                  ),
                  const SizedBox(height: 32),
                  _isJoining
                      ? const CircularProgressIndicator()
                      : ModernGlassButton(
                          onPressed: _joinOrg,
                          child: const Text('Join Organization'),
                        ),
                ],
              )
            : const Text('Organization not found'),
      ),
    );
  }
}
