import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:provider/provider.dart';
import 'package:relatica/models/exec_error.dart';
import 'package:result_monad/result_monad.dart';

import '../../models/gallery_data.dart';
import '../../models/media_attachment_uploads/new_entry_media_items.dart';
import '../../services/gallery_service.dart';
import '../../services/media_upload_attachment_helper.dart';
import '../../utils/active_profile_selector.dart';
import '../../utils/snackbar_builder.dart';
import '../padding.dart';
import 'media_upload_editor_control.dart';

final _logger = Logger('$MediaUploadsControl');

class MediaUploadsControl extends StatefulWidget {
  final NewEntryMediaItems entryMediaItems;

  const MediaUploadsControl({super.key, required this.entryMediaItems});

  @override
  State<MediaUploadsControl> createState() => _MediaUploadsControlState();
}

class _MediaUploadsControlState extends State<MediaUploadsControl> {
  var useGalleryName = false;
  final controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    _logger.finest('Building');
    final galleryManager = context
        .watch<ActiveProfileSelector<GalleryService>>()
        .activeEntry
        .value;
    final galleries = galleryManager.getGalleries();
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              'New Images',
              style: Theme.of(context).textTheme.titleLarge,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                IconButton(
                  onPressed: () async {
                    await MediaUploadAttachmentHelper.getNewImagesFromCamera()
                        .match(
                            onSuccess: (newEntries) => setState(() => widget
                                .entryMediaItems.attachments
                                .addAll(newEntries)),
                            onError: (error) {
                              buildSnackbar(context,
                                  'Error selecting attachments: $error');
                              logError(error, _logger);
                            });
                  },
                  icon: const Icon(Icons.camera_alt),
                ),
                IconButton(
                  onPressed: () async {
                    await MediaUploadAttachmentHelper.getImagesFromGallery()
                        .match(
                            onSuccess: (newEntries) => setState(() => widget
                                .entryMediaItems.attachments
                                .addAll(newEntries)),
                            onError: (error) {
                              if (mounted) {
                                buildSnackbar(context,
                                    'Error selecting attachments: $error');
                              }
                            });
                  },
                  icon: const Icon(Icons.add_to_photos),
                ),
              ],
            )
          ],
        ),
        if (widget.entryMediaItems.attachments.isNotEmpty)
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Checkbox(
                  value: useGalleryName,
                  onChanged: (value) => setState(() {
                        useGalleryName = value ?? false;
                        controller.text = '';
                        widget.entryMediaItems.albumName = '';
                      })),
              const Text('Use Gallery:'),
              const HorizontalPadding(
                width: 3,
              ),
              if (useGalleryName) ...[
                Expanded(
                  child: TextField(
                    controller: controller,
                    onChanged: (value) {
                      widget.entryMediaItems.albumName = value;
                    },
                    decoration: InputDecoration(
                      hintText: 'Type New or Select',
                      alignLabelWithHint: true,
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: Theme.of(context).colorScheme.background,
                        ),
                        borderRadius: BorderRadius.circular(5.0),
                      ),
                    ),
                  ),
                ),
                PopupMenuButton<GalleryData>(
                  onSelected: (gallery) {
                    setState(() {
                      controller.text = gallery.name;
                      widget.entryMediaItems.albumName = gallery.name;
                    });
                  },
                  itemBuilder: (context) => galleries
                      .map((g) => PopupMenuItem(value: g, child: Text(g.name)))
                      .toList(),
                )
              ],
              const HorizontalPadding(
                width: 2,
              ),
            ],
          ),
        ...widget.entryMediaItems.attachments.map(
          (m) => MediaUploadEditorControl(
            media: m,
            onDelete: () {
              widget.entryMediaItems.attachments.remove(m);
              setState(() {});
            },
          ),
        ),
      ],
    );
  }
}
