import 'dart:async';

import 'package:clock/clock.dart';
import 'package:drift/drift.dart' show Value;
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:twonly/locator.dart';
import 'package:twonly/src/database/twonly.db.dart';
import 'package:twonly/src/services/mediafiles/mediafile.service.dart';
import 'package:twonly/src/utils/misc.dart';
import 'package:twonly/src/visual/elements/my_button.element.dart';
import 'package:twonly/src/visual/helpers/screenshot.helper.dart';

class SaveToGalleryButton extends StatefulWidget {
  const SaveToGalleryButton({
    required this.isLoading,
    required this.displayButtonLabel,
    required this.mediaService,
    this.storeImageAsOriginal,
    super.key,
  });
  final Future<ScreenshotImageHelper?> Function()? storeImageAsOriginal;
  final bool displayButtonLabel;
  final MediaFileService mediaService;
  final bool isLoading;

  @override
  State<SaveToGalleryButton> createState() => SaveToGalleryButtonState();
}

class SaveToGalleryButtonState extends State<SaveToGalleryButton> {
  bool _imageSaving = false;
  bool _imageSaved = false;

  @override
  Widget build(BuildContext context) {
    final isEnabled = !widget.isLoading && !_imageSaving;
    return MyButton(
      variant: MyButtonVariant.secondaryMiddle,
      onPressed: isEnabled
          ? () async {
              setState(() {
                _imageSaving = true;
              });

              if (widget.storeImageAsOriginal != null) {
                await widget.storeImageAsOriginal!();
              }

              final newMediaFile = await twonlyDB.mediaFilesDao
                  .insertOrUpdateMedia(
                    MediaFilesCompanion(
                      type: Value(widget.mediaService.mediaFile.type),
                      createdAt: Value(clock.now()),
                      stored: const Value(true),
                    ),
                  );

              if (newMediaFile != null) {
                final newService = MediaFileService(newMediaFile);

                if (widget.mediaService.tempPath.existsSync()) {
                  widget.mediaService.tempPath.copySync(
                    newService.tempPath.path,
                  );
                } else if (widget.mediaService.originalPath.existsSync()) {
                  widget.mediaService.originalPath.copySync(
                    newService.originalPath.path,
                  );
                }
                await newService.storeMediaFile();
              }

              if (mounted) {
                setState(() {
                  _imageSaved = true;
                  _imageSaving = false;
                });
              }
            }
          : null,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (_imageSaving || widget.isLoading)
            const SizedBox(
              width: 12,
              height: 12,
              child: CircularProgressIndicator.adaptive(
                strokeWidth: 1,
                valueColor: AlwaysStoppedAnimation(Colors.white),
              ),
            )
          else if (_imageSaved)
            const Icon(Icons.check, size: 14)
          else
            const FaIcon(FontAwesomeIcons.floppyDisk, size: 14),
          if (widget.displayButtonLabel) const SizedBox(width: 10),
          if (widget.displayButtonLabel)
            Text(
              _imageSaved
                  ? context.lang.shareImagedEditorSavedImage
                  : context.lang.shareImagedEditorSaveImage,
            ),
        ],
      ),
    );
  }
}
