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/card/card.js';
import '@shoelace-style/shoelace/dist/components/button/button.js';

import { styles } from '../styles/shared-styles';


declare global {
  interface Window {
    nostr?: WindowNostr;
  }
}

@customElement('app-home')
export class AppHome extends LitElement {

  // For more information on using properties and state in lit
  // check out this link https://lit.dev/docs/components/properties/
  @property() message = 'Welcome to my nostr demo!';
  @property({ type: String }) nostrAddy = '';
  @property({ type: String }) bio = '';
  @property({ type: String }) profilePic = '';
  @property({ type: Boolean }) isSignedIn = false;
  @property({ type: String }) publicKey = '';


  static styles = [
    styles,
    css`



    @media (horizontal-viewport-segments: 2) {
      #welcomeBar {
        flex-direction: row;
        align-items: flex-start;
        justify-content: space-between;
      }

      #welcomeCard {
        margin-right: 64px;
      }
    }

    /*
========================================
Profile Picture Container
========================================
*/
.profile-picture-container {
  display: grid;
  grid-template-columns: 300px 150px;
  grid-template-rows: 250px;
  grid-column-gap: 15px;
  margin-bottom: 12px;

}

.profile-picture-container p {
  margin: 0;
}

.profile-pic {
  grid-area: 1/1;
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 50%;
}

.personal-msg {
  grid-area: 1/2;
  margin-top: 300px;
}



.pics-videos {
  grid-area: 1/1;
  justify-self: center;
  align-self: end;
}

  `];

  async firstUpdated() {
    // this method is a lifecycle event in lit
    // for more info check out the lit docs https://lit.dev/docs/components/lifecycle/
    console.log('Welcome to my home page');
  }


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

    this.addEventListener('user-state-changed', (event: Event) => {
    const detail = (event as CustomEvent).detail;
    this.nostrAddy = detail.nostrAddy;
    this.bio = detail.bio;
    this.profilePic = detail.profilePic;
    this.isSignedIn = detail.isSignedIn;
  });
  }



  disconnectedCallback(): void {
    super.disconnectedCallback();
    window.removeEventListener('profile-updated', this.updateProfileFromEvent.bind(this));
    window.removeEventListener('user-signed-out', this.handlesSignOut.bind(this));
  }

  updateProfileFromEvent(event: Event) {
    console.log('Profile updated event received:', (event as CustomEvent).detail);

    const detail = (event as CustomEvent).detail;
    this.nostrAddy = detail.nostrAddy;
    this.bio = detail.bio;
    this.profilePic = detail.profilePic;
    this.isSignedIn = true;
    this.requestUpdate();
  }

  handlesSignOut() {
    this.profilePic = '';
    this.bio = '';
    this.nostrAddy = 'Guest';
    this.isSignedIn = false;
    this.requestUpdate();
  }

  async fetchAndDisplayProfile(pubkey: string) {
    this.nostrAddy = pubkey;
    this.bio = 'Loading profile info...';
    this.profilePic = '/assets/img/loading_pfp.png';

    try {
      // Fetch profile metadata from a relay
      const relay = await Relay.connect('wss://notes.miguelalmodo.com'); // Example URL
      const sub = relay.subscribe([{ kinds: [0], authors: [pubkey] }], {
        onevent: (event) => {
          const profileData = JSON.parse(event.content);
          this.nostrAddy = profileData.nip05 || 'No address available';
          this.bio = profileData.about || 'No bio available';
          this.profilePic = profileData.picture || '/assets/img/default_pfp.png';
          this.requestUpdate();
        },
        oneose: () => sub.close(),
      });
    } catch (error) {
      console.error('Error fetching profile:', error);
      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 = '/assets/img/default_pfp.png'; // Could be a placeholder image for guests
    this.isSignedIn = false;
  }


  share() {
    if ((navigator as any).share) {
      (navigator as any).share({
        title: 'PWABuilder pwa-starter',
        text: 'Check out the PWABuilder pwa-starter!',
        url: 'https://github.com/pwa-builder/pwa-starter',
      });
    }
  }




  render() {
    return html`
      <app-header></app-header>

      <main>
        <div id="welcomeBar">
          <sl-card id="welcomeCard">
            <div slot="header">
              <h2>Welcome to  ${this.nostrAddy || 'Guest'}'s Profile</h2>
            </div>
            <p>
              You can use the Nostr protocol to transform your personal website into
              a micro blog client. You can compose a note and post it to your social
              network.

            </p>


            <div class="profile-picture-container">
<img class="profile-pic" src="${this.profilePic || '/assets/img/default_pfp.png'}" alt="Profile Picture" width="200px" height="200px">

              <p class="personal-msg"><b>${this.bio || 'Welcome, guest! Please sign in to view your profile.'}</b></p>

            </div>

            ${'share' in navigator
              ? html`<sl-button slot="footer" variant="default" @click="${this.share}">
                        <sl-icon slot="prefix" name="share"></sl-icon>
                        Share this Starter!
                      </sl-button>`
              : null}
          </sl-card>

          <sl-button href="${resolveRouterPath('about')}" variant="primary">Navigate to About</sl-button>
          <sl-button href="${resolveRouterPath('note-wall')}" variant="primary">Navigate to Note Wall</sl-button>
         <sl-button href="${resolveRouterPath('write')}" variant="primary">Navigate to Note Compose</sl-button>

         </div>
      </main>
    `;
  }




}
