import 'dart:io';
import 'dart:ui'; // Add this import for ImageFilter

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sigap/src/utils/constants/colors.dart';
import 'package:sigap/src/utils/constants/sizes.dart';
import 'package:sigap/src/utils/helpers/helper_functions.dart';
import 'package:sigap/src/utils/loaders/circular_loader.dart';

class ImageUploader extends StatelessWidget {
  final XFile? image;
  final String title;
  final String subtitle;
  final String? errorMessage;
  final bool isUploading;
  final bool isVerifying;
  final bool isConfirmed;
  final bool isSuccess;
  final VoidCallback onTapToSelect;
  final VoidCallback? onClear;
  final VoidCallback? onValidate;
  final IconData placeholderIcon;
  final double height;
  final Widget? processingOverlay;
  final Widget? errorOverlay;

  const ImageUploader({
    super.key,
    required this.image,
    required this.title,
    required this.subtitle,
    this.errorMessage,
    required this.isUploading,
    required this.isVerifying,
    required this.isConfirmed,
    this.isSuccess = false,
    required this.onTapToSelect,
    this.onClear,
    this.onValidate,
    this.placeholderIcon = Icons.add_a_photo,
    this.height = 180,
    this.processingOverlay,
    this.errorOverlay,
  });

  @override
  Widget build(BuildContext context) {
    // Background color based on error state, success or confirmation
    final backgroundColor =
        errorMessage != null && errorMessage!.isNotEmpty
            ? TColors.error.withOpacity(0.1)
            : isSuccess
            ? Colors.green.withOpacity(0.1)
            : isConfirmed
            ? Colors.green.withOpacity(0.1)
            : Colors.grey.withOpacity(0.1);

    // Determine border color based on error state, success or confirmation
    final borderColor =
        errorMessage != null && errorMessage!.isNotEmpty
            ? TColors.error
            : isSuccess
            ? Colors.green
            : isConfirmed
            ? Colors.green
            : Colors.grey.withOpacity(0.5);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (image == null)
          _buildEmptyUploader(backgroundColor, borderColor, context)
        else
          _buildImagePreview(borderColor, context),

        // Show file size information if image is uploaded
        if (image != null)
          FutureBuilder<int>(
            future: File(image!.path).length(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                final fileSizeKB = snapshot.data! / 1024;
                final fileSizeMB = fileSizeKB / 1024;
                final isOversized = fileSizeMB > 4; // 4MB limit
                return Padding(
                  padding: const EdgeInsets.only(top: TSizes.sm),
                  child: Text(
                    'File size: ${fileSizeMB.toStringAsFixed(2)} MB',
                    style: TextStyle(
                      fontSize: TSizes.fontSizeSm,
                      color:
                          isOversized ? TColors.error : TColors.textSecondary,
                      fontWeight:
                          isOversized ? FontWeight.bold : FontWeight.normal,
                    ),
                  ),
                );
              }
              return const SizedBox.shrink();
            },
          ),
      ],
    );
  }

  Widget _buildEmptyUploader(
    Color backgroundColor,
    Color borderColor,
    BuildContext context,
  ) {
    final isDark = THelperFunctions.isDarkMode(context);

    return GestureDetector(
      onTap: onTapToSelect,
      child: Container(
        height: height,
        width: double.infinity,
        decoration: BoxDecoration(
          color: backgroundColor,
          borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
          border: Border.all(
            color: borderColor,
            width: errorMessage != null && errorMessage!.isNotEmpty ? 2 : 1,
          ),
        ),
        child:
            isUploading
                ? Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      TCircularLoader(
                        backgroundColor: TColors.transparent,
                        foregroundColor:
                            isDark ? TColors.accent : TColors.primary,
                      ),
                      const SizedBox(height: TSizes.sm),
                      Text(
                        'Uploading...',
                        style: TextStyle(color: TColors.textSecondary),
                      ),
                    ],
                  ),
                )
                : Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      errorMessage != null && errorMessage!.isNotEmpty
                          ? Icons.error_outline
                          : placeholderIcon,
                      size: TSizes.iconLg,
                      color:
                          errorMessage != null && errorMessage!.isNotEmpty
                              ? TColors.error
                              : Colors.grey,
                    ),
                    const SizedBox(height: TSizes.sm),
                    Text(
                      errorMessage != null && errorMessage!.isNotEmpty
                          ? 'Please upload an image first'
                          : title,
                      style: TextStyle(
                        color:
                            errorMessage != null && errorMessage!.isNotEmpty
                                ? TColors.error
                                : TColors.textSecondary,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: TSizes.xs),
                    Text(
                      subtitle,
                      style: TextStyle(
                        fontSize: TSizes.fontSizeSm,
                        color:
                            errorMessage != null && errorMessage!.isNotEmpty
                                ? TColors.error.withOpacity(0.8)
                                : TColors.textSecondary,
                      ),
                    ),
                  ],
                ),
      ),
    );
  }

  Widget _buildImagePreview(Color borderColor, BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Stack(
          alignment: Alignment.topRight,
          children: [
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
                border: Border.all(
                  color: isSuccess ? Colors.green : borderColor,
                  width: 2,
                ),
              ),
              child: Stack(
                alignment: Alignment.center,
                children: [
                  // Make the image tappable for preview
                  GestureDetector(
                    onTap: () => _showImagePreview(context),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(
                        TSizes.borderRadiusMd - 2,
                      ),
                      child: Image.file(
                        File(image!.path),
                        height: 200,
                        width: double.infinity,
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),

                  // Success indicator (checkmark)
                  if (isSuccess && !isUploading && !isVerifying)
                    Positioned(
                      bottom: 8,
                      right: 8,
                      child: Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: Colors.green,
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(
                          Icons.check,
                          color: Colors.white,
                          size: TSizes.iconSm,
                        ),
                      ),
                    ),

                  // Error overlay
                  if (errorMessage != null &&
                      errorMessage!.isNotEmpty &&
                      !isUploading &&
                      !isVerifying)
                    errorOverlay ?? _defaultErrorOverlay(),

                  // Loading overlay
                  if (isUploading || isVerifying)
                    processingOverlay ?? _defaultProcessingOverlay(),
                ],
              ),
            ),

            // Close button
            if (!isConfirmed && !isUploading && !isVerifying && onClear != null)
              Positioned(
                top: 8,
                right: 8,
                child: GestureDetector(
                  onTap: onClear,
                  child: Container(
                    padding: const EdgeInsets.all(TSizes.xs),
                    decoration: BoxDecoration(
                      color:
                          errorMessage != null && errorMessage!.isNotEmpty
                              ? TColors.error
                              : Colors.black54,
                      shape: BoxShape.circle,
                    ),
                    child: const Icon(
                      Icons.close,
                      color: Colors.white,
                      size: TSizes.iconSm,
                    ),
                  ),
                ),
              ),
          ],
        ),

        // // Validate button
        // if (onValidate != null && !isVerifying && !isUploading && !isConfirmed)
        //   Padding(
        //     padding: const EdgeInsets.only(top: TSizes.sm),
        //     child: ElevatedButton.icon(
        //       onPressed: onValidate,
        //       icon: const Icon(Icons.check_circle),
        //       label: Text('Verify Image'),
        //       style: ElevatedButton.styleFrom(
        //         backgroundColor: TColors.primary,
        //         foregroundColor: Colors.white,
        //         minimumSize: const Size(double.infinity, 50),
        //       ),
        //     ),
        //   ),
      ],
    );
  }

  // Method to show full-screen image preview
  void _showImagePreview(BuildContext context) {
    if (image == null) return;

    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          insetPadding: EdgeInsets.zero,
          backgroundColor: Colors.transparent,
          child: GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Stack(
              alignment: Alignment.center,
              children: [
                // Image with interactive viewer for zooming
                InteractiveViewer(
                  minScale: 0.5,
                  maxScale: 3.0,
                  child: Image.file(
                    File(image!.path),
                    fit: BoxFit.contain,
                    width: MediaQuery.of(context).size.width,
                    height: MediaQuery.of(context).size.height,
                  ),
                ),

                // Close button at the top
                Positioned(
                  top: 40,
                  right: 20,
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.black54,
                      shape: BoxShape.circle,
                    ),
                    child: IconButton(
                      icon: Icon(Icons.close, color: Colors.white),
                      onPressed: () => Navigator.of(context).pop(),
                    ),
                  ),
                ),

                // Image info at the bottom
                Positioned(
                  bottom: 40,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                    decoration: BoxDecoration(
                      color: Colors.black54,
                      borderRadius: BorderRadius.circular(30),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          isSuccess ? Icons.check_circle : Icons.image,
                          color: isSuccess ? Colors.green : Colors.white,
                          size: 20,
                        ),
                        SizedBox(width: 8),
                        Text(
                          title,
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _defaultErrorOverlay() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(TSizes.borderRadiusMd - 2),
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
        child: Container(
          height: 200,
          width: double.infinity,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(TSizes.borderRadiusMd - 2),
            color: Colors.black.withOpacity(0.5),
          ),
          child: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  TColors.error.withOpacity(0.4),
                  Colors.black.withOpacity(0.7),
                ],
              ),
            ),
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    padding: const EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      color: TColors.error.withOpacity(0.2),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      Icons.error_outline,
                      color: Colors.white,
                      size: TSizes.iconLg,
                    ),
                  ),
                  const SizedBox(height: TSizes.sm),
                  Text(
                    'Invalid Image',
                    style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  const SizedBox(height: TSizes.xs),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: TSizes.md),
                    child: Text(
                      errorMessage ?? 'Please try another image',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Colors.white.withOpacity(0.9),
                        fontSize: TSizes.fontSizeSm,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _defaultProcessingOverlay() {
    return Container(
      height: 200,
      width: double.infinity,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(TSizes.borderRadiusMd - 2),
        color: Colors.black.withOpacity(0.5),
      ),
      child: const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(color: Colors.white),
            SizedBox(height: TSizes.sm),
            Text(
              'Processing...',
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }

}
