import 'dart:io';
import 'package:flutter/material.dart';
import 'package:taxglide/consts/download_helper.dart';

class DownloadsScreen extends StatefulWidget {
  const DownloadsScreen({super.key});

  @override
  State<DownloadsScreen> createState() => _DownloadsScreenState();
}

class _DownloadsScreenState extends State<DownloadsScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  List<File> sentFiles = [];
  List<File> receivedFiles = [];
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _loadFiles();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _loadFiles() async {
    setState(() {
      isLoading = true;
    });

    try {
      final sent = await DownloadHelper.getSentFiles();
      final received = await DownloadHelper.getReceivedFiles();

      setState(() {
        sentFiles = sent;
        receivedFiles = received;
        isLoading = false;
      });
    } catch (e) {
      print("Error loading files: $e");
      setState(() {
        isLoading = false;
      });
    }
  }

  Future<void> _deleteFile(String filePath, bool isSent) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("Delete File"),
        content: const Text("Are you sure you want to delete this file?"),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text("Cancel"),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text("Delete"),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      final success = await DownloadHelper.deleteFile(filePath);

      if (success) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text("File deleted successfully"),
            backgroundColor: Colors.green,
          ),
        );
        _loadFiles();
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text("Failed to delete file"),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  String _getFileName(String path) {
    return path.split('/').last;
  }

  String _getFileSize(File file) {
    final bytes = file.lengthSync();
    if (bytes < 1024) return "$bytes B";
    if (bytes < 1024 * 1024) return "${(bytes / 1024).toStringAsFixed(1)} KB";
    return "${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB";
  }

  IconData _getFileIcon(String path) {
    final ext = path.split('.').last.toLowerCase();

    if (['jpg', 'jpeg', 'png', 'gif', 'webp'].contains(ext)) {
      return Icons.image;
    } else if (ext == 'pdf') {
      return Icons.picture_as_pdf;
    } else if (['doc', 'docx'].contains(ext)) {
      return Icons.description;
    } else if (['xls', 'xlsx'].contains(ext)) {
      return Icons.table_chart;
    } else {
      return Icons.insert_drive_file;
    }
  }

  Color _getFileIconColor(String path) {
    final ext = path.split('.').last.toLowerCase();

    if (['jpg', 'jpeg', 'png', 'gif', 'webp'].contains(ext)) {
      return Colors.blue;
    } else if (ext == 'pdf') {
      return Colors.red;
    } else if (['doc', 'docx'].contains(ext)) {
      return Colors.indigo;
    } else if (['xls', 'xlsx'].contains(ext)) {
      return Colors.green;
    } else {
      return Colors.grey;
    }
  }

  Widget _buildFileList(List<File> files, bool isSent) {
    if (isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (files.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              isSent ? Icons.upload_file : Icons.download,
              size: 80,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              isSent ? "No sent files" : "No downloaded files",
              style: TextStyle(
                fontSize: 18,
                color: Colors.grey[600],
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              isSent
                  ? "Files you upload will appear here"
                  : "Downloaded files will appear here",
              style: TextStyle(fontSize: 14, color: Colors.grey[500]),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadFiles,
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: files.length,
        itemBuilder: (context, index) {
          final file = files[index];
          final fileName = _getFileName(file.path);
          final fileSize = _getFileSize(file);
          final isImage = DownloadHelper.isImageFile(file.path);

          return Card(
            margin: const EdgeInsets.only(bottom: 12),
            elevation: 2,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            child: InkWell(
              onTap: () => DownloadHelper.openDownloadedFile(file.path),
              borderRadius: BorderRadius.circular(12),
              child: Padding(
                padding: const EdgeInsets.all(12),
                child: Row(
                  children: [
                    // File icon or image preview
                    Container(
                      width: 50,
                      height: 50,
                      decoration: BoxDecoration(
                        color: _getFileIconColor(file.path).withOpacity(0.1),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: isImage
                          ? ClipRRect(
                              borderRadius: BorderRadius.circular(8),
                              child: Image.file(file, fit: BoxFit.cover),
                            )
                          : Icon(
                              _getFileIcon(file.path),
                              size: 30,
                              color: _getFileIconColor(file.path),
                            ),
                    ),

                    const SizedBox(width: 12),

                    // File info
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            fileName,
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            fileSize,
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey[600],
                            ),
                          ),
                        ],
                      ),
                    ),

                    const SizedBox(width: 8),

                    // Delete button
                    IconButton(
                      icon: const Icon(Icons.delete_outline),
                      color: Colors.red,
                      onPressed: () => _deleteFile(file.path, isSent),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "Downloads",
          style: TextStyle(
            fontFamily: "Gilroy",
            fontWeight: FontWeight.w600,
          ),
        ),
        backgroundColor: Colors.white,
        elevation: 1,
        foregroundColor: Colors.black,
        bottom: TabBar(
          controller: _tabController,
          labelColor: const Color(0xFF630A73),
          unselectedLabelColor: Colors.grey,
          indicatorColor: const Color(0xFF630A73),
          tabs: [
            Tab(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(Icons.upload, size: 18),
                  const SizedBox(width: 6),
                  Text("Sent (${sentFiles.length})"),
                ],
              ),
            ),
            Tab(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(Icons.download, size: 18),
                  const SizedBox(width: 6),
                  Text("Received (${receivedFiles.length})"),
                ],
              ),
            ),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildFileList(sentFiles, true),
          _buildFileList(receivedFiles, false),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _loadFiles,
        backgroundColor: const Color(0xFF630A73),
        child: const Icon(Icons.refresh, color: Colors.white),
      ),
    );
  }
}
