{ pkgs, ... }:

{
  #age.secrets.fastmail.file = "/etc/nixos/secrets/fastmail.age";
  #age.secrets.fastmail.owner = "anish";
  home.packages = with pkgs; [
    neomutt
    imapfilter
  ];
  services.mbsync = {
    enable = true;
    frequency = "*:0/30";
    #postExec = "${pkgs.notmuch}/bin/notmuch new";
  };
  services.imapnotify.enable = true;
  programs.mbsync.enable = true;
  programs.msmtp.enable = true;
  programs.notmuch.enable = true;
  home.file.".mailcap".text = ''
    text/html; firefox %s
    application/pdf; zathura %s
    image/png; feh %s
    image/jpeg; feh %s
  '';
  programs.neomutt = {
    enable = true;
    extraConfig = ''
      # Shamelessly Stolen from https://gideonwolfe.com/posts/workflow/neomutt/intro/
      # set editor to neovim
      set editor = "nvim +':set textwidth=0'"

      #set virtual_spoolfile=yes
      set folder="~/Mail/anish"
      set mbox_type = Maildir
      mailboxes `find ~/Mail/anish/* -maxdepth 0 -type d | grep -v "Trash\|Spam\|tmp\|new\|cur" | sed 's|/home/anish/Mail/anish|=\"|g' | sed 's|$|\"|g' | tr '\n' ' '`
            
      ## Folder with emails
      #set folder = "~/Mail/anish"
      # Type of mailbox
      # Directory to poll for new mail
      #set spoolfile = +Inbox
      # Directory to save sent messages into
      #set record = +Sent
      # Sets the drafts folder
      set postponed = ~/Mail/anish/Drafts
      # File that headers will be cached
      # set header_cache = ~/.cache/mutt

      set my_name = "Anish"
      set imap_check_subscribed

      # Set preffered view modes
      auto_view text/html text/calendar application/ics # view html automatically
      alternative_order text/plain text/enriched text/html text/*

      # main options
      set use_from
      set from="anish@lakhwara.com"
      set sendmail="msmtpq"      # send from default account using msmtp
      set sendmail_wait=-1
      set edit_headers                     # show headers when composing
      set fast_reply                       # skip to compose when replying
      #set askcc                            # ask for CC:
      set fcc_attach                       # save attachments with the body
      set forward_format = "Fwd: %s"       # format of subject when forwarding
      set forward_decode                   # decode when forwarding
      set attribution = "On %d, %n wrote:" # format of quoting header
      set reply_to                         # reply to Reply to: field
      set reverse_name                     # reply as whomever it was to
      set include                          # include message in replies
      set forward_quote                    # include message in forwards
      set text_flowed
      set ssl_force_tls
      set fast_reply
      #unset sig_dashes                     # no dashes before sig
      #unset mime_forward                   # forward attachments as part of body
      #unset help                           # No help bar at the top of index
      set status_on_top                    # Status bar on top of index
      #set tmpdir = ~/Programs/neomutt/temp # where to keep temp files

      unset confirmappend      # don't ask, just do!
      set quit                 # don't ask, just do!!
      unset mark_old           # read/new is good enough for me
      set pipe_decode          # strip headers and eval mimes when piping
      set thorough_search      # strip headers and eval mimes before searching
      set timeout = 0

      # status bar, date format, finding stuff etc.
      set status_chars = " *%A"
      set status_format = "[ Folder: %f ] [%r%m messages%?n? (%n new)?%?d? (%d to delete)?%?t? (%t tagged)? ]%>─%?p?( %p postponed )?"
      set date_format = "%d.%m.%Y %H:%M"
      set reply_regexp = "^(([Rr][Ee]?(\[[0-9]+\])?: *)?(\[[^]]+\] *)?)*"
      set quote_regexp = "^( {0,4}[>|:#%]| {0,4}[a-z0-9]+[>|]+)+"
      set send_charset = "utf-8:iso-8859-1:us-ascii"
      set charset = "utf-8"
      set arrow_cursor = "no" # Change `color indicator` depending 

      # notmuch shortcuts
      # Points to the notmuch directory
      set nm_default_url = "notmuch://$HOME/Mail/anish"
      # Makes notmuch return threads rather than messages
      set nm_query_type = "threads"
      # Binding for notmuch search
      macro index,pager S "<vfolder-from-query>" "Search mailbox"

      # Pager View Options
      set pager_index_lines = 10  # Shows 10 lines of index when pager is active
      set pager_context = 3
      set pager_stop
      set menu_scroll
      set tilde
      set mail_check_stats
      unset markers

      #set header_cache = "~/.cache/mutt"
      #set message_cachedir = "~/.cache/mutt"

      set query_command = "khard email --parsable --search-in-source-files '%s'"

      ### Mappings Settings
                  
      # General rebindings
      bind attach <return> view-mailcap
      bind attach l view-mailcap
      bind editor <space> noop
      bind pager c imap-fetch-mail
      bind index G last-entry
      bind index g noop
      bind index gg first-entry
      bind pager,attach h exit
      bind pager j next-line
      bind pager k previous-line
      bind pager l view-attachments
      bind index D delete-message
      bind index U undelete-message
      bind index L limit
      bind index h noop
      bind index l display-message
      bind browser h goto-parent
      bind browser l select-entry
      bind pager,browser gg top-page
      bind pager,browser G bottom-page
      bind index,pager,browser d half-down
      bind index,pager,browser u half-up
      # bind index,pager R group-reply
      bind index \031 previous-undeleted  # Mouse wheel
      bind index \005 next-undeleted    # Mouse wheel
      bind pager \031 previous-line    # Mouse wheel
      bind pager \005 next-line    # Mouse wheel
      bind editor <Tab> complete-query


      # sidebar mappings
      set sidebar_short_path=yes
      set sidebar_delim_chars='/'
      bind index,pager \Ck sidebar-prev
      bind index,pager \Cj sidebar-next
      bind index,pager \Co sidebar-open
      bind index,pager \Cp sidebar-prev-new
      bind index,pager \Cn sidebar-next-new
      bind index,pager B sidebar-toggle-visible

      # global index and pager shortcuts
      bind index,pager @ compose-to-sender
      bind index,pager D purge-message
      bind index <tab> sync-mailbox
      bind index <space> collapse-thread

      # Email completion bindings
      bind editor <Tab> complete-query
      bind editor ^T complete

      # Press A to archive
      macro index,pager A  "<clear-flag>N<save-message>=/Archive"  "mark message as Archived"
      # Press C to add contact to Khard address book
      macro index,pager C \
      "<pipe-message>khard add-email<return>" \
      "add the sender email address to khard"

      ### Color Settings
      # Header colors:
      color header blue default ".*"
      color header brightmagenta default "^(From)"
      color header brightcyan default "^(Subject)"
      color header brightwhite default "^(CC|BCC)"

      mono bold bold
      mono underline underline
      mono indicator reverse
      mono error bold
      color normal default default
      color indicator brightyellow default # currently selected message. default makes bar clear, disabled arrow to save space.
      color sidebar_highlight red default
      color sidebar_divider brightblack black
      color sidebar_flagged red black
      color sidebar_new green black
      color normal brightyellow default
      color error red default
      color tilde black default
      color message cyan default
      color markers red white
      color attachment white default
      color search brightmagenta default
      color status brightyellow black
      color hdrdefault brightgreen default
      color quoted green default
      color quoted1 blue default
      color quoted2 cyan default
      color quoted3 yellow default
      color quoted4 red default
      color quoted5 brightred default
      color signature brightgreen default
      color bold black default
      color underline black default
      color normal default default

      color body brightred default "[\-\.+_a-zA-Z0-9]+@[\-\.a-zA-Z0-9]+" # Email addresses
      color body brightblue default "(https?|ftp)://[\-\.,/%~_:?&=\#a-zA-Z0-9]+" # URL
      color body green default "\`[^\`]*\`" # Green text between ` and `
      color body brightblue default "^# \.*" # Headings as bold blue
      color body brightcyan default "^## \.*" # Subheadings as bold cyan
      color body brightgreen default "^### \.*" # Subsubheadings as bold green
      color body yellow default "^(\t| )*(-|\\*) \.*" # List items as yellow
      color body brightcyan default "[;:][-o][)/(|]" # emoticons
      color body brightcyan default "[;:][)(|]" # emoticons
      color body brightcyan default "[ ][*][^*]*[*][ ]?" # more emoticon?
      color body brightcyan default "[ ]?[*][^*]*[*][ ]" # more emoticon?
      color body red default "(BAD signature)"
      color body cyan default "(Good signature)"
      color body brightblack default "^gpg: Good signature .*"
      color body brightyellow default "^gpg: "
      color body brightyellow red "^gpg: BAD signature from.*"
      mono body bold "^gpg: Good signature"
      mono body bold "^gpg: BAD signature from.*"
      color body red default "([a-z][a-z0-9+-]*://(((([a-z0-9_.!~*'();:&=+$,-]|%[0-9a-f][0-9a-f])*@)?((([a-z0-9]([a-z0-9-]*[a-z0-9])?)\\.)*([a-z]([a-z0-9-]*[a-z0-9])?)\\.?|[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+)(:[0-9]+)?)|([a-z0-9_.!~*'()$,;:@&=+-]|%[0-9a-f][0-9a-f])+)(/([a-z0-9_.!~*'():@&=+$,-]|%[0-9a-f][0-9a-f])*(;([a-z0-9_.!~*'():@&=+$,-]|%[0-9a-f][0-9a-f])*)*(/([a-z0-9_.!~*'():@&=+$,-]|%[0-9a-f][0-9a-f])*(;([a-z0-9_.!~*'():@&=+$,-]|%[0-9a-f][0-9a-f])*)*)*)?(\\?([a-z0-9_.!~*'();/?:@&=+$,-]|%[0-9a-f][0-9a-f])*)?(#([a-z0-9_.!~*'();/?:@&=+$,-]|%[0-9a-f][0-9a-f])*)?|(www|ftp)\\.(([a-z0-9]([a-z0-9-]*[a-z0-9])?)\\.)*([a-z]([a-z0-9-]*[a-z0-9])?)\\.?(:[0-9]+)?(/([-a-z0-9_.!~*'():@&=+$,]|%[0-9a-f][0-9a-f])*(;([-a-z0-9_.!~*'():@&=+$,]|%[0-9a-f][0-9a-f])*)*(/([-a-z0-9_.!~*'():@&=+$,]|%[0-9a-f][0-9a-f])*(;([-a-z0-9_.!~*'():@&=+$,]|%[0-9a-f][0-9a-f])*)*)*)?(\\?([-a-z0-9_.!~*'();/?:@&=+$,]|%[0-9a-f][0-9a-f])*)?(#([-a-z0-9_.!~*'();/?:@&=+$,]|%[0-9a-f][0-9a-f])*)?)[^].,:;!)? \t\r\n<>\"]"

      # Default index colors:
      color index yellow default '.*'
      color index_author red default '.*'
      color index_number blue default
      color index_subject cyan default '.*'

      # For new mail:
      color index brightyellow black "~N"
      color index_author brightred black "~N"
      color index_subject brightcyan black "~N"

      color progress black cyan

    '';
  };

  accounts.email = {
    accounts.anish = {
      primary = true;
      address = "anish@lakhwara.com";
      #alias = [ "*@lakhwara.com" ];
      #gpg = {
      #  key = "";
      #  signByDefault = true;
      #};
      imap.host = "imap.fastmail.com";
      mbsync = {
        enable = true;
        create = "both";
        expunge = "both";
        remove = "both";
        extraConfig.local.subFolders = "Verbatim";
      };
      imapnotify = {
        enable = true;
        boxes = [ "Inbox" ];
        onNotify = "${pkgs.isync}/bin/mbsync anish && ${pkgs.notmuch}/bin/notmuch index";
        onNotifyPost = {
          mail = "${pkgs.libnotify}/bin/notify-send -a mail 'email: new in %s'";
          #update = "${pkgs.libnotify}/bin/notify-send -a mail 'email: update %s'";
          #expunge = "${pkgs.libnotify}/bin/notify-send -a mail 'email: expunge %s'";
        };
      };
      msmtp.enable = true;
      msmtp.extraConfig = {
        "port" = "465";
      };
      notmuch.enable = true;
      realName = "Anish Lakhwara";
      signature = {
        text = ''
          Thanks,
          Anish
        '';
        showSignature = "append";
      };
      passwordCommand = "${pkgs.coreutils}/bin/cat /run/agenix/fastmail";
      smtp = {
        host = "smtp.fastmail.com";
      };
      userName = "anish@lakhwara.com";
      neomutt = {
        enable = true;
      };
    };
  };
}
