import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cached_network_image/cached_network_image.dart';

class UserActivitiesScreen extends StatelessWidget {
  final String userId;

  UserActivitiesScreen({required this.userId});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(' '),
        actions: [
          Container(
            alignment: Alignment.centerRight,
            padding: EdgeInsets.only(right: 16),
            child: Text(
              'Activities',
              style: TextStyle(
                color: Color(0xFF554994),
                fontSize: 24,
                fontFamily: 'Poppins',
                fontWeight: FontWeight.w700,
                height: 0.04,
                letterSpacing: -0.96,
              ),
            ),
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16.0),
        child: StreamBuilder<QuerySnapshot>(
          stream: FirebaseFirestore.instance
              .collection('activities')
              .where('user', isEqualTo: userId)
              .snapshots(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                  child:
                      CircularProgressIndicator()); // Loading indicator
            }
            if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}'); // Error handling
            }
            if (snapshot.data == null || snapshot.data!.docs.isEmpty) {
              return Center(
                child: Text('No activities found for this user.'),
              ); // No activities found
            }

            final imageDocs = snapshot.data!.docs
                .where((doc) => doc['imageUrl'] != null)
                .toList();

            return ImageWall(
              imageDocs: imageDocs,
            );
          },
        ),
      ),
    );
  }
}

class ImageWall extends StatelessWidget {
  final List<DocumentSnapshot> imageDocs;

  ImageWall({required this.imageDocs});

  @override
  Widget build(BuildContext context) {
    // Sort the imageDocs based on timestamp in descending order
    imageDocs.sort((a, b) => b['timestamp'].compareTo(a['timestamp']));

    return ListView.separated(
      itemCount: imageDocs.length,
      itemBuilder: (context, index) {
        final imageUrl = imageDocs[index]['imageUrl'];
        final timestamp = imageDocs[index]['timestamp'];
        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 8.0),
          child: ImageItem(
            imageUrl: imageUrl,
            timestamp: timestamp,
          ),
        );
      },
      separatorBuilder: (context, index) => SizedBox(height: 16.0),
    );
  }
}

class ImageItem extends StatelessWidget {
  final String imageUrl;
  final Timestamp timestamp;
  final double imageHeight = 200.0;

  ImageItem({required this.imageUrl, required this.timestamp});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Container(
          height: imageHeight,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16.0), // Rounded corners
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withOpacity(0.5),
                spreadRadius: 2,
                blurRadius: 5,
                offset: Offset(0, 2), // Drop shadow
              ),
            ],
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(16.0), // Clip rounded corners
            child: CachedNetworkImage(
              imageUrl: imageUrl,
              fit: BoxFit.cover,
              placeholder: (context, url) => Center(
                child: CircularProgressIndicator(),
              ),
              errorWidget: (context, url, error) => Icon(Icons.error),
            ),
          ),
        ),
        Container(
          padding: EdgeInsets.all(8.0),
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.7), // Semi-transparent background
            borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(16.0), // Round only bottom corners
              bottomRight: Radius.circular(16.0),
            ),
          ),
          child: Row(
            children: [
              Expanded(
                child: Text(
                  'Uploaded: ${timestamp.toDate()}',
                  style: TextStyle(color: Colors.white),
                ),
              ),
              IconButton(
                icon: Icon(Icons.date_range),
                color: Colors.white,
                onPressed: () {
                  
                },
              ),
            ],
          ),
        ),
      ],
    );
  }
}
