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

import '@components/General/Button';
import '@components/General/Input';
import '@components/General/Textarea';

@customElement('arx-arbor-thread-creator')
export class ArborThreadCreator extends LitElement {
  @property({ type: String })
  categoryId = '';

  @state()
  private newThread = '';

  @state()
  private threadContent = '';

  @state()
  private isCreating = false;

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

    .error {
      color: red;
      margin-bottom: 1rem;
    }

    .category-id {
      color: #666;
      margin-bottom: 1rem;
      font-family: monospace;
    }
  `;

  private async doCreateThread() {
    if (this.isCreating) return;

    if (this.newThread.length < 3) {
      alert('Thread title must be at least 3 characters long');
      return;
    }

    if (this.threadContent.length < 10) {
      alert('Thread content must be at least 10 characters long');
      return;
    }

    this.isCreating = true;

    try {
      await getSigner();
      const event = new NDKEvent(ndk);
      event.kind = 892;
      event.tags = [
        ['name', this.newThread],
        ['d', `60891:${this.categoryId}`],
      ];
      event.content = this.threadContent;
      await event.sign();
      await event.publish();
      location.hash = `/arbor/${event.id}`;
    } catch (error) {
      console.error('Failed to create thread:', error);
      alert('Failed to create thread');
    } finally {
      this.isCreating = false;
    }
  }

  private handleThreadInput(e: ArxInputChangeEvent) {
    this.newThread = e.detail.value;
  }

  private handleContentInput(e: ArxInputChangeEvent) {
    this.threadContent = e.detail.value;
  }

  override render() {
    return html`
      <div class="category-id">Category ID: ${this.categoryId}</div>

      <arx-input
        type="text"
        placeholder="New Thread"
        .value=${this.newThread}
        @change=${this.handleThreadInput}
        ?disabled=${this.isCreating}
      ></arx-input>

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

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

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