import 'dart:io';

import 'package:file_picker/file_picker.dart';
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 MultiFilesPicker extends StatefulWidget {
  final String label;
  final bool error;
  final List<File> files;
  final bool enabled;

  const MultiFilesPicker({Key key, this.files, this.label, this.error = false, this.enabled = true}) : super(key: key);

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

class _MultiFilesPickerState extends State<MultiFilesPicker> with TickerProviderStateMixin {
  Size _size;

  @override
  Widget build(BuildContext context) {
    _size = MediaQuery.of(context).size;
    Subtitle subtitle = AppLocalization.of(context).subtitle;
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: const Color(0xfff5f5f5),
        border: Border.all(
          color: const 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: widget.enabled
                    ? () {
                        // onImagePick(_subtitle);
                        onFilePicker(subtitle);
                      }
                    : null,
              ),
            ],
          ),
          12.height,
          AnimatedSize(
            duration: const Duration(milliseconds: 400),
            child: !widget.error
                ? const 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: const Duration(milliseconds: 400),
            child: Container(
              key: ValueKey(widget.files.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.files.isEmpty
                  ? MaterialButton(
                      onPressed: widget.enabled
                          ? () {
                              // onImagePick(_subtitle);
                              onFilePicker(subtitle);
                            }
                          : null,
                      child: Center(
                          child: Icon(
                        Icons.file_upload,
                        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.files.length, (index) {
                        File _image = widget.files[index];
                        return MultiFilesPickerItem(
                          file: _image,
                          onRemoveTap: (image) {
                            widget.files.remove(image);
                            setState(() {});
                          },
                        );
                      }),
                    ),
            ),
          ),
        ],
      ),
    );
  }

  onFilePicker(Subtitle subtitle) async {
    FilePickerResult result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowMultiple: true,
      allowedExtensions: ['jpg', 'png', 'pdf', 'doc', 'docx', 'xlsx', 'pptx'],
    );
    if (result != null) {
      for (var path in result.paths) {
        widget.files.insert(0, File(path));
      }
      setState(() {});
    }
  }

  onImagePick(Subtitle subtitle) async {
    if (widget.files.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.files.insert(0, fileImage);
        setState(() {});
      }
    }

    setState(() {});
  }
}
