import 'dart:async';
import 'package:intl/intl.dart';
import 'package:oc_front/main.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:oc_front/models/shared.dart';
import 'package:oc_front/models/workflow.dart';
import 'package:oc_front/widgets/catalog.dart';
import 'package:oc_front/models/response.dart';
import 'package:oc_front/pages/abstract_page.dart';
import 'package:oc_front/models/resources/resources.dart';
import 'package:oc_front/core/models/workspace_local.dart';
import 'package:oc_front/core/sections/header/header.dart';
import 'package:oc_front/core/services/perms_service.dart';
import 'package:oc_front/widgets/items/shallow_item_row.dart';
import 'package:oc_front/widgets/dialog/shallow_creation.dart';
import 'package:oc_front/widgets/inputs/shallow_text_input.dart';
import 'package:oc_front/core/models/shared_workspace_local.dart';
import 'package:oc_front/widgets/inputs/shallow_dropdown_input.dart';
import 'package:oc_front/core/services/specialized_services/peer_service.dart';
import 'package:oc_front/core/services/specialized_services/shared_service.dart';
import 'package:oc_front/core/services/specialized_services/workflow_service.dart';

enum CollaborativeAreaType { global, collaborative_area, workspace, workflow, peer, resource }

class  SharedFactory implements AbstractFactory {
  @override GlobalKey getKey() { return key; }
  @override String? getSearch() { return ""; }
  @override void back(BuildContext context) { }
  static GlobalKey<SharedPageWidgetState> key = GlobalKey<SharedPageWidgetState>();
  @override bool searchFill() { return false; }
  @override Widget factory(GoRouterState state, List<String> args) { return SharedPageWidget(); }
  @override void search(BuildContext context, bool special) { }
}

class SharedPageWidget extends StatefulWidget {
  CollaborativeAreaType type = CollaborativeAreaType.global;
  bool showDialog = false;
  SharedPageWidget(): super(key: SharedFactory.key);
  @override SharedPageWidgetState createState() => SharedPageWidgetState();
  static void search(BuildContext context) { }
  static Widget factory() { return SharedPageWidget(); }
}
class SharedPageWidgetState extends State<SharedPageWidget> {
  SharedService service = SharedService();
  Widget getMenuItem(CollaborativeAreaType workspaceType, IconData icon) {
    var s = workspaceType == CollaborativeAreaType.global ? "dashboard" : workspaceType == CollaborativeAreaType.workspace ? "shared workspaces" : workspaceType == CollaborativeAreaType.workflow ? "shared workflows" : "peers engaged";
    return Tooltip( message: s,
      child: InkWell( mouseCursor: SystemMouseCursors.click,
        onTap: () => setState(() {
          widget.type = workspaceType;
        }),
        child: Container( width: 50, height: 50,
        color: widget.type == workspaceType ? darkColor : Colors.transparent,
        padding: const EdgeInsets.symmetric(vertical: 10), 
        child : Icon(icon, 
          color: widget.type == workspaceType ? Colors.white : Colors.white, size: 20))));
  }
  @override Widget build(BuildContext context) {
    GlobalKey<ShallowTextInputWidgetState> key = GlobalKey<ShallowTextInputWidgetState>();
    if (CollaborativeAreaLocal.current == null) { 
      Future.delayed( const Duration(microseconds: 100), () {
        HeaderConstants.setTitle("Choose a Collaborative Area");
        HeaderConstants.setDescription("select a shared workspace to continue");
      });
      if (!widget.showDialog) {
        Future.delayed( const Duration(milliseconds: 100), () {
          widget.showDialog = true;
          showDialog(
            barrierDismissible: false,
            context: context, 
            builder: (BuildContext ctx) => AlertDialog(
              titlePadding: EdgeInsets.zero,
              insetPadding: EdgeInsets.zero,
              backgroundColor: Colors.white,
              shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(0)),
              title: ShallowCreationDialogWidget(
                formKey: key,
                canClose: () => CollaborativeAreaLocal.current != null,
                context: context,
                load: (p0) async {
                  CollaborativeAreaLocal.current = p0;
                  HeaderConstants.setTitle("Collaborative Area <${CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current]?.name ?? ""}>");
                  HeaderConstants.setDescription(CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current]?.description ?? "");
                  Future.delayed(const Duration(seconds: 1), () => SharedFactory.key.currentState?.setState(() { widget.showDialog = false; }));
                },
                form: [
                  ShallowTextInputWidget(
                    change :(p0) => key.currentState?.setState(() {}),
                    canLoad: (po) => po != null && po.isNotEmpty,
                    type: CollaborativeAreaType.collaborative_area,
                    width: getMainWidth(context) <= 540 ? getMainWidth(context) - 140 : 400,
                    attr: "description",
                    color: Colors.black,
                    hintColor: Colors.grey,
                    hint: "enter collaborative area description...",
                    filled: midColor,
                  )
                ],
                create: PermsService.getPerm(Perms.COLLABORATIVE_AREA_CREATE) ? (p0) async => await SharedService().post(context, p0, {}).then((value) {
                  if (value.data != null) {
                      CollaborativeAreaLocal.current = value.data!.id;
                  }
                  CollaborativeAreaLocal.init(context, true);

                  HeaderConstants.setTitle("Collaborative Area <${CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current]?.name ?? ""}>");
                  HeaderConstants.setDescription(CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current]?.description ?? "");
                  Future.delayed(const Duration(seconds: 1), () => SharedFactory.key.currentState?.setState(() { widget.showDialog = false;  }));
                }) : null,
                type: CollaborativeAreaType.collaborative_area,
                all: () async { 
                  await CollaborativeAreaLocal.init(context, true);
                  return CollaborativeAreaLocal.workspaces.values.map( 
                  (e) => Shallow(id: e.id ?? "", name: e.name ?? "") ).toList();
                }
              )));
        });
      }
    } else {
      Future.delayed( const Duration(milliseconds: 100), () {
        HeaderConstants.setTitle("Collaborative Area <${CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current]?.name ?? ""}>");
        HeaderConstants.setDescription(CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current]?.description ?? "");
      });
    }
    Widget w = WorkspaceSharedPageWidget(type: widget.type);
    List<Widget> addMenu = [];
    CollaborativeArea? current = CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current ?? ""];
    addMenu.add(getDropdown(widget.type, current, this, context, false));
    return Column( children: [ 
        Container(
          height: 50,
          color: lightColor,
          width: getMainWidth(context),
          padding: const EdgeInsets.only(left: 50),
          child: Stack( alignment: Alignment.centerLeft, children: [
                          Tooltip( message: "open file", child: Padding( padding: const EdgeInsets.only(right: 15), 
                            child: InkWell( mouseCursor: SystemMouseCursors.click,
                              onTap: () {
                                showDialog(
                                    barrierDismissible: false,
                                    context: context, builder: (context) {
                                    return AlertDialog(
                                      titlePadding: EdgeInsets.zero,
                                      insetPadding: EdgeInsets.zero,
                                      backgroundColor: Colors.white,
                                      shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(0)),
                                      title: ShallowCreationDialogWidget(
                                        formKey: key,
                                        canClose: () => CollaborativeAreaLocal.current != null,
                                        context: context,
                                        load: (p0) async {
                                          CollaborativeAreaLocal.current = p0;
                                          HeaderConstants.setTitle("Collaborative Area <${CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current]?.name ?? ""}>");
                                          HeaderConstants.setDescription(CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current]?.description ?? "");
                                          Future.delayed(const Duration(seconds: 1), () => SharedFactory.key.currentState?.setState(() {}));
                                        },
                                        form: [
                                          ShallowTextInputWidget(
                                            change :(p0) => key.currentState?.setState(() {}),
                                            type: CollaborativeAreaType.collaborative_area,
                                            width: getMainWidth(context) <= 540 ? getMainWidth(context) - 140 : 400,
                                            attr: "description",
                                            color: Colors.black,
                                            hintColor: Colors.grey,
                                            filled: midColor,
                                          )
                                        ],
                                        create: PermsService.getPerm(Perms.COLLABORATIVE_AREA_CREATE) ? (p0) async => await SharedService().post(context, p0, {}).then( (e) async {
                                          if (e.data != null) {
                                            CollaborativeAreaLocal.current = e.data!.id;
                                          }
                                          await CollaborativeAreaLocal.init(context, true);
                                          setState(() {});
                                        }) : null,
                                        type: CollaborativeAreaType.collaborative_area,
                                        all: () async => CollaborativeAreaLocal.workspaces.values.map( 
                                          (e) => Shallow(id: e.id ?? "", name: e.name ?? "") ).toList(),
                                      ));
                                  });
                              }, 
                              child: const Icon(Icons.folder_open, color: Colors.white)))),
                              Positioned( right: 0, child: Row( children: addMenu))
                        ])),
        Row( 
        children: [
          Container(
            decoration: BoxDecoration(
              color: Colors.black,
              border: Border(left: BorderSide(color: lightColor))
            ),
            height: getMainHeight(context) - 50,
            width: 50,
            child: Column(
              children: [
                getMenuItem(CollaborativeAreaType.global, Icons.dashboard),
                getMenuItem(CollaborativeAreaType.workspace, Icons.workspaces),
                getMenuItem(CollaborativeAreaType.workflow, Icons.rebase_edit),
                getMenuItem(CollaborativeAreaType.peer, Icons.group),
              ])
          ),
          Container( 
            height: getMainHeight(context)  - 50,
            width:  getMainWidth(context) -50,
            color: widget.type == CollaborativeAreaType.workflow || widget.type == CollaborativeAreaType.peer 
            || widget.type == CollaborativeAreaType.global ? midColor : Colors.white,
            child: SingleChildScrollView( child: w ))
        ]
      ) ]
    );
  }
}

class WorkspaceSharedPageWidget extends StatefulWidget {
  CollaborativeAreaType type = CollaborativeAreaType.global;
  WorkspaceSharedPageWidget({ required this.type }): super(key: null);
  @override WorkspaceSharedPageWidgetState createState() => WorkspaceSharedPageWidgetState();
}
class WorkspaceSharedPageWidgetState extends State<WorkspaceSharedPageWidget> {

  List<Widget> getCardWorkspaceItems(Map<String, List<AbstractItem>> data) {
    List<Widget> items = [];
    for (var w1 in data.keys) {
      for (var w in data[w1]!) {
      List<Widget> badges = [];
      List<Widget> bbadges = [];
      badges.add(Container( margin: const EdgeInsets.only(left: 5), padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
        decoration: BoxDecoration( 
          borderRadius: BorderRadius.circular(4),
          color: getColor(w.topic) 
        ),
        child:Text(w.topic, style: TextStyle( color: Colors.white, fontSize: 11) )));
      bbadges.add(Container(  margin: const EdgeInsets.only(left: 5), 
        decoration: BoxDecoration( color: Colors.grey, borderRadius: BorderRadius.circular(4) ),
        padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5), child: Text(w1, style: TextStyle( color: Colors.white, fontSize: 11) )));
      items.add(ShallowItemFlowDataRowWidget(
        color: Colors.grey.shade200,
        item: w, badges: badges, bottomBadges: bbadges,
        icon:  Icons.shopping_cart,
        contextWidth: 200
      ));
    }}
    return items;
  }

  List<Widget> getCardItems(List<ShallowData> data) {
    List<Widget> items = [];
    List<ShallowData> neoData = [];
    for (var d in data) {
      try { neoData.firstWhere( (e) => e.getID() == d.getID());
      } catch (e) { neoData.add(d); }
    }
    for (var w in neoData) {
      List<Widget> badges = [];
      if (w is Peer && (
          w.getID() != CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current ?? ""]?.rule?.creator
          || w.getID() != CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current ?? ""]?.creatorID)) {
        badges.add(Padding( padding: const EdgeInsets.only(left: 5), child: Icon(Icons.star, color: Colors.orange.shade300 )));
      } else if (widget.type == CollaborativeAreaType.workspace) {
        badges.add(Container( margin: const EdgeInsets.only(left: 5), padding: EdgeInsets.all(5), color: Colors.grey.shade200,
        child: Icon(Icons.star, color: Colors.orange.shade300,)));
      }
      items.add(ShallowItemRowWidget(
        color: Colors.grey.shade200,
        item: w, badges: badges,
        delete: w is Peer ? (PermsService.getPerm(Perms.PEER_UNSHARE) && (
          w.getID() != CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current ?? ""]?.rule?.creator
          && w.getID() != CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current ?? ""]?.creatorID) ? (String? change) async {
          await SharedService().removePeer(context, CollaborativeAreaLocal.current ?? "", change ?? "");
          await CollaborativeAreaLocal.init(context, false);
          setState(() {});
        } : null) : (w is Workflow && PermsService.getPerm(Perms.WORKSPACE_UNSHARE)) ? (String? change) async {
          await SharedService().removeWorkflow(context, CollaborativeAreaLocal.current ?? "", change ?? "");
          await CollaborativeAreaLocal.init(context, false);
          setState(() {});
        } : null,
        icon: w is Workflow ? Icons.work_history_rounded : Icons.person,
        contextWidth: 200
      ));
    }
    return items;
  }

  @override Widget build(BuildContext context) {
    var space = CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current ?? ""];
    if (widget.type == CollaborativeAreaType.global) {
      if (space == null) {
        return Container(
          color: midColor,
          height: getMainHeight(context) - 50,
          width: getMainWidth(context) - 50,
          alignment: Alignment.center,
          padding: const EdgeInsets.all(50)
        );
      }
      final DateFormat formatter = DateFormat('dd-MM-yyyy');
      Peer? creator;
      SharedService service = SharedService();
      try { creator = space.peers.firstWhere( (e) => (space.rule?.creator ?? "") == e.id);
      } catch (e) { /**/ }
      Map<String, List<AbstractItem>> datas = {};
      for (var w in space.workspaces) {
        datas[w.getName()] =<AbstractItem> [
                    ...w.computes,
                    ...w.datas,
                    ...w.processings,
                    ...w.storages,
                    ...w.workflows
                  ];
      }
      return Padding( padding: EdgeInsets.all(30),
          child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ 
            Row( mainAxisAlignment: MainAxisAlignment.center, children: [ 
              Text((CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current]?.name ?? "").toUpperCase(), 
              style: TextStyle(color: Colors.grey, fontSize: 25, fontWeight: FontWeight.bold), textAlign: TextAlign.center, 
              softWrap: true, overflow: TextOverflow.ellipsis,),
            ]),
            Container( 
              width: getMainWidth(context) - 50,
              margin: EdgeInsets.symmetric(vertical: 20),
              color: Colors.white,
              padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 50),
              child: Text(space.description ?? "", 
                  style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w400, color: Colors.grey))
            ),
            Padding( padding: EdgeInsets.only(left: 30), child: Text("COLLABORATIVE AREA ACCESS RULES", textAlign: TextAlign.start,
            style: TextStyle(color: darkColor, fontSize: 20, fontWeight: FontWeight.bold), overflow: TextOverflow.clip)),
            Container( 
              width: getMainWidth(context) - 50,
              margin: EdgeInsets.symmetric(vertical: 20),
              color: Colors.white,
              padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 50),
              child: Column(
                children: [
                  Row(children: [ Text("Share mode : "), Text( space.rule?.shareMode ?? "closed", style: TextStyle( fontWeight: FontWeight.bold ) )],),
                  Row(children: [ Text("Created : "), Text( formatter.format(space.rule?.createdAt ?? DateTime.now()), style: TextStyle( fontWeight: FontWeight.bold )) ],),
                  creator != null ? Row(children: [ Text("Area master : "), Text( creator.getName(), style: TextStyle( fontWeight: FontWeight.bold ) )  ],) 
                  : Container(),
                  Row(children: [ Text("User count : "), Text( "${space.peers.length}", style: TextStyle( fontWeight: FontWeight.bold ))  ],),
                  Row(children: [ Text("Users profile : "), Text( space.rule?.exploitedBy ?? "any", style: TextStyle( fontWeight: FontWeight.bold ) )  ],),
                ],
              )
            ),
            
            Row( children: [
              Padding( padding: EdgeInsets.only(left: 30), child: Text("COLLABORATIVE AREA PEERS", textAlign: TextAlign.start,
            style: TextStyle(color: darkColor, fontSize: 20, fontWeight: FontWeight.bold), overflow: TextOverflow.clip)), 
            PermsService.getPerm(Perms.PEER_SHARE) ? Container( 
              margin: EdgeInsets.only(left: 20), padding: EdgeInsets.only(left: 15),
              decoration: BoxDecoration(
                border: Border(left: BorderSide(color: Colors.grey))
              ), child: getDropdown(CollaborativeAreaType.peer, CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current], this, context, true)
              ) : Container()]),
            Container( 
              width: getMainWidth(context) - 50,
              margin: EdgeInsets.symmetric(vertical: 20),
              color: Colors.white,
              padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 50),
              child: Wrap( alignment: WrapAlignment.center, children: getCardItems(space.peers)),
            ),
            space.rules.isNotEmpty ? Padding( padding: EdgeInsets.only(left: 30), child: Text("RULES", textAlign: TextAlign.start,
            style: TextStyle(color: darkColor, fontSize: 20, fontWeight: FontWeight.bold), overflow: TextOverflow.clip)) : Container(),
            space.rules.isNotEmpty ? Container( 
              width: getMainWidth(context) - 50,
              margin: EdgeInsets.symmetric(vertical: 20),
              color: Colors.white,
              padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 50),
              child: Column( children: space.rules.map( (e) {
                return Row( children: [
                  Padding( padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                    child:Text("-", style: TextStyle(color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold), overflow: TextOverflow.clip)),
                  Text(e ?? "", style: TextStyle(color: Colors.grey, fontSize: 15), overflow: TextOverflow.clip)
                ]);
              }).toList() )
            ) : Container(),
            Row( children: [
              Padding( padding: EdgeInsets.only(left: 30), child: Text("WORKSPACES / RESOURCES", textAlign: TextAlign.start,
            style: TextStyle(color: darkColor, fontSize: 20, fontWeight: FontWeight.bold), overflow: TextOverflow.clip)), 
            PermsService.getPerm(Perms.WORKSPACE_SHARE) ? Container( 
              margin: EdgeInsets.only(left: 20), padding: EdgeInsets.only(left: 15),
              decoration: BoxDecoration(
                border: Border(left: BorderSide(color: Colors.grey))
              ), child: getDropdown(CollaborativeAreaType.workspace, CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current], this, context, true)) : Container() ]),
            Container( 
              width: getMainWidth(context) - 50,
              margin: EdgeInsets.symmetric(vertical: 20),
              color: Colors.white,
              padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 50),
              child: Wrap( alignment: WrapAlignment.center, children: getCardWorkspaceItems(datas))
              ),
            Row( children: [
              Padding( padding: EdgeInsets.only(left: 30), child: Text("WORKFLOWS", textAlign: TextAlign.start,
            style: TextStyle(color: darkColor, fontSize: 20, fontWeight: FontWeight.bold), overflow: TextOverflow.clip)), 
            PermsService.getPerm(Perms.WORKFLOW_SHARE) ? Container( 
              margin: EdgeInsets.only(left: 20), padding: EdgeInsets.only(left: 15),
              decoration: BoxDecoration(
                border: Border(left: BorderSide(color: Colors.grey))
              ), child: getDropdown(CollaborativeAreaType.workflow, CollaborativeAreaLocal.workspaces[CollaborativeAreaLocal.current], this, context, true)) : Container()]),
            Container( 
              width: getMainWidth(context) - 50,
              margin: EdgeInsets.symmetric(vertical: 20),
              color: Colors.white,
              padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 50),
              child: Wrap( alignment: WrapAlignment.center, children: getCardItems(space.workflows))
              ),
          ],)
        );
    }
    
    if (CollaborativeAreaLocal.current == null) { 
      return Container(
        color: midColor,
        height: getMainHeight(context) - 50,
        width: getMainWidth(context) - 50,
        alignment: Alignment.center,
        padding: const EdgeInsets.all(50)
      );
    }
    List<Widget> items = [];
    List<ShallowData> data = [];
    if (widget.type == CollaborativeAreaType.workspace) {
      data = space?.workspaces ?? [];
    } else if (widget.type == CollaborativeAreaType.workflow) {
      data = space?.workflows ?? [];
    } else if (widget.type == CollaborativeAreaType.peer) {
      data = space?.peers ?? [];
    }
    if (widget.type == CollaborativeAreaType.workspace) {
      List<ShallowData> neoData = [];
      for (var d in data) {
        try { neoData.firstWhere( (e) => e.getID() == d.getID());
        } catch (e) { neoData.add(d); }
      }
      for (var w in neoData) {
        if (WorkspaceLocal.workspaces[w.getID()] == null) { continue; }
        items.add(WorkspaceSharedItemPageWidget(name: "Workspace <${WorkspaceLocal.workspaces[w.getID()]!.name}>", id: w.getID())); 
      }
    } else {
      items = getCardItems(data);
    }
    if (items.isEmpty) {
        return Container( 
          color: midColor,
          height: getMainHeight(context) - 50,
          width: getMainWidth(context) - 50,
          alignment: Alignment.center,
          padding: const EdgeInsets.all(50),
          child: Text("NO ITEMS SHARED", style: const TextStyle(fontSize: 25, fontWeight: FontWeight.w600, color: Colors.white)));
     }
     if (widget.type == CollaborativeAreaType.workflow || widget.type == CollaborativeAreaType.peer) {
      return Padding( 
        padding: const EdgeInsets.all(50),
        child: Stack( alignment: Alignment.topLeft, children : items));
     }
    return Column( mainAxisAlignment: MainAxisAlignment.start, children : items);
  }
}

// ignore: must_be_immutable
class WorkspaceSharedItemPageWidget extends StatefulWidget {
  bool open = true;
  String id = "";
  String name = "";
  WorkspaceSharedItemPageWidget({ this.name = "", this.id = "" }): super(key: null);
  @override WorkspaceSharedItemPageWidgetState createState() => WorkspaceSharedItemPageWidgetState();
}
class WorkspaceSharedItemPageWidgetState extends State<WorkspaceSharedItemPageWidget> {
    @override Widget build(BuildContext context) {
      return Column( children: [
        Container( 
          width: getMainWidth(context) - 50,
            height: 50,
            padding: const EdgeInsets.symmetric(horizontal: 20),
            decoration: BoxDecoration(color: midColor, border: Border(bottom: BorderSide(color: Colors.white))),
            child: Stack( 
                alignment: Alignment.centerLeft,
                children: [
                  Row( 
                    children: [
                      const Padding(padding: EdgeInsets.only(right: 20), child: Icon(Icons.shopping_cart_outlined, size: 18, color: Colors.grey)),
                    Text(widget.name, 
                      style: const TextStyle(fontSize: 15, color: Colors.grey, fontWeight: FontWeight.w600)),
                    ]
                  ),
                  Positioned( right: 0, top: 5, child: IconButton( icon: Icon(widget.open ? Icons.arrow_drop_up : Icons.arrow_drop_down, color: Colors.grey),
                    onPressed: () => setState(() {
                      widget.open = !widget.open;
                  })))
              ])
            ),
          widget.open ? CatalogWidget(itemWidth: getMainWidth(context) - 50, 
          items: WorkspaceLocal.byWorkspace(widget.id)) : Container()
        ]);
    }
}

  Widget getDropdown(CollaborativeAreaType type, CollaborativeArea? current, State<dynamic> state, BuildContext context, bool mainPage ) {
    if (type == CollaborativeAreaType.workspace) {
      return Row( mainAxisAlignment: MainAxisAlignment.end,
        children : [ Container( padding: EdgeInsets.only(left:  mainPage ? 0 : 20), decoration: BoxDecoration(
          border:  mainPage ? null : Border(left: BorderSide(color: Colors.white))
        ), child: ShallowDropdownInputWidget( 
          tooltipLoad: "share",
          tooltipRemove: "unshare",
          iconLoad: Icons.share,
          type: type, 
          filled: mainPage ? Colors.white : lightColor,
          hintColor:  mainPage ? Colors.grey : midColor,
          color: mainPage ? Colors.black : Colors.white,
          prefixIcon: Icon(Icons.shopping_cart, color: Colors.white),
          current: WorkspaceLocal.current,
          all: () async => WorkspaceLocal.getWorkspacesShallow(),
          width: getMainWidth(context) / 3,
          canLoad: (String? change) => current != null && !current.workspaces.map( (e) => e.id ).contains(change),
          canRemove: (String? change) => current != null && current.workspaces.map( (e) => e.id ).contains(change), 
          load: PermsService.getPerm(Perms.WORKSPACE_SHARE) ? (String val) async {
            await SharedService().addWorkspace(context, CollaborativeAreaLocal.current ?? "", val);
            await CollaborativeAreaLocal.init(context, false);
            state.setState(() {});
            if (mainPage) {
              SharedFactory.key.currentState?.setState(() {});
            }
          } : null,
          remove: PermsService.getPerm(Perms.WORKSPACE_UNSHARE) ? (String val) async {
            await SharedService().removeWorkspace(context, CollaborativeAreaLocal.current ?? "", val);
            await CollaborativeAreaLocal.init(context, false);
            state.setState(() {});
            if (mainPage) {
              SharedFactory.key.currentState?.setState(() {});
            }
          } : null))
      ]);
    }
    if (type == CollaborativeAreaType.workflow) {
      return Row( mainAxisAlignment: MainAxisAlignment.end,
        children : [ Container( padding: EdgeInsets.only(left:  mainPage ? 0 : 20), decoration: BoxDecoration(
          border:  mainPage ? null : Border(left: BorderSide(color: Colors.white))
        ), child: ShallowDropdownInputWidget( 
          tooltipLoad: "share",
          tooltipRemove: "unshare",
          iconLoad: Icons.share,
          filled: mainPage ? Colors.white : lightColor,
          hintColor:  mainPage ? Colors.grey : midColor,
          color: mainPage ? Colors.black : Colors.white,
          type: type, all: () async {
            List<Shallow> shals = [];
            await WorflowService().all(context).then((value) {
                if (value.data != null) {
                  shals = value.data!.values.map((e) => Shallow(id: e["id"], name: e["name"])).toList();
                }
              });
            return shals;
          },
          width: getMainWidth(context) / 3,
          canLoad: (String? change) => current != null && !current.workflows.map( (e) => e.id ).contains(change),
          canRemove: (String? change) => current != null && current.workflows.map( (e) => e.id ).contains(change),
          load: PermsService.getPerm(Perms.WORKFLOW_SHARE) ? (String change) async {
            await SharedService().addWorkflow(context, CollaborativeAreaLocal.current ?? "", change);
            await CollaborativeAreaLocal.init(context, false);
            state.setState(() {});
            if (mainPage) {
              SharedFactory.key.currentState?.setState(() {});
            }
          } : null,
          remove: PermsService.getPerm(Perms.WORKFLOW_UNSHARE) ? (String change) async {
            await SharedService().removeWorkflow(context, CollaborativeAreaLocal.current ?? "", change);
            await CollaborativeAreaLocal.init(context, false);
            state.setState(() {});
            if (mainPage) {
              SharedFactory.key.currentState?.setState(() {});
            }
          } : null))
      ]);
    }
    if (type == CollaborativeAreaType.peer) {
      return Row( mainAxisAlignment: MainAxisAlignment.end,
        children : [
        Container( padding: EdgeInsets.only(left: mainPage ? 0 : 20), decoration: BoxDecoration(
          border:  mainPage ? null : Border(left: BorderSide(color : Colors.white))
        ), child: ShallowDropdownInputWidget( 
          tooltipLoad: "add",
          iconLoad: Icons.add,
          filled: mainPage ? Colors.white : lightColor,
          hintColor:  mainPage ? Colors.grey : midColor,
          color: mainPage ? Colors.black : Colors.white,
          type: type, all: () async {
            List<Shallow> shals = [];
            await PeerService().all(context).then((value) {
                if (value.data != null) {
                  shals = value.data!.values.where( (e) {
                      print("e: $e ${e["id"]} ${current?.creatorID}");
                      return e["id"] != current?.creatorID;
                    }
                  ).map((e) => Shallow(id: e["id"], name: e["name"])).toList();
                }
              });
            return shals;
          },
          width: getMainWidth(context) / 3,
          canLoad: (String? change) => current != null && !current.peers.map( (e) => e.id ).contains(change),
          canRemove: (String? change) => current != null && current.peers.map( (e) => e.id ).contains(change), 
          load: PermsService.getPerm(Perms.PEER_SHARE) ? (String change) async {
            await SharedService().addPeer(context, CollaborativeAreaLocal.current ?? "", change);
            await CollaborativeAreaLocal.init(context, false);
            state.setState(() {});
            if (mainPage) {
              SharedFactory.key.currentState?.setState(() {});
            }
          } : null,
          remove: PermsService.getPerm(Perms.PEER_UNSHARE) ?  (String change) async {
            await SharedService().removePeer(context, CollaborativeAreaLocal.current ?? "", change);
            await CollaborativeAreaLocal.init(context, false);
            state.setState(() {});
            if (mainPage) {
              SharedFactory.key.currentState?.setState(() {});
            }
          } : null))
      ]);
    }
    return Container();
  }