import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:dart_ipify/dart_ipify.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:localstore/localstore.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shimmer/shimmer.dart';

import '../../src/pages/pdf_viewer.dart';
import '../models/avisos.dart';
import '../providers/avisos_provider.dart';
import '../widgets/deslizar.dart';

class AvisosPage extends StatefulWidget {
  @override
  _AvisosPageState createState() => _AvisosPageState();
}

class _AvisosPageState extends State<AvisosPage> {
  final _meses = {
    'JAN':'01','FEB':'02','MAR':'03','APR':'04','MAY':'05','JUN':'06',
    'JUL':'07','AUG':'08','SEP':'09','OCT':'10','NOV':'11','DEC':'12'
  };
  final _avisosProvider = AvisosProvider();
  final db = Localstore.instance;

  bool _construyendoAviso = false;
  bool _deslizo = false;
  bool _isLoading = true;
  List<TableRow> _tableRows = [];

  late Avisos _avisos;
  late String _ip;
  late Map<String, dynamic> _info;

  @override
  void initState() {
    super.initState();

    initIP();
  }

  Future<void> initIP() async{
    //_ip = await GetIp.ipAddress;
    _ip = await Ipify.ipv4();

    final items = await db.collection('clientes').get();
    final key = items!.keys.last;

    _info = items[key];

    final avisos = await _avisosProvider.fetchAvisos(_info['accesToken'], _info['dinum']);
    _avisos = avisos;
    _buildAvisosTable();

    setState(() => _isLoading = false);
  }

  void showViewer(File document) {
    setState(() => _construyendoAviso = false);
    Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => PDFViewer(
          localFile: true,
          file: document,
        )
    ));
  }

  @override
  Widget build(BuildContext context) {
    final _screenSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Avisos',
          style: GoogleFonts.roboto(
            fontWeight: FontWeight.w700,
            color: const Color(0xFF67616B),
          ),
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        iconTheme: const IconThemeData(
          color: Color.fromRGBO(255, 0, 0, 1),
        ),
      ),
      body: SafeArea(
        child: _isLoading ? const Center(
          child: CircularProgressIndicator(),
        ) : Stack(
          alignment: Alignment.center,
          children: [
            SizedBox(
              width: _screenSize.width,
              height: _screenSize.height,
              child: Stack(
                children: [
                  Positioned(
                    bottom: 0.0,
                    right: 0.0,
                    child: Image.asset(
                      'assets/carteraVencer.png',
                      width: _screenSize.width*0.75,
                      fit: BoxFit.cover,
                    ),
                  ),
                  Container(
                    width: _screenSize.width,
                    height: _screenSize.height,
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          NotificationListener<ScrollNotification>(
                            onNotification: (scrollNotification){
                              if(scrollNotification is ScrollStartNotification){
                                _onStartScroll(scrollNotification.metrics);
                              }
                              return true;
                            },
                            child: SingleChildScrollView(
                              scrollDirection: Axis.horizontal,
                              child: Container(
                                width: 512.0,
                                child: Table(
                                  defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                                  children: _tableRows,
                                  columnWidths: {
                                    0: FlexColumnWidth(2.5),
                                    1: FlexColumnWidth(3),
                                    2: FlexColumnWidth(1.5),
                                    3: FlexColumnWidth(1.75)
                                  },
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
            AnimatedCrossFade(
              firstChild: Container(),
              secondChild: AlertDialog(
                content: Shimmer.fromColors(
                  baseColor: const Color(0xFFB40404),
                  highlightColor: const Color(0x55FF0000),
                  child: Text(
                    'Cargando aviso...',
                    textAlign: TextAlign.center,
                    style: GoogleFonts.roboto(
                        fontWeight: FontWeight.bold,
                        fontSize: 24.0
                    ),
                  ),
                ),
                contentPadding: const EdgeInsets.all(16.0),
              ),
              duration: const Duration(milliseconds: 250),
              crossFadeState: _construyendoAviso ? CrossFadeState.showSecond : CrossFadeState.showFirst,
            ),
            if(!_deslizo)
              Positioned(
                child: Deslizar(),
                top: 16.0,
                right: 16.0,
              ),
          ],
        ),
      ),
    );
  }

  _buildAvisosTable(){
    bool par = false;
    List<TableRow> tableRows = _avisos.result!.map((aviso){
      String dateAviso = aviso.feci!.substring(0, 2);
      dateAviso += '/' + _meses[aviso.feci!.substring(3,6)]!;
      dateAviso += '/20' + aviso.feci!.substring(7);
      par = !par;

      return TableRow(
          decoration: BoxDecoration(
              color: !par ? const Color(0x55CCCCCC) : const Color.fromRGBO(0, 0, 0, 0)
          ),
          children: [
            Container(
              padding: const EdgeInsets.all(4.0),
              child: Text(
                dateAviso,
                style: GoogleFonts.roboto(
                    fontSize: 18.0
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Container(
              padding: const EdgeInsets.all(4.0),
              child: Text(
                aviso.titu!,
                style: GoogleFonts.roboto(
                    fontSize: 18.0
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Container(
              alignment: Alignment.center,
              child: IconButton(
                icon: const Icon(
                    Icons.remove_red_eye
                ),
                onPressed: (){
                  setState(() => _construyendoAviso = true);
                  _avisosProvider.verAviso(_info['accesToken'], aviso.idav!, _info['dinum'], aviso.leido! ? "LE" : "NL", _ip).then((avisoArch){
                    _createFileFromString(avisoArch.result!.contenido!, avisoArch.result!.nombre!).then((document){
                      if(document == null){
                        Fluttertoast.showToast(
                            msg: '¡Hubo un error al abrir el PDF!',
                            toastLength: Toast.LENGTH_LONG,
                            timeInSecForIosWeb: 3,
                            gravity: ToastGravity.CENTER
                        );
                      }else{
                        showViewer(document);
                      }
                    });
                  });
                } ,
              ),
            ),
            Container(
              padding: const EdgeInsets.all(4.0),
              child: Text(
                !aviso.leido! ? 'Leído' : 'No leído',
                style: GoogleFonts.roboto(
                    color: !aviso.leido! ? Color(0xFF00FF00) : const Color(0xFFFF0000),
                    fontSize: 18.0
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            )
          ]
      );
    }).toList();

    setState(() {
      _tableRows = tableRows;
      _tableRows.insert(0, TableRow(
          decoration: BoxDecoration(
              color: Color(0x55CCCCCC)
          ),
          children: [
            Container(
              padding: EdgeInsets.all(4.0),
              child: Text(
                'Fecha de Publicación',
                style: GoogleFonts.roboto(
                    color: Color(0xFF67616B),
                    fontWeight: FontWeight.w700,
                    fontSize: 18.0
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Container(
              padding: EdgeInsets.all(4.0),
              child: Text(
                'Título',
                style: GoogleFonts.roboto(
                    color: Color(0xFF67616B),
                    fontWeight: FontWeight.w700,
                    fontSize: 18.0
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Container(
              padding: EdgeInsets.all(4.0),
              child: Text(
                'Acciones',
                style: GoogleFonts.roboto(
                    color: Color(0xFF67616B),
                    fontWeight: FontWeight.w700,
                    fontSize: 18.0
                ),
                overflow: TextOverflow.ellipsis,
                maxLines: 2,
              ),
            ),
            Container(
              padding: EdgeInsets.all(4.0),
              child: Text(
                'Estatus',
                style: GoogleFonts.roboto(
                    color: Color(0xFF67616B),
                    fontWeight: FontWeight.w700,
                    fontSize: 18.0
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            )
          ]
      ));
    });
  }

  Future<File> _createFileFromString(String encoded, String name) async{
    Uint8List bytes = base64Decode(encoded);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = File(
        "$dir/$name"
    );
    await file.writeAsBytes(bytes);
    return file;
  }

  _onStartScroll(ScrollMetrics metrics) => setState(() => _deslizo = true);
}
