import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/flutter_flow/upload_data.dart';
import 'package:hub/shared/utils/limited_text_size.dart';

// ignore: must_be_immutable
class MediaUploadButtonUtil extends StatefulWidget {
  final Function(FFUploadedFile) onUploadComplete;
  bool isUploading;
  final String labelText;
  FFUploadedFile? uploadedFiles;

  MediaUploadButtonUtil({
    super.key,
    required this.onUploadComplete,
    required this.isUploading,
    required this.labelText,
    this.uploadedFiles,
  });

  @override
  State<MediaUploadButtonUtil> createState() => _MediaUploadButtonUtilState();
}

class _MediaUploadButtonUtilState extends State<MediaUploadButtonUtil> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    double limitedInputTextSize = LimitedFontSizeUtil.getInputFontSize(context);
    bool _isLoading = false;

    return Builder(
      builder: (context) {
        if (widget.uploadedFiles != null &&
            widget.uploadedFiles!.bytes!.isNotEmpty) {
          {
            return InkWell(
              splashColor: Colors.transparent,
              focusColor: Colors.transparent,
              hoverColor: Colors.transparent,
              highlightColor: Colors.transparent,
              onTap: () async {
                setState(() {
                  widget.isUploading = false;
                  widget.uploadedFiles =
                      FFUploadedFile(bytes: Uint8List.fromList([]));
                  widget.onUploadComplete(widget.uploadedFiles!);
                });
              },
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8.0),
                child: Image.memory(
                  widget.uploadedFiles!.bytes ?? Uint8List.fromList([]),
                  width: 300.0,
                  height: 200.0,
                  fit: BoxFit.cover,
                ),
              ),
            );
          }
        } else {
          return Stack(
            children: [
              Align(
                alignment: const AlignmentDirectional(0.0, 0.0),
                child: GestureDetector(
                  onTap: () async {
                    setState(() {
                      _isLoading = true;
                    });
                    final selectedMedia =
                        await selectMediaWithSourceBottomSheet(
                      context: context,
                      imageQuality: 100,
                      allowPhoto: true,
                      includeDimensions: true,
                    );
                    if (selectedMedia != null) {
                      setState(() => widget.isUploading = true);
                      var selectedUploadedFiles = <FFUploadedFile>[];

                      try {
                        final message = FFLocalizations.of(context)
                            .getVariableText(
                                enText: 'Uploading file...',
                                ptText: 'Enviando arquivo...');
                        showUploadMessage(
                          context,
                          message,
                          showLoading: true,
                        );
                        selectedUploadedFiles = selectedMedia
                            .map((m) => FFUploadedFile(
                                  name: m.storagePath.split('/').last,
                                  bytes: m.bytes,
                                  height: m.dimensions?.height,
                                  width: m.dimensions?.width,
                                  // blurHash: m.blurHash,
                                ))
                            .toList();
                      } finally {
                        ScaffoldMessenger.of(context).hideCurrentSnackBar();
                        widget.isUploading = false;
                      }
                      if (selectedUploadedFiles.length ==
                          selectedMedia.length) {
                        setState(() {
                          widget.uploadedFiles = selectedUploadedFiles.first;
                        });
                        widget.onUploadComplete(widget.uploadedFiles!);
                        final message = FFLocalizations.of(context)
                            .getVariableText(
                                enText: 'Success!', ptText: 'Sucesso!');
                        showUploadMessage(context, message);
                      } else {
                        setState(() {
                          _isLoading = false;
                        });
                        final message = FFLocalizations.of(context)
                            .getVariableText(
                                enText: 'Failed to upload data',
                                ptText: 'Falha ao enviar dados');
                        showUploadMessage(context, message);
                        return;
                      }
                    } else {
                      setState(() {
                        _isLoading = false;
                      });
                    }
                  },
                  child: Center(
                    child: Container(
                      width: MediaQuery.of(context).size.width * 0.8,
                      height: 120,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8.0),
                        border: Border.all(
                          color: FlutterFlowTheme.of(context).customColor6,
                          width: 1.0,
                        ),
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.max,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          _isLoading
                              ? SizedBox(
                                  width: 30.0,
                                  height: 30.0,
                                  child: CircularProgressIndicator(
                                    valueColor: AlwaysStoppedAnimation<Color>(
                                      FlutterFlowTheme.of(context).primary,
                                    ),
                                  ),
                                )
                              : Icon(
                                  Icons.photo_camera,
                                  color: FlutterFlowTheme.of(context).primary,
                                  size: 30.0,
                                ),
                          Padding(
                            padding: const EdgeInsets.fromLTRB(0, 15, 0, 0),
                            child: Text(
                              FFLocalizations.of(context).getText(
                                'p4ftwxcy',
                              ),
                              textAlign: TextAlign.center,
                              style: FlutterFlowTheme.of(context)
                                  .titleSmall
                                  .override(
                                    fontFamily: FlutterFlowTheme.of(context)
                                        .titleSmallFamily,
                                    color: FlutterFlowTheme.of(context)
                                        .primaryText,
                                    fontSize: limitedInputTextSize,
                                    letterSpacing: 0.0,
                                    useGoogleFonts: GoogleFonts.asMap()
                                        .containsKey(
                                            FlutterFlowTheme.of(context)
                                                .titleSmallFamily),
                                  ),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ],
          );
        }
      },
    );
  }
}
