import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:test_sa/controllers/localization/localization.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/models/subtitle.dart';
import 'package:test_sa/views/app_style/colors.dart';
import 'package:test_sa/views/app_style/sizing.dart';
import 'package:test_sa/views/widgets/buttons/app_flat_button.dart';

import 'multi_image_picker_item.dart';

class MultiImagesPicker extends StatefulWidget {
  final String label;
  final bool error;
  final List<File> images;

  const MultiImagesPicker({Key key, this.images, this.label, this.error = false}) : super(key: key);

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

class _MultiImagesPickerState extends State<MultiImagesPicker> with TickerProviderStateMixin {
  Size _size;

  @override
  Widget build(BuildContext context) {
    _size = MediaQuery.of(context).size;
    Subtitle _subtitle = AppLocalization.of(context).subtitle;
    return Container(
      padding: EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Color(0xfff5f5f5),
        border: Border.all(
          color: Color(0xffefefef),
        ),
        borderRadius: BorderRadius.circular(AppStyle.borderRadius * AppStyle.getScaleFactor(context)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //   SizedBox(height: 8 * AppStyle.getScaleFactor(context),),
          Row(
            children: [
              Expanded(
                child: Text(
                  widget.label ?? _subtitle.images,
                  style: Theme.of(context).textTheme.headline6.copyWith(
                        fontSize: 14,
                      ),
                  textScaleFactor: AppStyle.getScaleFactor(context),
                ),
              ),
              AFlatButton(
                text: _subtitle.add,
                onPressed: () {
                  onImagePick(_subtitle);
                },
              ),
            ],
          ),
          12.height,
          AnimatedSize(
            duration: Duration(milliseconds: 400),
            child: !widget.error
                ? SizedBox.shrink()
                : Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        _subtitle.imagesRequired,
                        style: Theme.of(context).textTheme.headline6.copyWith(
                              fontSize: 14,
                              color: AColors.red,
                            ),
                        textScaleFactor: AppStyle.getScaleFactor(context),
                      ),
                      SizedBox(
                        height: 8 * AppStyle.getScaleFactor(context),
                      ),
                    ],
                  ),
          ),
          AnimatedSwitcher(
            duration: Duration(milliseconds: 400),
            child: Container(
              key: ValueKey(widget.images.length),
              width: _size.width,
              height: 200 * AppStyle.getScaleFactor(context),
              padding: EdgeInsets.all(
                8 * AppStyle.getScaleFactor(context),
              ),
              alignment: Alignment.topLeft,
              decoration: BoxDecoration(
                border: Border.all(color: Theme.of(context).primaryColor, width: 2),
                borderRadius: BorderRadius.circular(8 * AppStyle.getScaleFactor(context)),
              ),
              child: widget.images.isEmpty
                  ? MaterialButton(
                      onPressed: () {
                        onImagePick(_subtitle);
                      },
                      child: Center(
                          child: Icon(
                        Icons.add_a_photo_outlined,
                        size: 48 * AppStyle.getScaleFactor(context),
                        color: Theme.of(context).primaryColor,
                      )),
                    )
                  : GridView.count(
                      crossAxisCount: 2,
                      //_size.width ~/ 80,
                      scrollDirection: Axis.horizontal,
                      mainAxisSpacing: 10,
                      crossAxisSpacing: 10,
                      children: List.generate(widget.images.length, (index) {
                        File _image = widget.images[index];
                        return MultiImagesPickerItem(
                          image: _image,
                          onRemoveTap: (image) {
                            widget.images.remove(image);
                            setState(() {});
                          },
                        );
                      }),
                    ),
            ),
          ),
        ],
      ),
    );
  }

  onImagePick(Subtitle _subtitle) async {
    if (widget.images.length >= 5) {
      Fluttertoast.showToast(msg: _subtitle.maxImagesNumberIs5);
      return;
    }
    ImageSource source = await showDialog(
        context: context,
        builder: (dialogContext) => CupertinoAlertDialog(
              actions: <Widget>[
                TextButton(
                  child: Text(_subtitle.pickFromCamera),
                  onPressed: () {
                    Navigator.of(dialogContext).pop(ImageSource.camera);
                  },
                ),
                TextButton(
                  child: Text(_subtitle.pickFromGallery),
                  onPressed: () {
                    Navigator.of(dialogContext).pop(ImageSource.gallery);
                  },
                ),
              ],
            ));
    if (source == null) return;

    final pickedFile = await ImagePicker().pickImage(source: source, imageQuality: 70, maxWidth: 800, maxHeight: 800);

    if (pickedFile != null) {
      File _fileImage = File(pickedFile.path);
      if (_fileImage != null) {
        widget.images.insert(0, _fileImage);
        setState(() {});
      }
    }

    setState(() {});
  }
}
