import type { ArxInputChangeEvent } from '@/components/General/Input';
import { getSigner, ndk } from '@/ndk';
import { NDKEvent } from '@nostr-dev-kit/ndk';
import { LitElement, css, html } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';

import '@components/General/Textarea';

@customElement('arx-arbor-post-creator')
export class ArborPostCreator extends LitElement {
  @property({ type: String })
  threadId = '';

  @state()
  private postContent = '';

  @state()
  private thread: NDKEvent | null = null;

  @state()
  private isCreating = false;

  @state()
  private error: string | null = null;

  static override styles = css`
    :host {
      display: block;
    }

    .container {
      display: flex;
      flex-direction: column;
      gap: 1rem;
    }

    .thread-id {
      color: #666;
      font-family: monospace;
    }

    .error {
      color: #dc2626;
      font-size: 0.875rem;
    }

    .actions {
      display: flex;
      gap: 1rem;
      justify-content: flex-end;
    }

    .disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  `;

  override connectedCallback() {
    super.connectedCallback();
    this.loadThread();
  }

  private async loadThread() {
    try {
      await getSigner();
      this.thread = await ndk.fetchEvent(this.threadId);
      if (!this.thread) {
        throw new Error('Could not load thread');
      }
    } catch (error) {
      console.error('Failed to load thread:', error);
    }
  }

  private async doCreatePost() {
    if (this.isCreating) return;
    if (!this.thread) return;

    if (this.postContent.length < 10) {
      this.error = 'Post content must be at least 10 characters long';
      return;
    }

    this.error = null;
    this.isCreating = true;

    const event = new NDKEvent(ndk);
    event.kind = 893;
    event.tags = [
      ['A', this.thread.tags.find((tag) => tag[0] === 'd')?.[1] || ''],
      ['E', this.threadId],
      ['p', this.thread.pubkey],
    ];
    event.content = this.postContent;

    try {
      await event.sign();
      await event.publish();
      // Reset form
      this.postContent = '';
    } catch (error) {
      console.error('Failed to create post:', error);
      this.error = 'Failed to create post. Please try again.';
    } finally {
      this.isCreating = false;
    }
  }

  private handleContentInput(e: ArxInputChangeEvent) {
    this.postContent = e.detail.value;
    if (this.error && this.postContent.length >= 10) {
      this.error = null;
    }
  }

  override render() {
    return html`
      <div class="container">
        <div class="thread-id">Thread ID: ${this.threadId}</div>

        <arx-textarea
          placeholder="Post. You can use Markdown here."
          .value=${this.postContent}
          @change=${this.handleContentInput}
          ?disabled=${this.isCreating}
        ></arx-textarea>

        ${this.error ? html` <div class="error">${this.error}</div> ` : null}

        <div class="actions">
          <arx-button
            label="Cancel"
            @click=${() => this.dispatchEvent(new CustomEvent('cancel'))}
            ?disabled=${this.isCreating}
          ></arx-button>

          <arx-button
            label=${this.isCreating ? 'Creating...' : 'Create'}
            @click=${this.doCreatePost}
            ?disabled=${this.isCreating}
          >
            ${this.isCreating ? 'Creating...' : 'Create'}
          </arx-button>
        </div>
      </div>
    `;
  }
}
