<template>
  <div class="sm-direct">
    <Row :gutter="24">
      <Col
        :span="16"
        :offset="4"
      >
        <Card
          class="sm-direct__card"
          :bordered="false"
        >
          <div
            slot="title"
            class="sm-direct__card-title"
          >
            <Icon
              type="ios-pulse"
              size="18"
            />
            <span>{{ $t('SHOPEE_AUTO_SEND_MESSAGE_STATUS') }}</span>
          </div>

          <div class="sm-direct__status">
            <Row :gutter="16">
              <Col :span="8">
                <div class="sm-direct__stat">
                  <div class="sm-direct__stat-label">
                    {{ $t('SHOPEE_AUTO_SEND_MESSAGE_CONNECTION') }}
                  </div>
                  <div class="sm-direct__stat-value">
                    <Tag
                      :color="socketChat.connected ? 'success' : 'error'"
                      class="sm-direct__tag"
                    >
                      <Icon
                        :type="socketChat.connected ? 'ios-checkmark' : 'ios-close'"
                        size="14"
                      />
                      <span class="sm-direct__tag-text">
                        {{ socketChat.connected ? $t('CONNECTED') : $t('DISCONNECTED') }}
                      </span>
                    </Tag>
                  </div>
                </div>
              </Col>

              <Col :span="8">
                <div class="sm-direct__stat">
                  <div class="sm-direct__stat-label">
                    {{ $t('SHOPEE_AUTO_SEND_MESSAGE_CONNECTED_TIME') }}
                  </div>
                  <div class="sm-direct__stat-value">
                    <span class="sm-direct__stat-text">
                      {{ socketChat.timeConnected ? formatTime(socketChat.timeConnected) : '-' }}
                    </span>
                  </div>
                </div>
              </Col>

              <Col :span="8">
                <div class="sm-direct__stat">
                  <div class="sm-direct__stat-label">
                    {{ $t('SHOPEE_AUTO_SEND_MESSAGE_MESSAGES') }}
                  </div>
                  <div class="sm-direct__stat-value">
                    <Badge
                      :count="logChat.length"
                      type="primary"
                      class="sm-direct__badge"
                    />
                  </div>
                </div>
              </Col>
            </Row>

            <div
              v-if="socketChat.error"
              class="sm-direct__error"
            >
              <Alert
                type="error"
                :title="$t('SHOPEE_AUTO_SEND_MESSAGE_ERROR')"
                :description="socketChat.error"
                show-icon
              />
            </div>
          </div>
        </Card>

        <Card
          class="sm-direct__card sm-direct__card--log"
          :bordered="false"
        >
          <div
            slot="title"
            class="sm-direct__card-title"
          >
            <Icon
              type="ios-chatbubbles"
              size="18"
            />
            <span>{{ $t('SHOPEE_AUTO_SEND_MESSAGE_LOG') }}</span>
            <Badge
              :count="logChat.length"
              type="primary"
            />
          </div>

          <div class="sm-direct__log">
            <div
              v-if="logChat.length === 0"
              class="sm-direct__empty"
            >
              <Icon
                type="ios-chatbubbles-outline"
                size="48"
                class="sm-direct__empty-icon"
              />
              <p class="sm-direct__empty-text">
                {{ $t('SHOPEE_AUTO_SEND_MESSAGE_NO_MESSAGES') }}
              </p>
            </div>

            <div
              v-else
              class="sm-direct__messages"
            >
              <div
                v-for="(message, index) in logChat"
                :key="index"
                class="sm-direct__message"
              >
                <div class="sm-direct__message-header">
                  <Icon
                    type="ios-person"
                    size="16"
                  />
                  <span class="sm-direct__message-sender">{{ message.sender_name || 'Unknown' }}</span>
                  <span class="sm-direct__message-time">{{ formatTime(message.timestamp) }}</span>
                </div>
                <div class="sm-direct__message-content">
                  {{ message.content || message.text || 'No content' }}
                </div>
              </div>
            </div>
          </div>
        </Card>
      </Col>
    </Row>
  </div>
</template>
<script>
import { sendChatMessage } from '@/api/shopee/seller/chat/index';
import { socketConnectChat } from '@/api/shopee/seller/chat/socket';
import { loggerShopee } from '@/plugins/logger';

export default {
  name: 'ShopeeAutoReplyReview',
  data() {
    /** @type {ShopeeWebchatSocketMessage[]} */
    const logChat = [];

    return {
      socketChat: {
        timeConnected: null,
        timeDisConnected: null,
        connected: false,
        disconnected: false,
        error: null,
      },
      logChat,
    };
  },
  methods: {
    /**
     * Format time to readable string
     * @param {Date|string|number} time
     * @returns {string}
     */
    formatTime(time) {
      if (!time) {
        return '-';
      }

      const date = new Date(time);
      return date.toLocaleString('vi-VN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      });
    },

    /**
     * Handle new message from socket
     * @param {ShopeeWebchatSocketMessage} chatData
     */
    onNewMessage(chatData) {
      loggerShopee.info({
        msg: 'SHOPEE_CHAT_NEW_MESSAGE_RECEIVED',
        chatData,
      });
      this.logChat.push(chatData);
    },

    /**
     * Start listening to socket connection
     */
    startListenSocket() {
      socketConnectChat(
        this.onNewMessage,
        () => {
          this.socketChat.connected = true;
          this.socketChat.timeConnected = new Date();
          this.socketChat.error = null;
        },
        (error) => {
          this.socketChat.disconnected = true;
          this.socketChat.timeDisConnected = new Date();
          this.socketChat.error = error;
        },
      );
    },
  },
  created() {
    this.startListenSocket();
    if (false) {
      const toUserId = 1201756367;
      const toShopId = 792026147;
      const text = 'Xin chào quý khách, cảm ơn bạn đã ghé thăm cửa hàng của chúng tôi. Chúc bạn có một ngày tốt lành!';
      sendChatMessage(toUserId, toShopId, text)
        .then((response) => {
          loggerShopee.info({
            msg: 'SHOPEE_CHAT_MESSAGE_SENT',
            response,
          });
        })
        .catch((error) => {
          loggerShopee.error({
            msg: 'SHOPEE_CHAT_SEND_MESSAGE_ERROR',
            error,
          });
        });
    }
  },
};
</script>

<style lang="scss" scoped>
@import '@/vue/styles/tokens.scss';

.sm-direct {
  padding: 24px 0;

  &__card.ivu-card {
    background: $c-surface;
    border-radius: $radius-card;
    box-shadow: $shadow-card;

    &--log {
      margin-top: 24px;
    }
  }

  &__card-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 15px;
    font-weight: 600;
    color: $c-text-strong;
  }

  &__status {
    padding: 16px 0;
  }

  &__stat {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    padding: 16px;
    background: $c-surface-soft;
    border: 1px solid $c-border;
    border-radius: $radius-item;
  }

  &__stat-label {
    font-size: 13px;
    font-weight: 500;
    color: $c-text-muted;
  }

  &__stat-value {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  &__tag.ivu-tag {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-weight: 600;
    border-radius: $radius-pill;
  }

  &__stat-text {
    font-size: 14px;
    font-weight: 500;
    color: $c-text-strong;
  }

  &__badge {
    font-size: 16px;
  }

  &__error {
    margin-top: 16px;
  }

  &__log {
    max-height: 400px;
    overflow-y: auto;
    @include scrollbar;
  }

  &__empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    padding: 48px 24px;
    color: $c-text-placeholder;
  }

  &__empty-icon {
    color: $c-border-strong;
  }

  &__empty-text {
    margin: 0;
    font-size: 14px;
  }

  &__messages {
    max-height: 300px;
    overflow-y: auto;
    @include scrollbar;
  }

  &__message {
    padding: 12px;
    border-bottom: 1px solid $c-border;
    border-radius: $radius-item;
    transition: background $motion-fast;

    &:hover {
      background: $c-surface-soft;
    }

    &:last-child {
      border-bottom: none;
    }
  }

  &__message-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
  }

  &__message-sender {
    font-size: 14px;
    font-weight: 600;
    color: $c-text-strong;
  }

  &__message-time {
    margin-left: auto;
    font-size: 12px;
    color: $c-text-muted;
  }

  &__message-content {
    font-size: 14px;
    line-height: 1.5;
    color: $c-text;
    word-break: break-word;
  }
}
</style>
