import { LitElement, css, html } from 'lit';
import { property, customElement } from 'lit/decorators.js';
import { resolveRouterPath } from '../router';
import { Relay } from 'nostr-tools';
import { WindowNostr } from 'nostr-tools/nip07';

import '@shoelace-style/shoelace/dist/components/button/button.js';
@customElement('app-header')
export class AppHeader extends LitElement {
  @property({ type: String }) title = 'fostr';

  @property({ type: Boolean}) enableBack: boolean = false;

  @property({ type: String }) nostrAddy = '';
  @property({ type: String }) bio = '';
  @property({ type: String }) profilePic = '';
  @property({ type: Boolean }) isSignedIn = false;
  @property({ type: String }) publicKey = '';

  static styles = css`
    header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: var(--app-color-primary);
      color: white;
      padding: 12px;
      padding-top: 4px;

      position: fixed;
      left: env(titlebar-area-x, 0);
      top: env(titlebar-area-y, 0);
      height: env(titlebar-area-height, 30px);
      width: env(titlebar-area-width, 100%);
      -webkit-app-region: drag;
    }

    header h1 {
      margin-top: 0;
      margin-bottom: 0;
      font-size: 12px;
      font-weight: bold;
    }

    nav a {
      margin-left: 10px;
    }

    #back-button-block {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 8px;
    }

    @media(prefers-color-scheme: light) {
      header {
        color: black;
      }

      nav a {
        color: initial;
      }
    }
  `;

  connectedCallback(): void {
    super.connectedCallback();

    //is there a stored pubkey in localStorage already?
    const storedPubkey = localStorage.getItem('pubkey');
    if (storedPubkey) {
      this.isSignedIn = true;
      this.fetchProfileMetadata(storedPubkey);
    } else {
    // Show guest view by default
    this.displayGuestView();
  }}

  displayGuestView() {
    // Set initial values for guest view
    this.nostrAddy = '';
    this.bio = 'Welcome, guest! Please sign in with a browser extension to view your profile.';
    this.profilePic = ''; // Could be a placeholder image for guests
    this.isSignedIn = false;
  }

  async fetchProfileMetadata(pubkey: string) {
    const relay = await Relay.connect('wss://notes.miguelalmodo.com');
    console.log(`connected to ${relay.url}`);

    // subscribe to my profile metadata from the relay
    const sub = relay.subscribe([
      {
        kinds: [0], // profile metadata
        authors: [pubkey], //will insert the pubkey of the user who signed in
      }
    ], {
      onevent: (event) => {
        const profileData = JSON.parse(event.content);
        this.profilePic = profileData.picture || '';
        this.nostrAddy = profileData.nip05 || '';
        this.bio = profileData.about || '';

        this.dispatchEvent(new CustomEvent('profile-updated' , {
          detail: { nostrAddy: this.nostrAddy, bio: this.bio, profilePic: this.profilePic },
          bubbles: true,
          composed: true
        }));
      },
      oneose: () => {
        sub.close();
      }
    });
  }

  async signInWithNostr() {
    if (window.nostr) {
      try {
        const userPubkey = await window.nostr.getPublicKey();
        this.isSignedIn = true;

        //save pubkey in localStorage to keep sign-in state
        localStorage.setItem('pubkey', userPubkey)

        await this.fetchProfileMetadata(userPubkey);
      } catch (error) {
        console.error('Failed to sign in:', error);
      }
    } else {
      alert('Nostr extension not detected. Please install a Nostr extension.');
    }
  }

  signOut() {
    // clear pubkey from localStorage and reset to guest view
    localStorage.removeItem('pubKey');
    this.displayGuestView();
        console.log('signed out')

    this.dispatchEvent( new CustomEvent('user-signed-out', {
      bubbles: true,
      composed: true
    }));
      }

  render() {
    return html`
      <header>

        <div id="back-button-block">
          ${this.enableBack ? html`<sl-button size="small" href="${resolveRouterPath()}">
            Back
          </sl-button>` : null}

          <h1>${this.title}</h1>
        </div>

        <sl-button variant="primary" @click="${this.isSignedIn ? this.signOut : this.signInWithNostr}">
        ${this.isSignedIn ? 'Sign out' : 'Sign in with Nostr'}

          </sl-button>
      </header>
    `;
  }
}
