import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import '../../../core/constants/ui_constants.dart';
import '../buttons/modern_button.dart';

class ModernImagePicker extends StatefulWidget {
  final String? label;
  final String? hint;
  final Uint8List? imageBytes;
  final File? imageFile;
  final String? imageUrl;
  final VoidCallback? onPickImage;
  final VoidCallback? onRemoveImage;
  final bool isLoading;
  final double? height;
  final double? width;
  final BorderRadius? borderRadius;
  final String? errorText;
  final bool showRemoveButton;
  final IconData? placeholderIcon;
  final String? placeholderText;

  const ModernImagePicker({
    super.key,
    this.label,
    this.hint,
    this.imageBytes,
    this.imageFile,
    this.imageUrl,
    this.onPickImage,
    this.onRemoveImage,
    this.isLoading = false,
    this.height = 200,
    this.width,
    this.borderRadius,
    this.errorText,
    this.showRemoveButton = true,
    this.placeholderIcon,
    this.placeholderText,
  });

  @override
  State<ModernImagePicker> createState() => _ModernImagePickerState();
}

class _ModernImagePickerState extends State<ModernImagePicker>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  late Animation<double> _fadeAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: UIConstants.durationFast,
      vsync: this,
    );

    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 0.95,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: UIConstants.curveNormal,
    ));

    _fadeAnimation = Tween<double>(
      begin: 1.0,
      end: 0.8,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: UIConstants.curveNormal,
    ));
  }

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

  bool get hasImage =>
      widget.imageBytes != null ||
      widget.imageFile != null ||
      (widget.imageUrl != null && widget.imageUrl!.isNotEmpty);

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

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Label
        if (widget.label != null) ...[
          Text(
            widget.label!,
            style: theme.textTheme.titleMedium?.copyWith(
              color: colorScheme.onSurface,
              fontWeight: FontWeight.w600,
            ),
          ),
          const SizedBox(height: UIConstants.spacing12),
        ],

        // Image Container
        GestureDetector(
          onTapDown: (_) => _animationController.forward(),
          onTapUp: (_) => _animationController.reverse(),
          onTapCancel: () => _animationController.reverse(),
          onTap: widget.onPickImage,
          child: AnimatedBuilder(
            animation: _animationController,
            builder: (context, child) {
              return Transform.scale(
                scale: _scaleAnimation.value,
                child: FadeTransition(
                  opacity: _fadeAnimation,
                  child: Container(
                    height: widget.height,
                    width: widget.width ?? double.infinity,
                    decoration: BoxDecoration(
                      borderRadius: widget.borderRadius ??
                          BorderRadius.circular(UIConstants.radius16),
                      border: Border.all(
                        color: widget.errorText != null
                            ? colorScheme.error
                            : colorScheme.outline.withOpacity(0.3),
                        width: 2,
                      ),
                      boxShadow: [
                        BoxShadow(
                          color: colorScheme.shadow.withOpacity(0.1),
                          blurRadius: 8,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: ClipRRect(
                      borderRadius: widget.borderRadius ??
                          BorderRadius.circular(UIConstants.radius16),
                      child: Stack(
                        children: [
                          // Image or Placeholder
                          if (hasImage)
                            _buildImageWidget()
                          else
                            _buildPlaceholder(theme, colorScheme),

                          // Loading Overlay
                          if (widget.isLoading)
                            _buildLoadingOverlay(colorScheme),

                          // Remove Button
                          if (hasImage &&
                              widget.showRemoveButton &&
                              widget.onRemoveImage != null)
                            _buildRemoveButton(colorScheme),
                        ],
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        ),

        // Hint Text
        if (widget.hint != null) ...[
          const SizedBox(height: UIConstants.spacing8),
          Text(
            widget.hint!,
            style: theme.textTheme.bodySmall?.copyWith(
              color: colorScheme.onSurfaceVariant,
            ),
          ),
        ],

        // Error Text
        if (widget.errorText != null) ...[
          const SizedBox(height: UIConstants.spacing8),
          Text(
            widget.errorText!,
            style: theme.textTheme.bodySmall?.copyWith(
              color: colorScheme.error,
            ),
          ),
        ],

        // Action Buttons
        const SizedBox(height: UIConstants.spacing16),
        Row(
          children: [
            Expanded(
              child: ModernButton(
                text: hasImage ? 'Change Image' : 'Pick Image',
                type: ModernButtonType.outline,
                size: ModernButtonSize.medium,
                icon: Icon(hasImage ? Icons.edit : Icons.add_photo_alternate),
                onPressed: widget.isLoading ? null : widget.onPickImage,
                isLoading: widget.isLoading,
              ),
            ),
            if (hasImage && widget.onRemoveImage != null) ...[
              const SizedBox(width: UIConstants.spacing12),
              ModernButton(
                text: 'Remove',
                type: ModernButtonType.danger,
                size: ModernButtonSize.medium,
                icon: Icon(Icons.delete_outline),
                onPressed: widget.isLoading ? null : widget.onRemoveImage,
              ),
            ],
          ],
        ),
      ],
    );
  }

  Widget _buildImageWidget() {
    if (widget.imageBytes != null) {
      return Image.memory(
        widget.imageBytes!,
        width: double.infinity,
        height: double.infinity,
        fit: BoxFit.cover,
      );
    } else if (widget.imageFile != null) {
      return Image.file(
        widget.imageFile!,
        width: double.infinity,
        height: double.infinity,
        fit: BoxFit.cover,
      );
    } else if (widget.imageUrl != null && widget.imageUrl!.isNotEmpty) {
      return Image.network(
        widget.imageUrl!,
        width: double.infinity,
        height: double.infinity,
        fit: BoxFit.cover,
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) return child;
          return Center(
            child: CircularProgressIndicator(
              value: loadingProgress.expectedTotalBytes != null
                  ? loadingProgress.cumulativeBytesLoaded /
                      loadingProgress.expectedTotalBytes!
                  : null,
            ),
          );
        },
        errorBuilder: (context, error, stackTrace) {
          return _buildPlaceholder(
              Theme.of(context), Theme.of(context).colorScheme);
        },
      );
    }
    return const SizedBox.shrink();
  }

  Widget _buildPlaceholder(ThemeData theme, ColorScheme colorScheme) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: colorScheme.surfaceVariant.withOpacity(0.3),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            widget.placeholderIcon ?? Icons.add_photo_alternate,
            size: UIConstants.iconSizeXLarge,
            color: colorScheme.onSurfaceVariant,
          ),
          const SizedBox(height: UIConstants.spacing12),
          Text(
            widget.placeholderText ?? 'Tap to select image',
            style: theme.textTheme.bodyLarge?.copyWith(
              color: colorScheme.onSurfaceVariant,
              fontWeight: FontWeight.w500,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: UIConstants.spacing8),
          Text(
            'JPG, PNG, GIF up to 10MB',
            style: theme.textTheme.bodySmall?.copyWith(
              color: colorScheme.onSurfaceVariant,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildLoadingOverlay(ColorScheme colorScheme) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: colorScheme.surface.withOpacity(0.8),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(
              color: colorScheme.primary,
            ),
            const SizedBox(height: UIConstants.spacing12),
            Text(
              'Uploading...',
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: colorScheme.onSurface,
                  ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRemoveButton(ColorScheme colorScheme) {
    return Positioned(
      top: UIConstants.spacing8,
      right: UIConstants.spacing8,
      child: Container(
        decoration: BoxDecoration(
          color: colorScheme.error,
          shape: BoxShape.circle,
          boxShadow: [
            BoxShadow(
              color: colorScheme.shadow.withOpacity(0.3),
              blurRadius: 4,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: IconButton(
          onPressed: widget.onRemoveImage,
          icon: Icon(
            Icons.close,
            color: colorScheme.onError,
            size: UIConstants.iconSizeSmall,
          ),
          padding: const EdgeInsets.all(UIConstants.spacing4),
          constraints: const BoxConstraints(
            minWidth: 32,
            minHeight: 32,
          ),
        ),
      ),
    );
  }
}
