import 'dart:io';

import 'package:flutter/material.dart';
import 'package:Emma_home/main.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class MissingEvent extends StatefulWidget {
  const MissingEvent({super.key});

  @override
  _MissingEvent createState() => _MissingEvent();
}

class _MissingEvent extends State<MissingEvent> {
  bool isUploading = false;
  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;

    /*24 is for notification bar on Android*/

    // ScrollController und Status-Variable
    ScrollController scrollController = ScrollController();

    // Verfügbarer Bereich auf dem Bildschirm
    final screenWidth = MediaQuery.of(context).size.width;
    final screenHeight = MediaQuery.of(context).size.height;
    double statusBarHeight = MediaQuery.of(context).padding.top;
    double HeaderHeight = 60;
    double TimeButtonHeight = 35;
    double TimeButtonpadding = 20;
    double FooterHeight = 91;
    double bottomPadding = MediaQuery.of(context).padding.bottom;
    final staticContentheight = statusBarHeight +
        HeaderHeight +
        TimeButtonHeight +
        TimeButtonpadding +
        FooterHeight +
        bottomPadding;
    double amaountOfCategoryLines = 4; //singleCategories.categories.length/2;
    double paddingHeight = 10;
    double shaddowHeight = 10;

    final dynamicContentHeight =
        ((amaountOfCategoryLines + 1) * paddingHeight) +
            (amaountOfCategoryLines * shaddowHeight);
    final resultHeightRemove = staticContentheight + dynamicContentHeight;
    final int itemHeight =
        ((screenHeight - resultHeightRemove) / 4).toInt(); //240-90) / 4;
    final double itemWidth = (size.width - 40) / 2;
    MediaQueryData queryData;
    queryData = MediaQuery.of(context);
    late File imageFile = File("");
    bool isloaded = false;
    final ImagePicker picker = ImagePicker();

    Future<void> pickImage() async {
      final XFile? image = await picker.pickImage(
        source: ImageSource.gallery,
        // Add any desired options, such as image quality
        //imageQuality: 100,
        //maxWidth: 800,
        //maxHeight: 600,
      );

      if (image != null) {
        setState(() {
          imageFile = File(image.path);
          isloaded = true;
          isUploading = true;
          setState(() {});
        });
        // Use the image file
        final String imagePath = image.path;
        try {
          final fileBytes = await image.readAsBytes();
          DateTime now = DateTime.now();
          // Datums- und Zeitformat definieren
          DateFormat formatter = DateFormat(
              'yyyyMMddHHmmss'); // Beachte das große 'HH' für 24-Stunden-Format

          // Datum und Uhrzeit als String formatieren
          String formattedDateTime = formatter.format(now);
          final fileName = '${formattedDateTime}_${image.name}';
          await supabase.storage.from('event_upload').uploadBinary(
                fileName,
                fileBytes,
              );
          setState(() {
            isUploading = false;
          });
        } catch (e) {
          print(e);
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('Error uploading file: ${e.toString()}'),
            ),
          );
        }
        print('Image path: $imagePath');
        dialogSave(context);
      } else {
        print('No image selected.');
      }
    }

    Future<void> captureImage() async {
      final XFile? image = await picker.pickImage(
        source: ImageSource.camera,
        //imageQuality: 100,
      );

      if (image != null) {
        setState(() {
          isUploading = true;
        });
        final String imagePath = image.path;
        try {
          final fileBytes = await image.readAsBytes();
          final fileName = '${TimeOfDay.now()}_${image.name}';
          await supabase.storage.from('event_upload').uploadBinary(
                fileName,
                fileBytes,
              );
          setState(() {
            isUploading = false;
          });
        } catch (e) {
          print(e);
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('Error uploading file: ${e.toString()}'),
            ),
          );
        }
        print('Image path: $imagePath');
        dialogSave(context);
      } else {
        print('No image captured.');
      }
    }

    var appBar = AppBar(
      leading: SizedBox(
        height: 60,
        width: 63,
        child: IconButton(
          icon: Image.asset('assets/images/logo.png'),
          onPressed: () {
            // Open drawer or perform action
          },
        ),
      ),
      title: Row(
        children: [
          const SizedBox(
            height: 10, //height of button
            width: 20, //width of button
            child: Icon(Icons.keyboard_arrow_down),
          ),
          const SizedBox(
            //width of button
            width: 10,
          ),
          SizedBox(
            width: 100.0,
            child: TextField(
              controller: TextEditingController(text: "Ingolstadt"),
              decoration: const InputDecoration(
                border: UnderlineInputBorder(),
              ),
            ),
          ),
        ],
      ),
      actions: [
        IconButton(
          icon: const Icon(Icons.search),
          onPressed: () {
            // Perform search action
          },
        ),
        const SizedBox(
          height: 40,
          child: VerticalDivider(
            thickness: 1,
            width: 20,
            color: Colors.black,
          ),
        ),
        SizedBox(
          height: 50, //height of button
          //width of button
          child: IconButton(
            icon: Image.asset('assets/images/Login.png'),
            onPressed: () {},
          ),
        ),
      ],
      bottom: PreferredSize(
        preferredSize: const Size.fromHeight(1.0),
        child: Container(
          color: Colors.black,
          height: 1.0,
        ),
      ),
      flexibleSpace: Container(),
    );
    var body = Stack(children: [
      Container(
        padding: const EdgeInsets.all(22.0),
        width: double.infinity,
        //height: 952,
        //clipBehavior: Clip.antiAlias,
        child: Column(
          children: [
            const SizedBox(height: 10),
            const Align(
              alignment: Alignment.centerLeft,
              child: Text(
                'Fehlendes Event bei uns?',
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 24,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w800,
                  height: 0,
                ),
              ),
            ),
            const SizedBox(height: 10),
            Align(
              alignment: Alignment.centerLeft,
              child: SizedBox(
                width: double.infinity,
                height: 144,
                child: RichText(
                  text: const TextSpan(
                    text:
                        'Du hast unterwegs ein Event gesehen, welches noch nicht bei uns in der Liste steht? Schicke uns das Foto von dem Event zu. Wir werden diese, wenn nicht schon  geschehen den Events hinzufügen. Danke für deine Unterstützung!',
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 16,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w400,
                      height: 1.5, // Ein vernünftigerer Zeilenabstand
                    ),
                  ),
                ),
              ),
            ),
            const SizedBox(height: 10),
            Container(
              width: 300,
              height: 200,
              padding: const EdgeInsets.symmetric(horizontal: 70, vertical: 85),
              decoration: ShapeDecoration(
                color: const Color(0xFFEDEDED),
                shape: RoundedRectangleBorder(
                  side: const BorderSide(
                    width: 1,
                    strokeAlign: BorderSide.strokeAlignOutside,
                  ),
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
              child: SizedBox(
                width: 200, // Breite des Buttons
                height: 50,
                child: OutlinedButton.icon(
                  icon: const Icon(
                    Icons.image,
                    size: 10,
                  ),
                  onPressed: () {
                    pickImage();
                  },
                  style: ButtonStyle(
                    side: WidgetStateProperty.all(
                      const BorderSide(
                        color: Colors.red,
                        width: 1,
                      ),
                    ),
                  ),
                  label: const Text(
                    'Bild hochladen',
                  ),
                ),
              ),
            ),

            /* Padding(
              padding: const EdgeInsets.all(8.0),
              child: !isloaded
                  ? Image.network(
                      "https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/No_image_available.svg/2048px-No_image_available.svg.png",
                      width: 100, // Maximalbreite des Bildes
                      height: 100, // Maximalhöhe des Bildes
                      fit: BoxFit.contain,
                    )
                  : Image.file(imageFile)), */
            const SizedBox(height: 10),
            Row(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  child: const Text(
                    'Bild  aufnehmen',
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 18,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w500,
                      height: 0,
                    ),
                  ),
                ),
                const SizedBox(
                  width: 10,
                ),
                Container(
                  width: 85,
                  height: 37,
                  padding:
                      const EdgeInsets.symmetric(horizontal: 15, vertical: 5),
                  clipBehavior: Clip.antiAlias,
                  decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                      side: const BorderSide(width: 2),
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      SizedBox(
                        width: 23,
                        height: 20.70,
                        child: IconButton(
                          icon: const FaIcon(FontAwesomeIcons.camera, size: 20),
                          onPressed: () {
                            // Füge hier die YouTube-Aktion hinzu
                            captureImage();
                          },
                          padding: EdgeInsets
                              .zero, // Entfernt das Padding des IconButton
                          constraints:
                              const BoxConstraints(), // Entfernt die Standardbeschränkungen
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                /* Container(
                width: 160,
                height: 44,
                padding: const EdgeInsets.all(10),
                decoration: ShapeDecoration(
                  shape: RoundedRectangleBorder(
                    side: BorderSide(width: 2),
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                     Text(
                      'Abrechen',
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 18,
                        fontFamily: 'Inter',
                        fontWeight: FontWeight.w500,
                        height: 0.07,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                width: 10,
              ),
              Container(
                width: 160,
                height: 44,
                padding: const EdgeInsets.all(10),
                decoration: ShapeDecoration(
                  color: Colors.black,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      'Senden',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontFamily: 'Inter',
                        fontWeight: FontWeight.w500,
                        height: 0.07,
                      ),
                    ), 
                  ],
                ),
              ),*/
              ],
            ),
/*           const SizedBox(height: 10),
          Text(
            'Bock dein Event bei uns zu \npräsentieren? ',
            style: TextStyle(
              color: Colors.black,
              fontSize: 24,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w800,
              height: 0,
            ),
          ),
          const SizedBox(height: 10),
          SizedBox(
            width: 328,
            height: 48,
            child: Text.rich(
              TextSpan(
                children: [
                  TextSpan(
                    text:
                        'Melde dich hier bei uns als Host an.\nWir freuen uns auf dich! ',
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 18,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w500,
                      height: 0.09,
                    ),
                  ),
                  TextSpan(
                    text: '>>Link hier',
                    style: TextStyle(
                      color: Color(0xFF3985CC),
                      fontSize: 18,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w500,
                      height: 0.07,
                    ),
                  ),
                ],
              ),
            ),
          ), */
          ],
        ),
      ),
      // AnimatedOpacity für das Overlay
      AnimatedOpacity(
        opacity: isUploading ? 1.0 : 0.0, // Sichtbarkeit steuern
        duration: const Duration(milliseconds: 300), // Dauer der Animation
        curve: Curves.easeInOut, // Animationskurve
        child: isUploading
            ? Container(
                width: MediaQuery.of(context).size.width, // Volle Breite
                height: MediaQuery.of(context).size.height, // Volle Höhe
                color: Colors.black.withOpacity(0.5), // Halbtransparentes Grau
                child: const Center(
                  child: CircularProgressIndicator(
                    color: Colors.white,
                  ),
                ),
              )
            : const SizedBox.shrink(), // Nichts anzeigen, wenn nicht sichtbar
      ),
    ]);

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: appBar,
      body: body,
    );
  }
}

Future<void> dialogSave(BuildContext context) {
  return showDialog<void>(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: const Text('Bild wurde gespeichert'),
        content: const Text(
          'Vielen Dank!\n'
          'Das Bild wurde erfolgreich hochgeladen!\n',
        ),
        actions: <Widget>[
          TextButton(
            style: TextButton.styleFrom(
              textStyle: Theme.of(context).textTheme.labelLarge,
            ),
            child: const Text('OK'),
            onPressed: () {
              Navigator.popUntil(context, (route) => route.isFirst);
            },
          ),
        ],
      );
    },
  );
}
