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/flutter_flow_widgets.dart';
import 'package:hub/flutter_flow/upload_data.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) {
    return Padding(
      padding: const EdgeInsetsDirectional.fromSTEB(24.0, 0.0, 24.0, 0.0),
      child: 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: FFButtonWidget(
                    onPressed: () async {
                      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(() {});
                          final message = FFLocalizations.of(context)
                              .getVariableText(
                                  enText: 'Failed to upload data',
                                  ptText: 'Falha ao enviar dados');
                          showUploadMessage(context, message);
                          return;
                        }
                      }
                    },
                    text: '',
                    icon: Icon(
                      Icons.photo_camera,
                      color: FlutterFlowTheme.of(context).accent1,
                      size: 30.0,
                    ),
                    options: FFButtonOptions(
                      width: double.infinity,
                      height: 120.0,
                      padding: const EdgeInsetsDirectional.fromSTEB(
                          0.0, 0.0, 0.0, 20.0),
                      iconPadding: const EdgeInsetsDirectional.fromSTEB(
                          14.0, 0.0, 0.0, 20.0),
                      color: FlutterFlowTheme.of(context).primaryBackground,
                      textStyle: FlutterFlowTheme.of(context)
                          .titleSmall
                          .override(
                            fontFamily:
                                FlutterFlowTheme.of(context).titleSmallFamily,
                            color: FlutterFlowTheme.of(context).primaryText,
                            fontSize: 16.0,
                            letterSpacing: 0.0,
                            useGoogleFonts: GoogleFonts.asMap().containsKey(
                                FlutterFlowTheme.of(context).titleSmallFamily),
                          ),
                      borderSide: BorderSide(
                        color: FlutterFlowTheme.of(context).accent1,
                        width: 0.2,
                      ),
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                  ),
                ),
                Align(
                  alignment: const AlignmentDirectional(0.0, 0.0),
                  child: Padding(
                    padding: const EdgeInsetsDirectional.fromSTEB(
                        10.0, 65.0, 10.0, 0.0),
                    child: Text(
                      widget.labelText,
                      style: FlutterFlowTheme.of(context).bodyMedium.override(
                            fontFamily:
                                FlutterFlowTheme.of(context).bodyMediumFamily,
                            color: FlutterFlowTheme.of(context).primaryText,
                            letterSpacing: 0.0,
                            useGoogleFonts: GoogleFonts.asMap().containsKey(
                                FlutterFlowTheme.of(context).bodyMediumFamily),
                          ),
                    ),
                  ),
                ),
              ],
            );
          }
        },
      ),
    );
  }
}
