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;
      }
    }
  `;
  /** the connected callback method one of the lifecycle methods that runs once the element is added
   * to the dom. there is no disconnectedCallback because the header is never removed from the DOM.
   * i centralize state in this component because it's where the sign in and out button resides.
   *
   *
  */
  connectedCallback(): void {
    super.connectedCallback();

    // Check for stored pubkey and fetch metadata if available
    const storedPubkey = localStorage.getItem('pubkey');
    if (storedPubkey) {
      this.isSignedIn = true;
      this.fetchProfileMetadata(storedPubkey);
    } else {
      this.displayGuestView();
    }
  }

  displayGuestView() {
    // this method displays a guest view when the user is signed out
    this.nostrAddy = '';
    this.bio = 'Welcome, guest! Please sign in with a browser extension to view your profile.';
    this.profilePic = '/public/assets/img/default_pfp.png'; // a placeholder profile picture
    this.isSignedIn = false;

    this.dispatchUserStateChanged();
  }

  async fetchProfileMetadata(pubkey: string) {
    try {
      const relay = await Relay.connect('wss://notes.miguelalmodo.com');
      const sub = relay.subscribe(
        [{ kinds: [0], authors: [pubkey] }],
        {
          onevent: (event) => {
            const profileData = JSON.parse(event.content);
            this.profilePic = profileData.picture || '/assets/img/default_pfp.png';
            this.nostrAddy = profileData.nip05 || 'no addy available';
            this.bio = profileData.about || 'bio not available';

            this.dispatchUserStateChanged();
          },
          oneose: () => sub.close(),
        }
      );
    } catch (error) {
      console.error('Failed to fetch profile metadata:', error);
      this.displayGuestView();
    }
  }

  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);
        this.isSignedIn = false;
      }
    } else {
      alert('Nostr extension not detected. Please install a Nostr extension.');
    }
  }

  /* this sign out method clears the public key from local storage and sets the profile view
  back to guest view */
  signOut() {
    localStorage.removeItem('pubkey');
    this.displayGuestView();
  }

  dispatchUserStateChanged() {
    this.dispatchEvent(
      new CustomEvent('user-state-changed', {
        detail: {
          isSignedIn: this.isSignedIn,
          nostrAddy: this.nostrAddy,
          bio: this.bio,
          profilePic: this.profilePic,
        },
        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'}

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