// Version: 1.1.0 | Created: 2026-04-01
// Spaces screen — list of Matrix spaces with expandable child room lists.

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../data/spaces_repository.dart';
import '../domain/space_model.dart';

part 'spaces_screen.g.dart';

// ---------------------------------------------------------------------------
// Providers
// ---------------------------------------------------------------------------

@riverpod
Stream<List<SpaceModel>> spacesStream(Ref ref) {
  return ref.watch(spacesRepositoryProvider).watchSpaces();
}

@riverpod
List<SpaceRoomModel> spaceRooms(Ref ref, String spaceId) {
  return ref.watch(spacesRepositoryProvider).getRoomsInSpace(spaceId);
}

// ---------------------------------------------------------------------------
// Screen
// ---------------------------------------------------------------------------

class SpacesScreen extends ConsumerWidget {
  const SpacesScreen({super.key, this.embedded = false});

  final bool embedded;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final spacesAsync = ref.watch(spacesStreamProvider);

    final body = spacesAsync.when(
      loading: () => const Center(child: CircularProgressIndicator()),
      error: (err, _) => Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Text('Could not load spaces: $err'),
        ),
      ),
      data: (spaces) {
        if (spaces.isEmpty) {
          return _EmptySpacesState();
        }
        return ListView.builder(
          itemCount: spaces.length,
          itemBuilder: (context, index) {
            return _SpaceTile(space: spaces[index]);
          },
        );
      },
    );

    if (embedded) return body;

    return Scaffold(
      appBar: AppBar(title: const Text('Spaces')),
      body: body,
    );
  }
}

// ---------------------------------------------------------------------------
// Space tile with expandable child room list
// ---------------------------------------------------------------------------

class _SpaceTile extends ConsumerStatefulWidget {
  const _SpaceTile({required this.space});

  final SpaceModel space;

  @override
  ConsumerState<_SpaceTile> createState() => _SpaceTileState();
}

class _SpaceTileState extends ConsumerState<_SpaceTile> {
  bool _expanded = false;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final space = widget.space;

    return Column(
      children: [
        // Space header row
        ListTile(
          leading: _SpaceAvatar(
            name: space.displayName,
            avatarUrl: space.avatarUrl,
          ),
          title: Text(
            space.displayName,
            style: theme.textTheme.titleSmall?.copyWith(
              fontWeight: FontWeight.w600,
            ),
          ),
          subtitle: Text(
            '${space.roomCount} ${space.roomCount == 1 ? 'room' : 'rooms'}',
            style: theme.textTheme.bodySmall?.copyWith(
              color: theme.colorScheme.onSurface.withAlpha(153),
            ),
          ),
          trailing: space.roomCount > 0
              ? IconButton(
                  icon: Icon(
                    _expanded ? Icons.expand_less : Icons.expand_more,
                    color: theme.colorScheme.onSurface.withAlpha(153),
                  ),
                  onPressed: () => setState(() => _expanded = !_expanded),
                )
              : null,
          onTap: () => setState(() => _expanded = !_expanded),
        ),

        // Child rooms — shown when expanded
        if (_expanded) _ChildRoomList(spaceId: space.id),

        const Divider(height: 1),
      ],
    );
  }
}

// ---------------------------------------------------------------------------
// Child room list
// ---------------------------------------------------------------------------

class _ChildRoomList extends ConsumerWidget {
  const _ChildRoomList({required this.spaceId});

  final String spaceId;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final rooms = ref.watch(spaceRoomsProvider(spaceId));
    final theme = Theme.of(context);

    if (rooms.isEmpty) {
      return Padding(
        padding: const EdgeInsets.only(left: 56, right: 16, bottom: 8),
        child: Text(
          'No joined rooms in this space.',
          style: theme.textTheme.bodySmall?.copyWith(
            color: theme.colorScheme.onSurface.withAlpha(102),
          ),
        ),
      );
    }

    return Column(
      children: rooms.map((room) {
        return ListTile(
          contentPadding: const EdgeInsets.only(left: 56, right: 16),
          leading: _SpaceAvatar(
            name: room.displayName,
            avatarUrl: room.avatarUrl,
            radius: 18,
          ),
          title: Text(room.displayName, style: theme.textTheme.bodyMedium),
          trailing: room.isDirect
              ? Icon(
                  Icons.person_outline,
                  size: 16,
                  color: theme.colorScheme.onSurface.withAlpha(102),
                )
              : null,
          onTap: () => context.push('/rooms/${Uri.encodeComponent(room.id)}'),
        );
      }).toList(),
    );
  }
}

// ---------------------------------------------------------------------------
// Avatar widget
// ---------------------------------------------------------------------------

class _SpaceAvatar extends StatelessWidget {
  const _SpaceAvatar({required this.name, this.avatarUrl, this.radius = 22});

  final String name;
  final String? avatarUrl;
  final double radius;

  @override
  Widget build(BuildContext context) {
    final initials = name.isNotEmpty ? name[0].toUpperCase() : '?';
    if (avatarUrl != null) {
      return CircleAvatar(
        radius: radius,
        backgroundImage: NetworkImage(avatarUrl!),
      );
    }
    return CircleAvatar(
      radius: radius,
      backgroundColor: Theme.of(context).colorScheme.secondary.withAlpha(51),
      child: Text(
        initials,
        style: TextStyle(
          fontSize: radius * 0.7,
          color: Theme.of(context).colorScheme.secondary,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Empty state
// ---------------------------------------------------------------------------

class _EmptySpacesState extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.dashboard_outlined,
              size: 64,
              color: theme.colorScheme.onSurface.withAlpha(77),
            ),
            const SizedBox(height: 16),
            Text(
              'No spaces yet',
              style: theme.textTheme.titleMedium?.copyWith(
                color: theme.colorScheme.onSurface.withAlpha(153),
              ),
            ),
            const SizedBox(height: 8),
            Text(
              'Spaces you join will appear here.',
              textAlign: TextAlign.center,
              style: theme.textTheme.bodySmall?.copyWith(
                color: theme.colorScheme.onSurface.withAlpha(102),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
