import {Component, inject, signal} from '@angular/core';
import {DmStorage, ServiceManager, TextChannelStorage} from '../../../../service-manager';
import {ActivatedRoute} from '@angular/router';
import {IndexedDB} from '../../../../storage/indexed-db';
import {TUI_BREAKPOINT, TuiButton, TuiIcon} from '@taiga-ui/core';
import {FileDataWithPreview, MessageBox} from '../../../elements/message-box/message-box';
import {Attachment} from '@chatenium/chatenium-sdk/domain/common.schema';
import {FileUploadProgressListener} from '@chatenium/chatenium-sdk/domain/fileUploadService.schema';
import {MessageBoxViewModel} from '../../../elements/message-box/message-box-viewmodel';
import {TextChannelServiceService} from '@chatenium/chatenium-sdk/services/textChannelService';
import {Message} from '@chatenium/chatenium-sdk/domain/textChannelService.schema';
import {Messages} from '../../../elements/messages/messages';
import {Navbar} from '../../../elements/navbar/navbar';
import {Oimg} from '../../../elements/oimg/oimg';

@Component({
  selector: 'app-text',
  imports: [
    MessageBox,
    Messages,
    Navbar,
    Oimg,
    TuiButton,
    TuiIcon
  ],
  templateUrl: './text.html',
  styleUrl: './text.scss',
})
export class Text {
  serviceManager = inject(ServiceManager)
  route = inject(ActivatedRoute)
  indexedDb = inject(IndexedDB)
  breakpoint = inject(TUI_BREAKPOINT)

  networkId = ""
  channelId = ""
  categoryId = ""

  get store(): TextChannelStorage | null {
    if (!this.serviceManager.networkServices()[this.networkId]) {
      return null
    }
    return this.serviceManager.networkServices()[this.networkId].textChannels()[this.channelId]
  }

  async sendMessage(message: string, files: FileDataWithPreview[] | null) {
    if (!this.store) return
    if (!files && message.trim() == "") return

    const session = this.serviceManager.currentSession();
    if (session != null) {
      const editedMessage = this.store.messageBox.editingMessage()
      if (editedMessage) {
        const storedMsg = this.store.messages().find(m => m.msgid == editedMessage.messageId)
        const originalMessage: Message = JSON.parse(JSON.stringify(storedMsg))
        if (storedMsg) {
          storedMsg.message = message
        }

        try {
          await this.store.service.editMessage(editedMessage.messageId, message)
        } catch (e) {
          if (storedMsg) {
            storedMsg.message = originalMessage.message
          }
        }

        this.store.messageBox.editingMessage.set(null)
        this.store.messageBox.message.set("")
        return
      }

      let attachments: Attachment[] = []
      files?.forEach(file => {
        const extraMetaData: Record<string, string> = {}
        extraMetaData["thumbnailMetaData"] = file.videoThumbnail ?? ""

        attachments.push({
          fileName: file.name,
          fileId: file.fileId,
          type: file.type,
          format: file.extension,
          path: file.blob,
          height: file.height,
          width: file.width,
          extraMetaData: extraMetaData
        })
      })

      this.store.messages.update(value => [...value, {
        author: {
          userid: session.userData.userid,
          pfp: session.userData.pfp,
          username: session.userData.username,
          displayName: session.userData.displayName
        },
        msgid: "",
        message: message,
        sent_at: {
          T: 0,
          I: 0
        },
        isEdited: false,
        channelId: "",
        networkId: "",
        categoryId: "",
        files: [],
        seen: false,
        replyTo: "",
        replyToId: "",
        forwardedFrom: "",
        forwardedFromName: ""
      }])

      this.scrollToBottom("smooth")

      await this.store.service.sendMessage("", message, null, null, files, <FileUploadProgressListener>{
        fileProgressUpdate: (tempMsgId, fileId, allChunks, chunksDone) => {
          this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone)
        }
      })
    }

    this.store.messageBox.message.set("")
  }

  async deleteMessage(messageId: string) {
    if (!this.store) return
    const i = this.store.messages().findIndex(m => m.msgid == messageId)
    if (i != -1) {
      const originalMessage: Message = JSON.parse(JSON.stringify(this.store.messages()[i]))
      this.store.messages().splice(i, 1)
      try {
        await this.store.service.deleteMessages([messageId])
      } catch (e) {
        this.store.messages().splice(i, 0, originalMessage)
      }
    }
  }

  scrollToBottom(anim: 'instant' | 'smooth'): void {
    setTimeout(() => {
      const scrollContainer = <HTMLDivElement>document.querySelector("#scrollContainer")
      scrollContainer.scroll({
        top: scrollContainer.scrollHeight,
        left: 0,
        behavior: anim
      });
    }, 0)
  }

  uploadProgressUpdate(tempMsgId: string, fileId: string, allChunks: number, chunksDone: number) {
    console.log(fileId, allChunks, chunksDone)
  }

  // The chatid parameter ensures isolation
  onWsListen(action: string, message: string, networkId: string, channelId: string) {
    const data = JSON.parse(message);
    if (data.channelId === channelId) {
      const targetStore = this.serviceManager.networkServices()[networkId].textChannels()[channelId];
      if (targetStore) {
        switch (action) {
          case "newMessage":
            targetStore.messages.update(messages => [...messages, data]);
            this.scrollToBottom("smooth")
            break;
        }
      }
    }
  }

  ngOnInit() {
    this.route.params.subscribe(async params => {
      const networkId = params['networkId'];
      const categoryId = params['categoryId'];
      const channelId = params['channelId'];
      this.networkId = networkId;
      this.categoryId = categoryId;
      this.channelId = channelId;

      const session = this.serviceManager.currentSession();
      const networkData = this.serviceManager.networks().find(c => c.networkId === networkId);

      if (!session || !networkData) {
        console.warn("No network data")
        return
      }

      const categoryData = networkData.categories.find(c => c.categoryId === categoryId);
      if (!categoryData) {
        console.warn("No category data")
        return
      }
      const channelData = categoryData.channels.find(c => c.channelId === channelId);
      if (!channelData) {
        console.warn("No channel data")
        return
      }
      if (!this.serviceManager.networkServices()[networkId]) {
        console.warn("No networkService")
        return
      }
      console.log(this.serviceManager.networkServices())
      console.log(this.serviceManager.networkServices()[networkId])
      if (!this.serviceManager.networkServices()[networkId].textChannels()[channelId]) {
        const newStore = {
          categoryData: signal(categoryData),
          channelData: signal(channelData),
          messages: signal<Message[]>([]),
          messageBox: new MessageBoxViewModel((msg, files) => this.sendMessage(msg, files)),
          wsListener: (action, data) => this.onWsListen(action, data, networkId, categoryId),
        } as TextChannelStorage;

        newStore.service = new TextChannelServiceService(
          session.userData.userid,
          session.token,
          networkId,
          categoryId,
          channelId,
          this.indexedDb.getApi(),
          (action, data) => newStore.wsListener(action, data)
        );

        this.serviceManager.networkServices()[networkId].textChannels()[channelId] = newStore;

        const currentStore = this.serviceManager.networkServices()[networkId].textChannels()[channelId]
        const history = await currentStore.service.get();
        currentStore.messages.set(history);
        this.scrollToBottom("instant")

        await currentStore.service.joinWebSocketRoom();
      }
    });
  }
}
