import 'dart:convert' show base64Decode;

import 'package:flutter/material.dart';
import 'package:fotodocumentation/dto/customer_dto.dart';
import 'package:fotodocumentation/dto/picture_dto.dart';
import 'package:fotodocumentation/pages/customer/picture_fullscreen_dialog.dart';
import 'package:fotodocumentation/pages/ui_utils/general_style.dart';
import 'package:fotodocumentation/utils/di_container.dart';
import 'package:intl/intl.dart';

class PictureWidget extends StatefulWidget {
  final CustomerDto customerDto;
  final PictureDto pictureDto;
  const PictureWidget({super.key, required this.customerDto, required this.pictureDto});

  @override
  State<PictureWidget> createState() => _PictureWidgetState();
}

class _PictureWidgetState extends State<PictureWidget> {
  GeneralStyle get _generalStyle => DiContainer.get();

  late PictureDto _selectedPicture;
  late DateFormat _dateFormat;
  final ScrollController _commentScrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _dateFormat = DateFormat('dd MMMM yyyy');
    _selectedPicture = widget.pictureDto;
  }

  @override
  void dispose() {
    _commentScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final pictures = widget.customerDto.pictures;
    final currentIndex = pictures.indexWhere((p) => p.id == _selectedPicture.id);
    final hasPrevious = currentIndex > 0;
    final hasNext = currentIndex < pictures.length - 1;

    return Stack(
      children: [
        Container(
          width: double.infinity,
          height: double.infinity,
          color: _generalStyle.pageBackgroundColor,
          child: Padding(
            padding: const EdgeInsets.only(top: 50.0, left: 50.0, right: 50.0, bottom: 8.0),
            child: _body(context),
          ),
        ),
        // Left navigation button
        if (hasPrevious)
          Positioned(
            left: 0,
            top: 0,
            bottom: 0,
            child: GestureDetector(
              onTap: () => _navigateToPicture(currentIndex - 1),
              child: MouseRegion(
                cursor: SystemMouseCursors.click,
                child: Container(
                  width: 50,
                  color: Colors.transparent,
                  child: Center(
                    child: Container(
                      decoration: BoxDecoration(
                        color: _generalStyle.primaryButtonBackgroundColor,
                        shape: BoxShape.circle,
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Icon(
                          Icons.chevron_left,
                          color: _generalStyle.primaryButtonTextColor,
                          size: 32,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        // Right navigation button
        if (hasNext)
          Positioned(
            right: 0,
            top: 0,
            bottom: 0,
            child: GestureDetector(
              onTap: () => _navigateToPicture(currentIndex + 1),
              child: MouseRegion(
                cursor: SystemMouseCursors.click,
                child: Container(
                  width: 50,
                  color: Colors.transparent,
                  child: Center(
                    child: Container(
                      decoration: BoxDecoration(
                        color: _generalStyle.primaryButtonBackgroundColor,
                        shape: BoxShape.circle,
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Icon(
                          Icons.chevron_right,
                          color: _generalStyle.primaryButtonTextColor,
                          size: 32,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        // Close button
        Positioned(
          top: 16,
          right: 16,
          child: Container(
            decoration: BoxDecoration(
              color: _generalStyle.primaryButtonBackgroundColor,
              shape: BoxShape.circle,
            ),
            child: IconButton(
              icon: Icon(Icons.close, color: _generalStyle.primaryButtonTextColor, size: 24),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ),
        ),
      ],
    );
  }

  void _navigateToPicture(int index) {
    final pictures = widget.customerDto.pictures;
    if (index >= 0 && index < pictures.length) {
      setState(() {
        _selectedPicture = pictures[index];
      });
    }
  }

  Widget _body(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final isNarrow = constraints.maxWidth < 800;
        return SingleChildScrollView(
          child: isNarrow
              ? Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _imageWidget(_selectedPicture),
                    const SizedBox(height: 32),
                    _contentWidget(_selectedPicture),
                  ],
                )
              : Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _imageWidget(_selectedPicture),
                    const SizedBox(width: 32),
                    Expanded(child: _contentWidget(_selectedPicture)),
                  ],
                ),
        );
      },
    );
  }

  Widget _imageWidget(PictureDto dto) {
    return GestureDetector(
      key: const Key("image"),
      behavior: HitTestBehavior.opaque,
      onTap: () => _showFullscreenImage(dto),
      child: MouseRegion(
        cursor: SystemMouseCursors.click,
        child: ConstrainedBox(
          constraints: const BoxConstraints(minWidth: 100, minHeight: 100),
          child: Image.memory(
            base64Decode(dto.image),
            fit: BoxFit.contain,
          ),
        ),
      ),
    );
  }

  void _showFullscreenImage(PictureDto dto) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return PictureFullscreenDialog(dto: dto);
      },
    );
  }

  Widget _contentWidget(PictureDto dto) {
    final labelStyle = TextStyle(
      fontWeight: FontWeight.normal,
      fontSize: 16,
      fontFamily: _generalStyle.fontFamily,
      color: _generalStyle.primaryTextLabelColor,
    );

    final contentStyle = TextStyle(
      fontWeight: FontWeight.bold,
      fontSize: 16,
      fontFamily: _generalStyle.fontFamily,
      color: _generalStyle.secondaryTextLabelColor,
    );

    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text(
        "INFORMATIONEN",
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 44,
          fontFamily: _generalStyle.fontFamily,
          color: _generalStyle.primaryTextLabelColor,
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(top: 20.0),
        child: Text(
          "APOTHEKE",
          style: labelStyle,
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(top: 4.0),
        child: Text(
          widget.customerDto.name,
          style: contentStyle,
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(top: 20.0),
        child: Text(
          "KUNDENNUMMER",
          style: labelStyle,
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(top: 4.0),
        child: Text(
          widget.customerDto.customerNumber,
          style: contentStyle,
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(top: 20.0),
        child: Text(
          "DATUM",
          style: labelStyle,
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(top: 4.0),
        child: Text(
          _dateFormat.format(dto.pictureDate),
          style: contentStyle,
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(top: 20.0),
        child: Text(
          "KOMMENTAR",
          style: labelStyle,
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(top: 4.0),
        child: Container(
          width: double.infinity,
          height: 150,
          decoration: BoxDecoration(
            border: Border.all(color: _generalStyle.secondaryTextLabelColor.withValues(alpha: 0.3)),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Scrollbar(
            controller: _commentScrollController,
            thumbVisibility: true,
            child: SingleChildScrollView(
              controller: _commentScrollController,
              padding: const EdgeInsets.all(8.0),
              child: Text(
                dto.comment ?? "",
                style: contentStyle,
              ),
            ),
          ),
        ),
      ),
    ]);
  }
}
