import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:taxglide/consts/download_helper.dart';
import 'package:taxglide/controller/api_contoller.dart';

import 'package:photo_view/photo_view.dart';

class ChatProfileScreen extends ConsumerWidget {
  final int chatid;

  const ChatProfileScreen({super.key, required this.chatid});

  // Helper function to check if document is valid
  bool _isValidDocument(dynamic doc) {
    // Check if fileName exists and is not empty
    final hasFileName =
        doc.fileName != null && doc.fileName.toString().trim().isNotEmpty;

    // Check if filePath exists and is not empty
    final hasFilePath =
        doc.filePath != null && doc.filePath.toString().trim().isNotEmpty;

    // Return true only if both fileName and filePath exist
    return hasFileName && hasFilePath;
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final result = ref.watch(chatDocumentProvider(chatid));

    return Scaffold(
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(240),
        child: AppBar(
          automaticallyImplyLeading: true,
          backgroundColor: Colors.transparent,
          elevation: 0,
          centerTitle: true,
          title: const Text(
            "Profile",
            style: TextStyle(
              fontFamily: "Gilroy-SemiBold",
              fontWeight: FontWeight.w400,
              fontSize: 20,
              height: 1.4,
              letterSpacing: 0.6,
              color: Colors.black,
            ),
          ),

          flexibleSpace: result.when(
            loading: () => const Center(child: CircularProgressIndicator()),
            error: (e, st) => Center(child: Text(e.toString())),
            data: (data) {
              return Container(
                width: double.infinity,
                height: 282,
                padding: const EdgeInsets.only(top: 100, bottom: 20),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: const Color(0xFFDEDEDE),
                      width: 1,
                    ),
                  ),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircleAvatar(
                      radius: 45,
                      backgroundImage: NetworkImage(data.profile),
                    ),
                    const SizedBox(height: 12),
                    Text(
                      data.name,
                      style: Theme.of(context).textTheme.titleLarge!.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      data.role,
                      style: TextStyle(fontSize: 16, color: Colors.grey[700]),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      ),

      body: result.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (e, st) => Center(child: Text(e.toString())),
        data: (data) {
          // Filter out invalid documents
          final senderList = data.userUploadedDocuments
              .where((doc) => _isValidDocument(doc))
              .toList();

          final receiverList = data.adminUploadedDocuments
              .where((doc) => _isValidDocument(doc))
              .toList();

          return SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // ---------------- Shared by Taxglide ----------------
                const Text(
                  "Shared By Taxglide",
                  style: TextStyle(
                    fontFamily: "Gilroy-SemiBold",
                    fontWeight: FontWeight.w600,
                    fontSize: 20,
                    height: 1.4,
                    letterSpacing: 0.6,
                    color: Colors.black,
                  ),
                ),

                const SizedBox(height: 10),

                receiverList.isEmpty
                    ? const Text("No documents from Taxglide")
                    : SizedBox(
                        height: 110,
                        child: ListView.separated(
                          scrollDirection: Axis.horizontal,
                          itemCount: receiverList.length,
                          separatorBuilder: (_, __) =>
                              const SizedBox(width: 12),
                          itemBuilder: (_, index) {
                            final doc = receiverList[index];
                            final isImage = DownloadHelper.isImageFile(
                              doc.filePath,
                            );
                            final isPdf =
                                DownloadHelper.getFileExtension(doc.filePath) ==
                                'pdf';

                            return GestureDetector(
                              onTap: () {
                                if (isImage) {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (_) => ImagePreviewScreen(
                                        imageUrl: doc.filePath,
                                      ),
                                    ),
                                  );
                                } else if (isPdf) {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (_) => PdfPreviewScreen(
                                        pdfUrl: doc.filePath,
                                        fileName: doc.fileName,
                                      ),
                                    ),
                                  );
                                }
                              },
                              child: Container(
                                width: 100,
                                padding: const EdgeInsets.all(8),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(12),
                                  border: Border.all(
                                    color: Colors.grey.shade300,
                                  ),
                                ),
                                child: Column(
                                  children: [
                                    Expanded(
                                      child: isImage
                                          ? ClipRRect(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                              child: Image.network(
                                                doc.filePath,
                                                width: 100,
                                                fit: BoxFit.cover,
                                              ),
                                            )
                                          : isPdf
                                          ? const Icon(
                                              Icons.picture_as_pdf,
                                              size: 40,
                                              color: Colors.red,
                                            )
                                          : const Icon(
                                              Icons.insert_drive_file,
                                              size: 40,
                                              color: Colors.blue,
                                            ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        ),
                      ),

                const SizedBox(height: 30),

                // ---------------- Shared by Client ----------------
                const Text(
                  "Shared By Client",
                  style: TextStyle(
                    fontFamily: "Gilroy-SemiBold",
                    fontWeight: FontWeight.w600,
                    fontSize: 20,
                    height: 1.4,
                    letterSpacing: 0.6,
                    color: Colors.black,
                  ),
                ),
                const SizedBox(height: 10),

                senderList.isEmpty
                    ? const Text("No documents from Client")
                    : SizedBox(
                        height: 110,
                        child: ListView.separated(
                          scrollDirection: Axis.horizontal,
                          itemCount: senderList.length,
                          separatorBuilder: (_, __) =>
                              const SizedBox(width: 12),
                          itemBuilder: (_, index) {
                            final doc = senderList[index];
                            final isImage = DownloadHelper.isImageFile(
                              doc.filePath,
                            );
                            final isPdf =
                                DownloadHelper.getFileExtension(doc.filePath) ==
                                'pdf';

                            return GestureDetector(
                              onTap: () async {
                                if (isImage) {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (_) => ImagePreviewScreen(
                                        imageUrl: doc.filePath,
                                      ),
                                    ),
                                  );
                                } else {
                                  await DownloadHelper.downloadFile(
                                    doc.filePath,
                                  );
                                }
                              },
                              child: Container(
                                width: 100,
                                padding: const EdgeInsets.all(8),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(12),
                                  border: Border.all(
                                    color: Colors.grey.shade300,
                                  ),
                                ),
                                child: Column(
                                  children: [
                                    Expanded(
                                      child: isImage
                                          ? ClipRRect(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                              child: Image.network(
                                                doc.filePath,
                                                width: 100,
                                                fit: BoxFit.cover,
                                              ),
                                            )
                                          : isPdf
                                          ? const Icon(
                                              Icons.picture_as_pdf,
                                              size: 40,
                                              color: Colors.red,
                                            )
                                          : const Icon(
                                              Icons.insert_drive_file,
                                              size: 40,
                                              color: Colors.blue,
                                            ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        ),
                      ),
              ],
            ),
          );
        },
      ),
    );
  }
}

class ImagePreviewScreen extends StatelessWidget {
  final String imageUrl;

  const ImagePreviewScreen({super.key, required this.imageUrl});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: Center(
        child: PhotoView(
          imageProvider: NetworkImage(imageUrl),
          backgroundDecoration: const BoxDecoration(color: Colors.black),
        ),
      ),
    );
  }
}

class PdfPreviewScreen extends StatelessWidget {
  final String pdfUrl;
  final String fileName;

  const PdfPreviewScreen({
    super.key,
    required this.pdfUrl,
    required this.fileName,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(fileName),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.picture_as_pdf, size: 80, color: Colors.red),
            const SizedBox(height: 20),
            Text(
              fileName,
              style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 10),
            const Text(
              "PDF Preview not available",
              style: TextStyle(color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }
}
