{ config, lib, pkgs, ... }:

with lib;

let
  cfg = config.settings.applications.zellij;
  sesh = pkgs.writeScriptBin "sesh" ''
    #! /usr/bin/env sh
  
    # Taken from https://github.com/zellij-org/zellij/issues/884#issuecomment-1851136980
    # select a directory using zoxide
    ZOXIDE_RESULT=$(${pkgs.zoxide}/bin/zoxide query --interactive)

    # checks whether a directory has been selected
    if [[ -z "$ZOXIDE_RESULT" ]]; then
    	# if there was no directory, select returns without executing
    	exit 0
    fi
    # extracts the directory name from the absolute path
    SESSION_TITLE=$(echo "$ZOXIDE_RESULT" | sed 's#.*/##')

    # get the list of sessions
    SESSION_LIST=$(zellij list-sessions -n | awk '{print $1}')

    # checks if SESSION_TITLE is in the session list
    if echo "$SESSION_LIST" | grep -q "^$SESSION_TITLE$"; then
    	# if so, attach to existing session
    	zellij attach "$SESSION_TITLE"
    else
    	# if not, create a new session
    	echo "Creating new session $SESSION_TITLE and CD $ZOXIDE_RESULT"
    	cd $ZOXIDE_RESULT
    	zellij attach -c "$SESSION_TITLE"
    fi
  '';
in {
  options = {
    settings.applications.zellij.enable = lib.mkOption {
      type = lib.types.bool;
      description = ''
        Enable zellij tool
      '';
    };
  };

  config = mkIf cfg.enable {
    programs.zellij = {
      enable = true;
    };

    programs.zoxide = {
      enable = true;
      enableZshIntegration = true;
    };

    home.packages = [
      sesh
    ];

    home.file.zellij = {
      target = ".config/zellij/config.kdl";
      text = ''
        pane_frames true
        keybinds {
          normal {
            bind "Ctrl e" { ToggleFloatingPanes; SwitchToMode "normal"; }
            bind "Ctrl d" { Detach; }
            bind "Alt 1" { GoToTab 1; }
            bind "Alt 2" { GoToTab 2; }
            bind "Alt 3" { GoToTab 3; }
            bind "Alt 4" { GoToTab 4; }
            bind "Alt 5" { GoToTab 5; }
          }
        }
      '';
    };

    home.file.zellij-layout-default = {
      target = ".config/zellij/layouts/default.kdl";
      text = ''
        layout {
          pane borderless=true {}
          floating_panes {
            pane {
              width "80%"
              height "80%"
              x "10%"
              y "10%"
            }
          }
          pane size=1 borderless=true {
            plugin location="zellij:tab-bar"
          }
        }
      '';
    };
  };
}

